Jump to content

Functions with sql queries


zimmo

Recommended Posts

I am learning how to use functions, and they are a great. I am unsure of how to perform an sql query in a function. It is checking to see if a username is taken. Can this be done with a function?

 

Here is the query, but it is failing when called.

 

<?
function validUsername($username)
{
  $sql = "SELECT * FROM tableA WHERE username = '$_POST[username]' "; 
  $sql_result = mysql_query($sql); 

if (mysql_num_rows($sql_result) !=0)
{
	$isValid = true;
}
else
{
	$isValid = false;
}
return $isValid;
} 
?>

Link to comment
Share on other sites

try defining username outside of the function. making code look like this

 

<?
$username = $_POST['username'];  // defines username
validUsername($username);   // this calls the function

function validUsername($username)
{  
  $sql = "SELECT * FROM tableA WHERE username = '$_POST[username]' ";   
  $sql_result = mysql_query($sql);  	
  
  if (mysql_num_rows($sql_result) !=0)	
  {		
    $isValid = true;	
  }	
  else	
  {		
    $isValid = false;	
  }	
  
  return $isValid;
} 
?>

Link to comment
Share on other sites

Doh... sorry, yes I just missed that. I normally do us php not just the ?. Thanks for pointing that out.

 

Sorry I forgot to add about the function. The function I posted up, is actually held within an external file and called from the header using an include.

 

The actual page that calls the form has the following code, but it does not work, it gives me no error, but it does not actually perform the sql query? it just tries to insert a duplicate.

 

Here is the code calling the function:

 

	if ( empty($username) ) {
	$error['username_error'] = '<div class="formerror">Please enter your username</div>';
	}
	elseif (!validUsername ($username) ) {
	$error['username_error'] = '<div class="formerror">Username taken</div>';
	}

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.