Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to execute MYSQL query inside a PHP function

Tags:

php

mysql

PHP:

function generate_uid() {  
  $uid = mt_rand();  

  $sql = "SELECT user_id  
            FROM user_registration";  

  if (!mysql_query($sql,$con)) {  
    die('Error: ' . mysql_error());  
  }  

  $result = mysql_query($sql);  
  $availability = TRUE;  

  while($row = mysql_fetch_array($result)) {  
    if($row['user_id'] == $uid) {  
      $availability = FALSE; 
    }  
  }

  if($availability == FALSE) {
    generate_uid();
  }  
}  

The error

Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in E:\Web Design EC\register2.php on line 8 Error:

But when i execute this function as normal php there is no error and the $uid is generated. What maybe the problem??

like image 798
Sussagittikasusa Avatar asked Oct 20 '10 18:10

Sussagittikasusa


1 Answers

$con is not defined in the current variable scope. You can pass the connection to function as a parameter:

function generate_uid($con) {
    ...
    mysql_query($sql, $con);
}

$uid = generate_uid($con);

Or you can use global:

function generate_uid() {
    global $con;
    ...
    mysql_query($sql, $con);
}

$uid = generate_uid();

Or, simply leave the connection variable out, and the last opened connection will be used:

function generate_uid() {
    ...
    mysql_query($sql); 
}

$uid = generate_uid();

All of those should work.

To learn more about variable scope, check out the PHP manual on the subject at:

http://www.php.net/manual/en/language.variables.scope.php

like image 171
Tatu Ulmanen Avatar answered Oct 26 '22 18:10

Tatu Ulmanen