[英]Placing a PHP variable in a MySQL query
I'm having issues placing a PHP variable in MySQL string, 我在将PHP变量放入MySQL字符串时遇到问题,
<?php
$con=mysqli_connect("***","***","***","***");
function getItem($itemNo)
{
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM products WHERE product_id = '$itemNo'");
echo $itemNo;
echo "<br>";
while($row = mysqli_fetch_array($result))
{
echo $row['product_id'] . " " . $row['product_name'];
echo "<br>";
}
}
getItem(1001);
mysqli_close($con);
?>
The page shows my echo of the $itemNo
, but thats all. 该页面显示了
$itemNo
回声,仅此$itemNo
。 If I just do select * from products
, it gives my entire table like it should, so I know the database is working, so I've narrowed it down to the placement of the variable. 如果我只是
select * from products
,它将像应该的那样提供我的整个表,因此我知道数据库正在工作,因此将其范围缩小到了变量的位置。
EDIT : 编辑 :
product_id
column is an int and also the primary key . product_id
列既是int也是主键 。
You can try a prepared statement to make using variables in your queries easier. 您可以尝试使用准备好的语句来简化查询中的变量使用。
$stmt = $con->prepare("SELECT * FROM products WHERE product_id=?");
$stmt->bind_param($itemNo);
$stmt->execute();
$stmt->close();
$result = mysqli_query($con,"SELECT * FROM products WHERE product_id = " .$itemNo );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.