如何在 PHP 中从 SQL 查询中检索单个值


how to retrieve a single value from sql query in php

我试图通过使用PHP中的sql查询从数据库中检索单个整数值来检查条件是否为真。这是代码 -

$stmt = $dbo->prepare("SELECT Qty FROM sample.stock WHERE stock_ID=$s_stock_ID AND component='$component' LIMIT 1");
if ($stmt->execute(array($_GET['Qty']))) 
{ 
   $Q = $_GET['Qty'];
   while ($row = $stmt->fetch()) 
   {
    print_r($row);
   } 
}
if($Qty <= $Q) // comparison of integers
    { 
     echo "success";
    }
else
{
 echo "failed";
}

我不明白我被困在这里的地方..如果有人能指出我的错误,那就太好了。谢谢。

我已经更新了您的代码以添加 Try/Catch 块。您还需要将 Qty 移动到 while 循环中。您可以将其作为对象或数组获取。在下面的示例中,我将其作为对象获取。

    $Q = $_GET['Qty'];
    $sql = "SELECT Qty FROM sample.stock WHERE stock_ID=$s_stock_ID AND component='$component' LIMIT 1";
    $stmt = $dbo->prepare( $sql );
    try {
        $stmt->execute( array($_GET['Qty']) );
        while ($row = $stmt->fetch(PDO::FETCH_OBJ)) 
        {
            if( $row->Qty <= $Q ) { 
                echo "success";
            } else {
                echo "failed";
            }
        }
    } catch (PDOException $e) {
        print $e->getMessage();
    }

http://php.net/manual/en/pdostatement.fetch.php