Share on Google+Share on Google+

Php Sql Quotes and Quoting

Advertisement
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:

 

Advertisements

Posted on: December 10, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.