PHP变量在查询中不求值

2022-02-21 00:00:00 search php mysqli

我是PHP和MySQL的新手,我就是搞不懂这一点。我在论坛里找遍了,但没有找到一个我能理解的答案。我最初使用的是mysql_fetch_assoc(),但是我只能搜索数字,并且在搜索字母时也收到错误。我希望我是在正确的轨道上。预先感谢您的所有帮助!

$con = mysqli_connect($hostname,$username,$password) or die ("<script language='javascript'>alert('Unable to connect to database')</script>");
mysqli_select_db($con, $dbname);

if (isset($_GET['part'])){
    $partid = $_GET['part'];
    $sql = 'SELECT * 
        FROM $usertable 
        WHERE PartNumber = $partid';

    $result = mysqli_query($con, $sql);
    $row = mysqli_fetch_assoc($result);

    $partnumber = $partid;
    $nsn = $row["NSN"];
    $description = $row["Description"];
    $quantity = $row["Quantity"];
    $condition = $row["Conditio"];
}

解决方案

当您的结果不是结果(而是"False")时会发生这种情况。 您应该更改此行

$sql = 'SELECT * FROM $usertable WHERE PartNumber = $partid';

至此:

$sql = "SELECT * FROM $usertable WHERE PartNumber = $partid";

因为"可以解释$Variables,而‘不能。"

适用于整数(数字),对于字符串,您需要将$Variable放在单引号中,如

$sql = "SELECT * FROM $usertable WHERE PartNumber = '$partid' ";

如果您想/必须使用单引号,那么php无法解释变量,您必须这样做:

 $sql = 'SELECT * FROM '.$usertable.' WHERE string_column = "'.$string.'" AND integer_column = '.$number.';

相关文章