简体   繁体   English

如何将PHP变量放入SQL查询的输出中

[英]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 say a '$dir' in my table. 我想使用PHP全局变量,并在表中使用“ $ dir”将其粘贴在输出中。 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. 尽管如果执行此操作,并且变量使用用户输入,则非常重要的一点是要针对SQL注入等对它们进行清理。 The function mysql_real_escape_string() is provided for just such instances. 仅为此类实例提供了函数mysql_real_escape_string()

$sql = "UPDATE TABLE x SET dir=" . mysql_real_escape_string($dir) . " WHERE id=" . mysql_real_escape_string($id);

$query = "SELECT '" . $ query =“ SELECT'”。 $dir . $ dir。 "' as myVariable, userName, userpassword from users where userName = ...." “'作为myVariable,userName,来自userName = ...的用户的用户密码。”

The first reply was missing some quotes: 第一个答复缺少一些引号:

$sql = "UPDATE TABLE x SET dir=" . $ sql =“ UPDATE TABLE x SET dir =”。 $dir . $ dir。 " WHERE id=" . “ WHERE id =”。 $i $ i

-> ->

$sql = "UPDATE TABLE x SET dir='" . $ sql =“ UPDATE TABLE x SET dir ='”。 mysql_real_escape_string($dir) . mysql_real_escape_string($ dir)。 "' WHERE id=" . “'WHERE id =”。 $i $ i

and

$sql = "UPDATE TABLE x SET dir=" . $ sql =“ UPDATE TABLE x SET dir =”。 mysql_real_escape_string($dir) . mysql_real_escape_string($ dir)。 " WHERE id=" . “ WHERE id =”。 mysql_real_escape_string($id); mysql_real_escape_string($ id);

-> ->

$sql = "UPDATE TABLE x SET dir='" . $ sql =“ UPDATE TABLE x SET dir ='”。 mysql_real_escape_string($dir) . mysql_real_escape_string($ dir)。 "' WHERE id=" . “'WHERE id =”。 mysql_real_escape_string($id); mysql_real_escape_string($ id);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM