Jump to content

Validation of form entry against entries in SQL database


erme

Recommended Posts

Hi

 

I'm trying to code something to validate a form entry against what is already in the database. I have an input of 'Name' and a field in the SQL db of 'NameDB'. I've got $error working for other things non db related.

 

$countsql = "SELECT * FROM Table";

$inter = mysql_query("$countsql");
while($r = mysql_fetch_array($inter))
{

	if ($Name == " . $r['NameDB'] . ") {
		$error.="Name already in database!<br />\n";
	}
}

<input type="text" id="Name" name="Name" value="<?=$Name;?>" />

 

Many thanks

You can try something like this

 

$countsql = "SELECT name FROM Table";

if (mysql_num_rows($countsql))
  {
    echo "Name already in database!< \n";
  }

 

.. i think you forgot the part of the query where you tell it WHAT name to pull out of the table. otherwise, it will simply return all names currently in the database.

 

if (isset($_POST['Name']))
{
  $query = "SELECT NameDB FROM Table WHERE NameDB='{$_POST['Name']}'";
  $resource = mysql_query($query);
  if ($result === FALSE)
  {
    echo 'Query failed: '.$query;
  }
  else
  {
    if (mysql_num_rows($resource) == 0)
      echo 'Name is not taken.';
    else
      echo 'Name is currently taken.';
  }
}

 

it is extremely wasteful of resources and time to pull every record from the database and iterate through them looking for a matching value - let MySQL do the legwork, and SELECT exactly what you're looking for.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.