获取SQL查询结果

问题描述:

我在那里看到有很多方法可以将SQL查询的结果转换为可用格式(即变量)。获取SQL查询结果

如果我有一个针对性的SQL查询,我知道他一定会返回一组预期值,可以说,查询客户号提取数据,城市,州,姓和名,等等。

代码例如如下:

$example = '50'; 
$result = mysql_query("SELECT * FROM customers WHERE customer_ID = '$example'",$db); 
while ($row = mysql_fetch_assoc($result)) { 
    foreach ($row as $col => $val) { 
    if ($col == 'firstname') { 
     $customerfirstname = $val; 
    } 
    } 
} 

或另一种方式:

$result = mysql_query("SELECT * FROM customers WHERE customer_ID = '$example'",$db); 
$myResultArray = array(); 

while ($row = mysql_fetch_assoc($result)) 
    $myResultArray = $row; 

    foreach ($myResultArray as $val) { 
    $customerfirstname = $val['firstname']; 
    } 

这只是两块我能想到的。

以上方法之一是否比另一方更好?如果是这样,为什么?

是否有另一种方法比这两种方法更有效?

+2

请用您正在使用的语言标记问题。 – Oded

两者都不是优选的。

foreach是多余的。

既然你知道你需要的字段名,你可以这样做:

while ($row = mysql_fetch_assoc($result)) { 
    $customerfirstname = $row['firstname']; 
} 

如果你需要申请有条件出于某种原因,你可以测试阵列中的字段的存在:

while ($row = mysql_fetch_assoc($result)) { 
    if (isset($row['firstname'])) { 
     $customerfirstname = $row['firstname']; 
    } 
} 

最后,因为你看上去由主键选择,while循环也是不必要:

if ($row = mysql_fetch_assoc($result)) { 
    $customerfirstname = $row['firstname']; 
} 

我已经使用了你在每个网站中提出的第一个例子,这个例子需要一个数据库,它并没有让我失败。至于如果一个比另一个好,我会说不。这只是一个品味问题。

有很多方法。这里是一个快速的,但我宁愿使用DTO进行设置,并以这种方式访问​​它......这将工作,虽然你的问题。

$query = "SELECT first_name, last_name, city FROM customers WHERE customer_id = '$example'"; 
$result = mysql_query($query); 

// If you are expecting only one row of data, then use this: 
list($first_name, $last_name, $city) = mysql_fetch_row($result); 

//several rows: 
while(list($first_name, $last_name, $city) = mysql_fetch_row($result)){ 
    echo $first_name; 
} 

我似乎失去了一些东西......

为什么不呢?

$result = mysql_query("SELECT * FROM customers WHERE customer_ID = '$example'",$db); 
while ($row = mysql_fetch_assoc($result)) { 
    $customerfirstname = $row['firstname']; 
} 

在第一个例子中?