我目前在 MySQL 数据库中有 5 个表。其中一些共享外键并且相互依赖。我已经在 MySQL 中测试了查询,它运行良好。使用查询 php 时,它显示数据库 PDO 连接错误。另外,我不确定我的 PHP 是否会像我想要的那样打印结果。我该如何解决这两个问题?
PHP
<?
try {
$pdo = new PDO ("mssql:host=$hostname;dbname=$dbname","$username","$pw");
} catch (PDOException $e) {
echo "Failed to get DB handle: " . $e->getMessage() . "\n";
exit;
}
$query = $pdo->prepare("SELECT course.id, major.name, course.name, course.code, course.description, course.hours, semester.semester, semester.year
FROM course
LEFT JOIN major_course_xref ON course.id = major_course_xref.course_id
LEFT JOIN major ON major.id = major_course_xref.major_id
LEFT JOIN course_semester_xref ON course.id = course_semester_xref.course_id
LEFT JOIN semester ON course_semester_xref.semester_id = semester.id");
$query->execute();
foreach ($pdo->query($query) as $row) {
print $row['id'] . "\t";
print $row['name'] . "\t";
print $row['name'] . "\n";
print $row['code'] . "\n";
print $row['description'] . "\n";
print $row['hours'] . "\n";
print $row['semester'] . "\n";
print $row['year'] . "\n";
}
unset($pdo);
unset($query);
?>
所需显示:
Computer Engeneering
Visual Studio I
CPE1900
Introduction to disciplined, object-oriented programming
4
Fall
2013
Rays 回答后更新:这是我现在得到的错误
Warning: PDO::query() expects parameter 1 to be string
Warning: Invalid argument supplied for foreach() in