Question

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?

Was it helpful?

Solution

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();

OTHER TIPS

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();

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)';

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top