好吧,我尝试使用第一个查询从psComputers表中获取计算机的所有名称。现在,我需要在第二个查询中从第一个查询中获取一个变量,以迭代在psTest表中分配给相应计算机的所有条目。我不知道这样的事情有可能吗?
表psComputer包含ID
,name
表格psTest包含ID
,computername
,category
,value
index.php
$statement = $pdo->prepare("SELECT * FROM psComputers ");
$statement->execute();
$result = $statement->fetchAll();
if ($statement->rowCount() > 0) {
foreach ($statement->fetchAll() as $row) {
$id = $row['ID'];
$name = $row['name'];
$statement2 = $pdo->prepare("SELECT * FROM psTest WHERE computerName = $name");
$statement2->execute();
$result2 = $statement2->fetchAll();
if ($statement2->rowCount() > 0) {
foreach ($statement2->fetchAll() as $row2) {
$id2 = $row2['ID'];
$computerName = $row2['computerName'];
$category = $row2['category'];
$value = $row2['value'];
}
}
}
}
答案 0 :(得分:3)
需要注意的几件事
private void updateExcel_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
dataGridView1[2, i].Value = ConsigneeCombo.Text;
}
}
而不是循环运行查询。这还将删除名称中的变量,从而使以上两个注释都不相关! (您应注意这两者,但它们与所讨论的代码无关。)在循环中运行查询很少是个好主意。
JOIN
答案 1 :(得分:3)
在第二个查询中,您需要在$name
周围加上引号,因为它是一个字符串。
$statement2 = $pdo->prepare("SELECT * FROM psTest WHERE computerName = '$name'");
但是,由于您使用的是预先准备好的查询,因此应使用参数代替变量。
您也不应两次致电$statement->fetchAll()
。第一次调用将读取所有行,第二次调用将没有任何要读取的内容(它不会重置游标)。
$statement = $pdo->prepare("SELECT * FROM psComputers ");
$statement->execute();
$result = $statement->fetchAll();
if (count($result) > 0) {
$statement2 = $pdo->prepare("SELECT * FROM psTest WHERE computerName = :name");
$statement2->bindParam(':name', $name);
foreach ($result as $row) {
$id = $row['ID'];
$name = $row['name'];
$statement2->execute();
$result2 = $statement2->fetchAll();
if (count($result2) > 0) {
foreach ($result2 as $row2) {
$id2 = $row2['ID'];
$computerName = $row2['computerName'];
$category = $row2['category'];
$value = $row2['value'];
}
}
}
}
但是更好的方法是只加入两个查询:
$statement = $pdo->prepare("
SELECT c.id AS computerID, c.name AS computerName, t.id AS testID, t.category, t.value
FROM psComputers AS c
JOIN psTest AS t ON c.name = t.computerName
ORDER BY c.id");