PHP, making MySQL statements and the use of quotes
Question by jel402
After setting up a mysqli object in php, i want to make to insert some POST variables into a table, but I have a question about how the quotes will work out:
$sql = "INSERT INTO whatever (a, b, c)
VALUES ('$_POST[a]','$_POST[b]','$_POST[c]')";
I’m aware, however, that most times I’ve used global variables like POST or GET, there are quotes around the variable name — my question is do I have to so in the sql statement above? Should I then escape single or double quotes around those variable names? Not sure if quotes are even necessary…
Answer by KennyTM
Since you are using MySQLi already, why not use a prepared statement?
if ($stmt = $mysqli->prepare('INSERT INTO whatever (a,b,c) VALUES (?,?,?)') {
$stmt->bind_param('sss', $_POST['a'], $_POST['b'], $_POST['c']);
....
This will take care of the quotes for you automatically and securely (against SQL injection).
See http://www.php.net/manual/en/mysqli-stmt.bind-param.php for example usage.
Answer by Starx
Quotes primarily means to group something, either string or something else. For example you are inserting Hello I am someone to the database then your query would be like this INSERT INTO tables VAlueS (Hello I am someone, other data, again another data)
this will not clarify your parameters.
Escaping the quotes are good option, but only if you are using the same quotes inside a quote for example
$sql = "INSERT INTO whatever (a, b, c)
VALUES ("$_POST[a]","$_POST[b]","$_POST[c]")";
In this case, it will render error, so you have to escape your quotes.