如何从php中的sql查询中检索单个值

时间:2016-01-15 07:48:39

标签: php mysql

我试图通过在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";
}

我无法理解我被困在哪里..如果有人能指出我的错误,那就太好了。感谢。

1 个答案:

答案 0 :(得分:0)

我已更新您的代码以添加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