【问题标题】:user defined function not working in php [closed]用户定义的函数在php中不起作用[关闭]
【发布时间】:2013-01-17 07:13:51
【问题描述】:

我在调用 rand_id() 函数时遇到问题。这是代码

<?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";
}
}
?>        

但是如果我删除该函数并检查此代码工作正常但现在我在检查数据库后无法生成唯一 id 消息...请帮助......

这是删除函数后的另一个代码

<?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();
}

?>        

【问题讨论】:

  • 具体是什么问题或错误?!
  • 您能用有意义的缩进重新格式化您的代码吗?
  • 尝试将您的函数从查询中分离出来,并将其设置为return 一个值,以便在函数外部进行检查。

标签: php function pdo unique-id


【解决方案1】:

您的数据库对象$conn 超出了rand_id() 函数的范围。您可以将其作为参数传递:

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

或者使用global方法:

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

关于Variable Scope on the Manual的更多信息。


为了以后的调试,记得检查你的错误日志。在这种情况下,你应该有类似的东西:

致命错误:在...中的非对象上调用成员函数 query()

【讨论】:

  • 工作..!!!非常感谢...:)
猜你喜欢
  • 1970-01-01
  • 2011-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-30
  • 2015-02-04
  • 1970-01-01
相关资源
最近更新 更多