Home Tutorial Php Sql Php Sql Quotes and Quoting

 
 

Php Sql Quotes and Quoting
Posted on: December 10, 2010 at 12:00 AM
This example illustrates different ways to define single and double quotes in the php application with sql query.

Php Sql Quotes and Quoting

This example illustrates different ways to define single and double quotes in the php application with sql query.

By default, PHP uses "magic quoting". This means that any variable passed via POST, GET, or cookies, will have all single quotes turned into backslash single quotes. That is, for these variables, all ' characters get turned in \' as in the source code.

 

Table: users before insertion

Table: users after insertion

 

 

Source Code of sql_quotes.php 

<?php
  $con = mysql_connect("localhost","root","root");
  if (!$con) {
    die('Could not connect: ' . mysql_error());
  }

  mysql_select_db("test", $con);

  $user = "sum'an";
  $email  = "suman@email.com";
  
  $newuser = addslashes($user);

  $query = "INSERT INTO users (username, email) VALUES 
      ('$newuser', '$email')" or die(mysql_error()
;
  mysql_query($query);

  $result = mysql_query("SELECT * FROM users ORDER BY username desc");
  echo "<table border='1'>
    <tr>
      <th>Name</th>
      <th>Email</th>
    </tr>";
    while ($row = mysql_fetch_array($result)) {
      echo "<tr>";
      echo "<td>" . $row['username'] "</td>";
      echo "<td>" . $row['email'] "</td>";
      echo "</tr>";
    }
  echo "</table>";
  
  mysql_close($con);
?>

Download Source Code

 

Output:

 

Related Tags for Php Sql Quotes and Quoting:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.