Best practice: MySQL insert and $_SESSION var

Hey guys, girls,

I know of 3 ways to insert $_SESSION, $_POST, $_GET data into MySQL.
The question is, which is the best (speed and security).

Assuming that I’ve already escaped the data to secure against SQL Injection, which would be the best:

$var = $_SESSION['var'];
$result = mysqli_query($link, "INSERT INTO table (var) VALUES ($var)");
$result = mysqli_query($link, "INSERT INTO table (var) VALUES ('$_SESSION[var]')");
$result = mysqli_query($link, "INSERT INTO table (var) VALUES ('".$_SESSION['var']."')";

Are you looking to store sessions in a database?

Using prepare statements would be a better alternative as that makes sure that mySQL can tell what is the insert command and what is the data to be inserted more easily (and makes it harder for someone to find a way to trick the database into running their own commands.

All of them are pretty much equivalent. What ever floats your boat. Some situations may call for one, others two or three, but in the end they are really all the same. It would be hard to say which is more appropriate without a concrete problem, as the problem dictates the most appropriate action. Your really asking best practice for embedding variables in strings, which can differ based on situation at hand. Generally it either comes down what is more readable, manageable or simple. I myself prefer sprintf() as it separates the data from string making the code more readable, but unless many variables are being dealt with sprintf() normally makes things more complex than they need to be. It just all depends on the situation. Although, your likely to be graced with the prepared statement argument since your using mysqli in this case anyway. So it would make sense to use prepared statements rather than embed the variables directly into the query sting. I’ll leave that one though for someone else to explain or you could look at the docs, if your feeling anxious.