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

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.