2

我想将 foreach 转换为 if 语句,因为 mysql 查询只返回一行。所以我想使用 if 而不是 foreach

    $db = new db();
    $db -> serverconnection();

    $item = $_GET["name"];

    $query = "SELECT c.firstname,c.phonenumber,c.address FROM `order` o,customerdetails c WHERE o.ordercode = '$item' AND c.sno=o.customerid";

        $results = $db->selectQuery($query);


            foreach ($results as $customerdetails)
            {
                $orderidDetail = $customerdetails['customerid'];
                echo $customerdetails["firstname"];
                echo $customerdetails["phonenumber"];
                echo $customerdetails["address"];       
           }
4

3 回答 3

3

使用当前.

$customerdetails = current($results);
if($customerdetails)
    {
    $orderidDetail = $customerdetails['customerid'];
    echo $customerdetails["firstname"];
    echo $customerdetails["phonenumber"];
    echo $customerdetails["address"];       
    }
于 2013-07-08T16:33:12.263 回答
2

改变

foreach ($results as $customerdetails)
{
    $orderidDetail = $customerdetails['customerid'];
    echo $customerdetails["firstname"];
    echo $customerdetails["phonenumber"];
    echo $customerdetails["address"];       

}

if(isset($results[0]))
{
    $orderidDetail = $results[0]['customerid'];
    echo $results[0]["firstname"];
    echo $results[0]["phonenumber"];
    echo $results[0]["address"];       

}

于 2013-07-08T16:38:58.263 回答
0

就像是

if (count($results) == 1) { 
   ... single row of results ...
} else {
   foreach(...) { ... multiple rows ...}
}

也许?

但是,如果您知道查询只会返回一行,那么无论如何您根本不需要 if/foreach。

于 2013-07-08T16:34:42.453 回答