Question

I have a problem in calling my rand_id() function. here is code as

<?php 
try

{

$config=array(
'DB_USERNAME'=>'root',
'DB_PASSWORD'=>'');


$conn=new PDO('mysql:host=localhost;dbname=scc',$config['DB_USERNAME'],$config['DB_PASSWORD']); 
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

echo rand_id(); 

}

catch(Exception $e)
{
echo 'error: '.$e->getMessage();
}

function rand_id()
{

$id=rand(100,103);          //i have record with id ='100'
$results=$conn->query("select id from student_personal_info where id='".$id."'");

if($results->rowCount()>0)
{   
rand_id();
}
else
{
return "this is unique id";
}
}
?>        

but if I remove the function and check this code working fine but now i can't generate unique id message after checking with database...plz help......

Here is another code after removing function

<?php 

try
{
$config=array(
'DB_USERNAME'=>'root',
'DB_PASSWORD'=>'');

$conn=new PDO('mysql:host=localhost;dbname=scc',$config['DB_USERNAME'],$config['DB_PASSWORD']); 
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


$id=rand(100,103);          //i have record with id ='100'
$results=$conn->query("select id from student_personal_info where id='".$id."'");

if($results->rowCount()>0)
{   
echo  "generate again";
}
else
{
echo  "this is unique id";
}
}
catch(Exception $e)
{
echo 'error: '.$e->getMessage();
}

?>        
Was it helpful?

Solution

Your database object $conn is out of scope in the rand_id() function. You could pass it as an argument:

function rand_id($conn)
{
    // ...
}

Or use the global method:

function rand_id()
{
    global $conn;
    // $conn is now accessible
}

More info about Variable Scope on the Manual.


For future debugging, remember to check your error log. In this case you should have something like:

Fatal Error: Call to a member function query() on a non-object in ...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top