使用字段名称与fetch_all()回应 - php

时间:2014-04-02 19:49:13

标签: php

我想知道是否有人可以提供帮助。我对php很新,我遇到了一些语法问题。我有一个到SQL数据库的PDO连接,它工作正常,但我的问题是我只能在使用fetch_all()语句收集数据后使用数组地址进行回显。我可以使用字段名称回显吗?以下是导致问题的代码部分:

// connect to the database using the new more secure PDO method
$conn = new PDO('mysql:host=localhost;dbname=webauth', 'tim', 'password');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);   
$query="SELECT * FROM tbl_cust WHERE pk_cust_id=$custid;";  //'$custid'
$stmt = $conn->prepare($query);
$stmt->execute();
$names = $stmt->fetchAll();
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}

echo "<table border='2'> 
<tr>
<th>cust first</th>
<th>cust last</th>
</tr>";


  echo "<tr>";
  echo "<td>" . $names[0][2] . "</td>"; //this displays the second field correctly
  echo "<td>" . $names['cust_firstname'] . "</td>"; //just ignores this command - no error     though
  echo "</tr>";

echo "</table>";
echo $names[0][2];  //this does work and shows the firstname
echo $names->cust_firstname;  //this doesnt work - doesnt crash, but shows nothing     cust_firstname is the SQL field

提前谢谢。

2 个答案:

答案 0 :(得分:0)

如果将它声明为关联数组,它应该可以工作

$names = $stmt->fetch(PDO::FETCH_ASSOC);

然后输出以下内容

$names['cust_firstname']

答案 1 :(得分:0)

fetchAll返回一个数组,每个元素代表结果中的一行,如下所示:

[0] - First row
     array(
        'field1' => 'value',
        'field2' => 'value'
     )
     ...
[1] - Second row
     array(
        'field1' => 'value',
        'field2' => 'value'
     )

如果您确定只从查询中收到一行,则可以访问以下值:

$names[0]['your_field_name'];