我尝试使用以下代码使用PDO,我想为context_list选择值数组,但它会返回一条记录,任何我想出错的想法?
FooBarData
部分解决方案:
这有效:
try {
$sql2 = "SELECT area_easting, area_northing, context_number FROM excavation.contexts";
$sth = $conn->prepare($sql2);
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC))
{
$easting_list = $row['area_easting'];
$northing_list = $row['area_northing'];
$context_list = $row['context_number'];
}
}
catch(PDOException $e )
{
echo "Error: ".$e;
}
echo "context list: ";
echo $context_list;
但是现在我需要让$ r-> area_easting可以访问会话,但这是另一个问题。
答案 0 :(得分:0)
您的查询可能会返回多条记录(前提是它们实际存在于表格中)
您的代码循环遍历所有记录(使用while
循环),但值($easting_list
,$northing_list
和$context_list
)将在循环中被覆盖。
我建议您对代码进行以下更改:
$easting_list = array();
$northing_list = array();
$context_list = array();
try {
$sql2 = "SELECT area_easting, area_northing, context_number FROM excavation.contexts";
$sth = $conn->prepare($sql2);
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC))
{
$easting_list[] = $row['area_easting'];
$northing_list[] = $row['area_northing'];
$context_list[] = $row['context_number'];
}
}
catch(PDOException $e )
{
echo "Error: ".$e;
}
echo "context list: ";
echo implode(', ', $context_list);
现在所有值都存储在3个数组中。 explode
用于打印$context_list
数组中所有值的逗号分隔列表。