Unable to execute MYSQL query inside a PHP function – Education Career Blog

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??

,

$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

,

You are using $con in your function, but $con is not defined in your function scope.

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

You need to either

a) Pass $con to your function or

b) Set $con as a global

c) Not use $con at all eg.

    if (!mysql_query($sql))

however make sure that your app is only connecting to ONE database, otherwise you will run into issues because when you don’t specify a connection it will use the last connection opened.

,

Inside your function, your MySQL connection doesn’t exist. You either need to pass it in, or use the global keyword:

$con = mysql_connect('localhost', 'mysql_user', 'mysql_password');

function generate_uid()
{
global $con;
$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(); }
} 

,

while($row = mysql_fetch_array($result))

You can’t use that if you plan to use $row as an associative array. Use:

while($row = mysql_fetch_assoc($result))

instead.

EDIT

MYSQL_BOTH is turned on by default, forgot about that. The problem is pointed out by the other users, regarding the connection not being available in the function scope.

Leave a Comment