【发布时间】: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