I tried to execute the query, but the result was null, I executed the same query in PhpMyAdmin and returns the result.
The problem is when the query contains SELECT inside another SELECT statement (imbricate), so when the query contains only one SELECT statement, it works fine and returns the result. Here is the code:
db_config.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "university_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
get_planning.php
<?php
require 'db_config.php';
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT cours.jour,
TIME_FORMAT(cours.heure_debut, '%H:%i') AS debut,
TIME_FORMAT(cours.heure_fin, '%H:%i') AS fin,
enseignant.nom_ens as prof, modules.nom_mod as module, salles.nom_salle as salle
FROM cours, promotion, enseignant, modules, salles
WHERE cours.id_promo = (SELECT id_promo FROM promotion WHERE promotion.niveau = '2'
AND promotion.id_speci = (SELECT id_speci FROM spécialité WHERE nom_speci = 'MGL'))
AND cours.id_promo = promotion.id_promo AND cours.id_ens = enseignant.id_ens AND cours.id_salle = salles.id_salle AND cours.id_mod = modules.id_mod
ORDER BY cours.id_cours;";
$result = $conn->query($sql);
if($result == null)
echo "Result is empty!";
Output:
Result is empty!
Information:
- PHP: Version 7.3.5
- Database: MySQL
2
Answers
Three suggestions for troubleshooting this problem:
Change your
cours.id_promo = (SELECT ...
tocours.id_promo IN (SELECT...
and do the same to the line after it. Why? if you use=
and the inner select statement returns more than one result, boom. Query fails. SQL is, at its heart, a set-processing language, andthis IN that
checks thatthis
is a member of the setthat
.echo your
$sql
value to make sure the statement in it is correct. Try running the exact statement via phpmyadmin to make sure it gives you what you expect.You have this
Change it to this
The
query()
method only returns a falsey result if the query failed. If it succeeds but finds no matching rows,query()
returns an empty result set. So anytime your $result is falsey, you made a programming error in your query. Theecho
I mentioned will diagnose it for you.Pro tip Always check SQL operations for errors.
Pro tip 2. Bring your SQL skills into the 21st century. Use explicit join operations rather than old-timey comma-join operations. Change …
The relationships between your tables are much easier to read and understand this way. And, you can change
JOIN
toLEFT JOIN
if your application requires it.Just a suggestion.
Instead of nested old implicit join syntax based list table, where clause and nested sub-query should use explicit join syntax.