【发布时间】:2016-12-24 13:13:01
【问题描述】:
我想生成一个不在表格中的5位随机数并申请注册。我有下面的代码..它正在生成一个随机数,但它显示了
" 注意:未定义变量:id in F:\wamp\www\hello\hello.php on 8号线
请帮帮我
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
// function to generate random ID number
function createID() {
for ($i = 1; $i <= 5; $i++) {
$id .= rand(0,9);
}
return $id;
}
// MySQL connect info
mysql_connect("localhost", "root", "");
mysql_select_db("college");
$query = mysql_query("SELECT id FROM college");
// puts all known ID numbers into $ids array
while ($result = mysql_fetch_array($query)) {
$ids[] = $result["id"];
}
// generates random ID number
$id = createID();
// while the new ID number is found in the $ids array, generate a new $id number
while (in_array($id,$ids)) {
$id = createID();
}
// output ID number
echo $id;
?>
【问题讨论】:
-
如果您正在编写新代码,请不要使用
mysql_*函数。它们又旧又坏,在 PHP 5.5 中被弃用(它太旧了,甚至不再接收安全更新),并在 PHP 7 中完全删除。使用PDO或mysqli_*和 prepared statements而参数绑定。详情请见stackoverflow.com/q/12859942/354577。 -
你必须初始化 $id 以避免警告
-
它现在显示更多错误!
-
如何初始化 $id ?我是 php 新手
-
@Durai Sankar 我已经在下面的回答中解释了如何做到这一点。
标签: php mysql random undefined