gpt4 book ai didi

PHP FetchAll() 不返回行

转载 作者:行者123 更新时间:2023-11-29 18:35:35 25 4
gpt4 key购买 nike

我想知道是否有人可以帮助阐明为什么这段 PHP 代码没有进入 for 循环?在 MySQL 中,查询返回我需要的相应行,但在这个 PHP 文件中,它无法将任何内容返回到数组中,因此不执行 foreach 循环。

代码

<?php

try {
$sql = 'SELECT FirstName,LastName ';
$sql .= 'FROM adventureworks.employeedepartmenthistory ';
$sql .= 'JOIN employee USING(EmployeeID) ';
$sql .= 'JOIN contact USING(ContactID) ';
$sql .= 'WHERE DepartmentID = 2';
$stmt = $dbh->prepare($sql);
$stmt->execute();
echo $sql;
echo '<ul>';

foreach ($stmt->fetchAll() as $emps){
echo "<li>" . $emps["FirstName"] . $emps["LastName"] . "</li>";
}

echo '</ul>';

$stmt = null;
}
catch (Exception $e) {
echo "Error";
echo $e->getMessage();
}


?>

我什至让程序回显 SQL 查询,然后将其复制到 MySQL 中,它仍然有效。这可能是一个简单的语法错误,还是我正在执行的表连接?

我还确信该程序正在正确联系数据库,因为我还有其他类似的 PHP 文件可以正常工作,如下所示:

<?php

try {
$sql = 'SELECT department.Name FROM adventureworks.department';
$stmt = $dbh->prepare($sql);
$stmt->execute();

echo '<ul>';

foreach ($stmt->fetchAll() as $depts) {
echo "<li>" . $depts["Name"] . " -> (" .
"<a href='deptEmps.php?deptID=" . $depts['deptID']
. "'>Employees </a>)" . "</li>\n";
}

echo '</ul>';

$stmt = null;
}
catch (Exception $e) {
echo "Error";
echo $e->getMessage();
}


?>

最佳答案

PHP 脚本的问题是我没有指定要从哪些表中进行选择。这比它应该做的更难,因为上面的语法在 MySQL(我正在访问的数据库)中返回数据,可以在下面找到正在运行的正确 PHP 脚本:

工作 PHP:

<?php

try {
$sql = 'SELECT contact.FirstName,contact.LastName ';
$sql .= 'FROM adventureworks.employeedepartmenthistory ';
$sql .= 'JOIN adventureworks.employee USING(EmployeeID) ';
$sql .= 'JOIN adventureworks.contact USING(ContactID) ';
$sql .= 'WHERE DepartmentID = 2';
$stmt = $dbh->prepare($sql);
$stmt->execute();
echo $sql;
echo '<ul>';

foreach ($stmt->fetchAll() as $emps){
echo "<li>" . $emps["FirstName"] . $emps["LastName"] . "</li>";
}

echo '</ul>';

$stmt = null;
}
catch (Exception $e) {
echo "Error";
echo $e->getMessage();
}


?>

我错误地认为这些表是通过 PHP 中的 JOIN 假设的,就像它们在 MySQL 中一样。

关于PHP FetchAll() 不返回行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45335332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com