How to put a PHP Variable into output of a SQL Query
Ok, I am querying my DB for a file. And I want to use a PHP global variable and stick it somewhere in that output using sa开发者_如何学编程y a '$dir' in my table. Any possible way to do so?
Just use it in a string for the query like you would in any other string. eg:
$sql = "UPDATE TABLE x SET dir=" . $dir . " WHERE id=" . $id;
Though if you do this and your variables use user input it's VERY IMPORTANT to sanitize them against SQL injection and such. The function mysql_real_escape_string()
is provided for just such instances.
$sql = "UPDATE TABLE x SET dir=" . mysql_real_escape_string($dir) . " WHERE id=" . mysql_real_escape_string($id);
$query = "SELECT '" . $dir . "' as myVariable, userName, userpassword from users where userName = ...."
The first reply was missing some quotes:
$sql = "UPDATE TABLE x SET dir=" . $dir . " WHERE id=" . $i
->
$sql = "UPDATE TABLE x SET dir='" . mysql_real_escape_string($dir) . "' WHERE id=" . $i
and
$sql = "UPDATE TABLE x SET dir=" . mysql_real_escape_string($dir) . " WHERE id=" . mysql_real_escape_string($id);
->
$sql = "UPDATE TABLE x SET dir='" . mysql_real_escape_string($dir) . "' WHERE id=" . mysql_real_escape_string($id);
精彩评论