Pinkie Pinkie - 1 year ago 70
PHP Question

How to include a PHP variable inside a MySQL insert statement

I'm trying to insert values in the contents table. It works fine if I do not have a PHP variable inside VALUES. When I put the variable

inside VALUES then this doesn't work. What am I doing wrong?

$type = 'testing';
mysql_query("INSERT INTO contents (type, reporter, description) VALUES($type, 'john', 'whatever')");

Answer Source

The rules of adding strings into a query are plain and simple:

  1. The string should be enclosed in quotes.
  2. Therefore, these quotes should be escaped in the data, as well as some other characters, using mysql_real_escape_string()

So, your code becomes

$type     = 'testing';
$type     = mysql_real_escape_string($type);
$reporter = "John O'Hara";
$reporter = mysql_real_escape_string($reporter);

$query    = "INSERT INTO contents (type, reporter, description) 
             VALUES('$type', '$reporter', 'whatever')";
mysql_query($query) or trigger_error(mysql_error()." in ".$query);
// note that when running mysql_query you have to always check for errors

But if you're going to add the variable in another part of a query, the rules change.

  • To add a number, you have to cast it to its type explicitly.

For example:

$limit = intval($_GET['limit']); //casting to int type!
$query = "SELECT * FROM table LIMIT $limit";
  • To add an identifier, it's better to choose it from some sort of white list, consists of hardcoded values

For example:

if ($_GET['sortorder'] == 'name') {
  $sortorder = 'name';
} else {
  $sortorder = 'id';
$query = "SELECT * FROM table ORDER BY $sortorder";

To make it all simplified yet with guaranteed safety, one have to use some sort of placeholder system where the variable goes into a query not directly but via some proxy, called a placeholder.

So, your query call becomes something like this:

$type     = 'testing';
$reporter = "John O'Hara";
pquery("INSERT INTO contents (type, reporter, description) VALUES(?s, ?s, ?s)",
        $type, $reporter,'whatever');

And there will be absolutely no need to worry about all these matters.

For the limited set of placeholders you can use PDO. Though for real life usage you will need extended set which is offered by but a few libraries, one of which is SafeMysql.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download