I currently have 5 tables in MySQL database. Some of them share foreign keys and are interdependent of each other. I have tested the query in MySQL and it works perfect. When using the query php it is displaying an error with database PDO connection. Also, I am not sure if my PHP will print the results like I am intending. How can I resolve these two issues?
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);
?>
Desired Display:
Computer Engeneering
Visual Studio I
CPE1900
Introduction to disciplined, object-oriented programming
4
Fall
2013
Update after Rays answer: This the error that I get now
Warning: PDO::query() expects parameter 1 to be string
Warning: Invalid argument supplied for foreach() in
The
execute()method returnsFALSEon error, orTRUEif successful. Then you need to fetch the rows one at a time.See: http://php.net/manual/en/pdostatement.execute.php and http://www.php.net/manual/en/pdostatement.fetch.php