[英]How to use a variable in PHP that store in SQL query in database
I stored my SQL query in database and at this query i used PHP variable;我将我的 SQL 查询存储在数据库中,在这个查询中我使用了 PHP 变量; then when i fetch the data from MySQL the variable which used in query does not work and query die!
然后当我从 MySQL 获取数据时,查询中使用的变量不起作用并且查询死了! what should i do?
我该怎么办?
Exp: I stored this query on database: Exp:我将此查询存储在数据库中:
"SELECT * FROM mytable WHERE id='$id' OR name='$name'"
and then when fetch this query the variables does not work in code like this:然后当获取这个查询时,变量在这样的代码中不起作用:
mysqli_query($conn,$sql)
or或者
mysqli_query($conn,"$sql")
mysqli_query - Performs a query on the database
mysqli_fetch_array - Fetch a result row as a numeric array and as an associative array
try following code to fetch data尝试以下代码来获取数据
$sql= mysqli_query($coni, "SELECT * FROM mytable WHERE id='$id' OR name='$name'");
$info = mysqli_fetch_array($sql)
You have to use mysqli_fetch_array()
after executing mysqli_query()
.执行
mysqli_query()
后必须使用mysqli_fetch_array()
mysqli_query()
。 The following code will print all rows matching your query.以下代码将打印与您的查询匹配的所有行。
$result = mysqli_query($conn, $sql);
while($row=mysqli_fetch_array($result)){
print_r($row);
}
If that does not work.如果那不起作用。 Be sure that you have the correct link to the database
确保您拥有正确的数据库链接
$conn= mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
More info about mysqli_connect can be seen in the documentation .有关 mysqli_connect 的更多信息可以在文档中看到。
But it is more safe to use the PDO(PHP Database Object), beacuse it gives a better layer of security with prepared statements .但是使用 PDO(PHP 数据库对象)更安全,因为它为准备好的语句提供了更好的安全层。
There is a tutorial about PDOs .有一个关于 PDO的教程。 Look at it for more details.
查看它以获取更多详细信息。 For even more details refer the PDO documentaion .
有关更多详细信息,请参阅PDO 文档。
One of the problems of storing a statement as you have in the database is that it assumes that there are variables called $id
and $name
in scope at the time you execute the statement.将语句存储在数据库中的问题之一是它假设在执行语句时在作用域中有名为
$id
和$name
变量。 If instead you used prepared statements and place holders, you can bind the values you need at the time you run the statement.如果改为使用准备好的语句和占位符,则可以在运行语句时绑定所需的值。
So your statement would be...所以你的说法是...
"SELECT * FROM mytable WHERE id=? OR name=?"
You would then run it using然后你会使用它运行它
$stmt = mysqli_prepare($conn,$sql);
mysqli_stmt_bind_param($stmt, "ss", $id1, $searchNname);
mysqli_stmt_execute($stmt);
// Process data as you need to
(Still not convinced that holding these statements in the database is a good idea, but that is up to you.) (仍然不相信将这些语句保存在数据库中是个好主意,但这取决于您。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.