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
https://forums.phpfreaks.com/topic/199362-functions-with-sql-queries/
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;
} 
?>

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>';
	}

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.