Public Function NameIsOnFile($studentname) {
$sql = "SELECT COUNT(*) FROM studentlist WHERE name = '{$studentname}'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result, MYSQL_NUM);
if($row[0] > 0) { // student name is on file
return true;
}
return false;
} // end function
Is there an easier / less resource intensive way to accomplish this? (studentid is the key to this table, not name).
I’ve done a search in this forum, but must not be using the right keywords.
Public Function NameIsOnFile($studentname) {
$sql = "SELECT COUNT(*) FROM studentlist WHERE name = '{$studentname}'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0) { // student name is on file
return true;
}
return false;
} // end function
Ideally you should stop using the function mysql_query, mysql_num_rows etc as they are being phased out, check these instead http://php.net/manual/en/book.pdo.php
Depending on what you want to do, you could also create a unique index on ‘name’, do an insert, and then handle the duplicate key error if the name already exists.
Thanks guys. That sounds like the better approach. I have my validation packaged in a separate function within my class than the database maintenance (Insert/Update). As such, got into a bit of tunnel vision.
Not better at all considering mysql_num_rows() will always return a single row given the query. That function will never return false. Removing the aggregate function would fix it.