0

When inserting into MySQL with PHP, I can do either of the following:

$query = 'INSERT INTO tablename SET id = "4"';
$query = "INSERT INTO tablename SET id = '4'";
$query = 'INSERT INTO tablename SET id = \'4\'';
$query = "INSERT INTO tablename SET id = \"4\"";

Is there a reason (security, performance, code readability, ...) why I should prefer one of them?

3 Answers3

0

That depends on situation, in your case it should be:

$query = 'INSERT INTO tablename (id) VALUES (4)';

In case that you would want to insert an integer and a string, it should be:

$query = "INSERT INTO tablename (id, name) VALUES (4, 'New York')";

In case that you would want to build query by directly inserting variables into the query, it should be:

$query = "INSERT INTO tablename (id, name) VALUES ($id, '$city')";

  • Building a query like this is prone to SQL injection.

In case that you would want to build query by using for example PDO library, it would be:

$query = 'INSERT INTO tablename (id, name) VALUES (:id, :city)';

  • I'll reserve the downvote in case you don't correct the answer, but you **can** do `INSERT INTO ... SET col = ...`. – Marcus Adams Apr 29 '14 at 16:10
  • @MarcusAdams Interesting, I have never ever seen such usage of `INSERT` statement. –  Apr 29 '14 at 16:13
  • Why would use single quotes on the first and last statements? – Marcus Adams Apr 29 '14 at 16:16
  • @MarcusAdams Because in case that I would use `""` then PHP interpreter would look for variables inside the string. –  Apr 29 '14 at 16:17
  • @MarcusAdams In case that I wrap string inside `""` and I don't use variables inside the string, then it is for readability purposes, `"Jake's mom"` is better readable then `'Jake\'s mom'`. –  Apr 29 '14 at 16:19
0

Like Martin Bean mentioned, it would be a good idea to use prepared statements:

$stmt = $con->prepare("INSERT INTO tablename SET id=?");
$stmt->bind_param(4);
$stmt->execute();
$stmt->close();
rmcfrazier
  • 444
  • 4
  • 8
0

I think that this is the most common format:

$query = "INSERT INTO tablename SET id = '4'";

So, you can easily come back and perform variable expansion like this:

$id = 4;
$table = "tablename";
$query = "INSERT INTO $table SET id = '$id'";

If the 4 is something passed in by the user, you would instead use parametrized queries and bind the parameter to avoid SQL injection:

$id = $_POST["id"];
$table = "tablename";
$stmt = $con->prepare("INSERT INTO $tablename SET id=:id");
$stmt->bindParam(":id", $id);
$stmt->execute();
Marcus Adams
  • 53,009
  • 9
  • 91
  • 143