How to Insert MySQL Text With Single Quotes in PHP

When inserting data into a MySQL database using PHP, place the values that are to be inserted between single quotes. If the values themselves include a single quote, or apostrophe, the correct value will not be inserted into the database. The PHP "mysql_real_escape_string" function escapes any single quotes found within a text string. It does this by adding a backslash (/) before the single quote. This allows the single quote to be seen as part of the value string and inserted correctly.

Instructions

    • 1

      Open a blank plain text document.

    • 2

      Type the line

      <?php

      to begin the PHP script.

    • 3

      Type the lines

      $username="username";
      $passwd = "password";
      $database = "test";
      $table = "table_name";
      $server="localhost";

      to create the variables that contain the database information. Replace the words in quotations with the values for your database.

    • 4

      Type the lines

      mysql_connect($server,$username,$passwd);
      @mysql_select_db($database) or die ("Unable to select database");

      to connect to the MySQL database.

    • 5

      Type the lines

      $fname = "Lee";
      $lname = "O'Toule";
      $username = "lotoule";

      to create the variables that contain the values that will be inserted into the database. In this example, the last name "O'Toule" contains a single quote, or apostrophe.

    • 6

      Type the lines

      $query = "INSERT INTO ".$table." VALUES('".$f_name."','".$l_name."','".$u_name."');";
      echo $query.PHP_EOL;
      mysql_query($query);

      to create the INSERT query, print it to the screen and send the query to the database. Printing it to the screen shows you that the mysql_real_escape_string function has placed a backslash (\) before the apostrophe.

    • 7

      Type the lines

      $query2="SELECT * FROM ".$table.";";
      $result=mysql_query($query2);
      $num=mysql_numrows($result);
      mysql_close();

      to send the SELECT query that will return the results to the database, count the number of rows in the results and close the database connection.

    • 8

      Type the lines

      $i=0;
      while ($i < $num) {
      $first = mysql_result($result,$i,'fname');
      $last=mysql_result($result,$i,'lname');
      $user=mysql_result($result,$i,'username');
      echo $first." ".$last." ".$user.PHP_EOL;
      $i++;
      }

      to loop through the results and print each record to the screen.

    • 9

      Type the line

      ?>

      to close the PHP script.

    • 10

      Save the file with the ".php" file extension.

Related Searches:

References

Resources

Comments

Related Ads

Featured