March 31, 2012
MySql php: check if Row exists
Question by Jeff
This is probably an easy thing to do but I’m an amateur and things just aren’t working for me.
I just want to check and see if a row exists where the $lectureName shows. If a row does exist with the $lectureName somewhere in it, I want the function to return “assigned” if not then it should return “available”. Here’s what I have. I’m fairly sure its a mess. Please help.
function checkLectureStatus($lectureName)
{
$con = connectvar();
mysql_select_db("mydatabase", $con);
$result = mysql_query("SELECT * FROM preditors_assigned WHERE lecture_name='$lectureName'");
while($row = mysql_fetch_array($result));
{
if (!$row[$lectureName] == $lectureName)
{
mysql_close($con);
return "Available";
}
else
{
mysql_close($con);
return "Assigned";
}
}
When I do this everything return available, even when it should return assigned.
Answer by quickshiftin
This ought to do the trick: just limit the result to 1 row; if a row comes back the $lectureName
is Assigned, otherwise it’s Available.
function checkLectureStatus($lectureName)
{
$con = connectvar();
mysql_select_db("mydatabase", $con);
$result = mysql_query(
"SELECT * FROM preditors_assigned WHERE lecture_name='$lectureName' LIMIT 1");
if(mysql_fetch_array($result) !== false)
return 'Assigned';
return 'Available';
}
Answer by Starx
Use mysql_num_rows(), to check if rows are available or not
$result = mysql_query("SELECT * FROM preditors_assigned WHERE lecture_name='$lectureName' LIMIT 1");
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
// do something
}
else {
// do something else
}