i’m very new to using mysql with php, and here’s what i found online to retrieve my results:
$con = mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die("Cannot connect to the database");
$query = "SELECT ... FROM ... WHERE ID=5";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if ($num > 0 ) {
// do stuff
} else {
// inform user
}
mysql_close($con);
ID is my table’s autogenerated non-null primary key. right now, i have 20 records in my table. if i enter an ID value corresponding to any of these existing records, everything goes well and works as intended.
however, if i enter an ID value of, say, 54 or anything that doesn’t correspond to any of my existing 20 records (meaning no row with such an ID exists), i expect $num <= 0 and my conditional statement will go to the else block. but i found out that wasn’t the case – it still goes to the TRUE branch and proceeds to // do stuff block, so i ran the query on phpmyadmin and found out that i’m getting exactly 1 row with NULL in all of the fields. that’s why $num was returning 1 which is >0.
questions:
- how do i properly go about checking for nonexistent rows? so that the rest of my script will only run if i actually get a row that contains data.
- i found
mysql_store_resultandmysql_free_resultwhile researching this online but there’s not enough info to make them work properly. like where in my code do i place them, how come i can do what i need to do right now in php even without them, etc? - any “best practice” stuff i’m missing here when dealing with mysql databases in php?
- when i have to call several sql statements, what i do is cycle through the
$query–$result–$numprocess before imysql_closemy connection. is that “best practice”?
thank so much, guys, you’re all amazing.
UPDATE: Including whole query
SELECT Dyna,
Floater,
Can.Label as CanLabel,
GROUP_CONCAT(DISTINCT Vanity.Name SEPARATOR ', ') as VanityName,
GROUP_CONCAT(DISTINCT Univ SEPARATOR ', ') as Univ,
ShopDate,
ManuDate,
FlipTran,
Remarks,
Bib,
Abbrev,
ShopChar,
Comment,
Value,
ERUSD
FROM
(Vanity INNER JOIN ((Vanity INNER JOIN Shoppy ON Vanity.VanityID = Shoppy.VanityID) INNER JOIN ShoppyVanity ON Shoppy.ID = ShoppyVanity.ID) ON Vanity.MethodID = ShoppyVanity.MethodID) INNER JOIN UAC ON (Shoppy.VanityID = UAC.VanityID) AND (Vanity.VanityID = UAC.VanityID)
WHERE (((Shoppy.ID)=5))
If you use group aggregate functions such as
GROUP_CONCATMySQL will create a group out of your whole result set. If there are no results, it will run them onNULLvalues instead, resulting in an empty row. Try adding this to the very end of your query to get rid of rows that don’t have valid data in them:HAVING VanityName IS NOT NULL