I’m trying to take emails entered and check them against a database. If one already exists, finish carrying on the function but do not insert and notify the user. Here’s my test file:
<?php
require_once('class.database.php');
try {
$objDB = Database::instance();
} catch (Exception $e) {
echo $e->getMessage();
exit(2);
}
try {
$table = "users";
$objDB->insert($table, array('email' => 'me@example.com', 'password' => 'foo'));
$objDB->insert($table, array('email' => 'mean@example.com', 'password' => 'bar'));
$objDB->insert($table, array('email' => 'meanme@example.com', 'password' => 'foobar'));
$data = $objDB->select("SELECT * FROM users");
var_dump($data);
} catch (Exception $e) {
echo "Query failure" . NL;
echo $e->getMessage();
}
?>
And here’s the two functions:
function isValidEmail($field) {
$stmt = "SELECT email FROM users WHERE email = '$field'";
$result = mysql_query($stmt);
if(!(mysql_num_rows($result))) {
//duplicate
echo "<div id='duplicate' class='error'>NOT A VALID EMAIL: DUPLICATE: EMAIL EXISTS IN DATABASE<div>";
return(false);
};
return(true);
}
function insert($tableName, $arValues) {
$id = null;
$sFieldList = join(', ', array_keys($arValues));
$arValueList = array();
foreach($arValues as $value) {
if(strtolower($value) == '#id#') {
//we need to get the next value from this tables sequence
$value = $id = $this->conn->nextID($tableName . "_id");
}
$arValueList[] = $this->conn->quoteSmart($value);
$validEmail = $this->isValidEmail($arValueList);
}
$sValueList = implode(', ', $arValueList);
//make sure the table name is properly escaped
$tableName = $this->conn->quoteIdentifier($tableName);
$sql = "INSERT INTO $tableName ($sFieldList) VALUES ($sValueList)";
//Only INSERT if there are no duplicates
//If one exists, the Message is shown in function isValidEmail
if($validEmail) {
$result = $this->conn->query($sql);
}
if(DB::isError($result)) {
throw new Exception($result->getMessage(), $result->getCode());
}
//Return the ID if there was one, or return the number of affected rows
return $id ? $id : $this->conn->affectedRows();
}
It works to completion, just either inserts or doesn’t. I can’t make it differentiate whether the email exists or it doesn’t.
if(!(mysql_num_rows($result))) {
doesn’t Insert anything and:
if((mysql_num_rows($result))) {
inserts everything.
I have my logic wrong somewhere. Any help is appreciated.