将PHP变量放在MySQL查询中

时间:2014-04-21 06:28:32

标签: php mysql sql

我在将MySQL变量放入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);

?>

该页面显示了$itemNo的回声,但仅此而已。如果我只做select * from products,它会像我一样给出我的整个表格,所以我知道数据库正在运行, 所以我把它缩小到了变量的位置。

修改

product_id列是 int ,还有主键

2 个答案:

答案 0 :(得分:2)

您可以尝试使用预准备语句,以便更轻松地在查询中使用变量。

$stmt = $con->prepare("SELECT * FROM products WHERE product_id=?");
$stmt->bind_param($itemNo);
$stmt->execute();
$stmt->close();

答案 1 :(得分:1)

 $result = mysqli_query($con,"SELECT * FROM products WHERE product_id = " .$itemNo );