Php Sql Quotes and Quoting


 

Php Sql Quotes and Quoting

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

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  = "[email protected]";
  
  $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:

 

Ads