[php] Check if a row exists using old mysql_* API

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.

This question is related to php mysql

The answer is


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
}

function checkLectureStatus($lectureName) {
  global $con;
  $lectureName = mysql_real_escape_string($lectureName);
  $sql = "SELECT 1 FROM preditors_assigned WHERE lecture_name='$lectureName'";
  $result = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
  if (mysql_fetch_row($result)) {
    return 'Assigned';
  }
  return 'Available';
}

however you have to use some abstraction library for the database access.
the code would become

function checkLectureStatus($lectureName) {
  $res = db::getOne("SELECT 1 FROM preditors_assigned WHERE lecture_name=?",$lectureName);
  if($res) {
    return 'Assigned';
  }
  return 'Available';
}

If you just want to compare only one row with $lactureName then use following

function checkLectureStatus($lectureName)
{
 $con = connectvar();
 mysql_select_db("mydatabase", $con);
 $result = mysql_query("SELECT * FROM preditors_assigned WHERE lecture_name='$lectureName'");
  if(mysql_num_rows($result) > 0)
  {
         mysql_close($con);
         return "Assigned";
  }
  else
  {
        mysql_close($con);
        return "Available";
  }
}

$result = mysql_query("select if(exists (SELECT * FROM  preditors_assigned WHERE lecture_name='$lectureName'),'Assigned', 'Available')");

Easiest way to check if a row exists:

$lectureName = mysql_real_escape_string($lectureName);  // SECURITY!
$result = mysql_query("SELECT 1 FROM preditors_assigned WHERE lecture_name='$lectureName' LIMIT 1");
if (mysql_fetch_row($result)) {
    return 'Assigned';
} else {
    return 'Available';
}

No need to mess with arrays and field names.