错误报告通知:
Undefined variable: random_chars in wamp\www\php_sandbox\idgen.php on line 21
Call Stack:
# Time Memory Function Location
1 0.0045 678928 {main}( ) ..\idgen.php:0
GPB7446
如何解决此错误?
将此代码用作自动唯一ID生成器。在允许将代码分配给创建新帐户的用户之前,如何连接到数据库以验证代码是否真正独一无二?
由于
<?php
$characters = array(
"A","B","E","F","G","H","J","K","M","N","P","R","S","T","W","X","Y","Z");
$keys = array();
while(count($keys) < 3) {
$x = mt_rand(0, count($characters)-1);
if(!in_array($x, $keys)) {
$keys[] = $x;
}
}
foreach($keys as $key){
$random_chars .= $characters[$key];}
$randNum = rand(2327,9987); $randLet = rand(2327,9987);
echo $random_chars . $randNum;
?>
答案 0 :(得分:2)
你没有初始化$random_chars
- 在连接之前尝试将其设置为空字符串。
...
$random_chars="";
foreach($keys as $key){
$random_chars .= $characters[$key];
}
$randNum = rand(2327,9987); $randLet = rand(2327,9987);
echo $random_chars . $randNum;
...
如果您使用长手语法,那么您收到错误的原因会更清楚......
$random_chars .= $characters[$key];
与
相同 $random_chars = $random_chars . $characters[$key];
第一次运行该行代码时,$random_chars
不存在。
关于检查数据库,这取决于您正在使用的数据访问机制。
您需要发出类似于:
的查询 SELECT COUNT(*) As RecordCount FROM MyUserTable WHERE MyIdColumn = 'ABC123'
然后,您将读取返回记录集的第一行的RecordCount值。如果它不存在,则该值应为0;如果不存在则为> 0。
编辑:澄清数据库位...
基本流程如下:
在开发过程中:
在运行时:
可以在此处找到有关PHP和MySQL的详细但详细的介绍: http://www.freewebmasterhelp.com/tutorials/phpmysql
您还应该阅读一些名为“SQL注入”的内容,在开发使用数据库的任何网站时,您需要注意这一点,并且除了您以外的任何人都可以看到。
下面是一些示例代码。您需要更改表名和列名以匹配创建数据库时使用的名称。我假设Db服务器与Web服务器是同一台机器 - 如果没有,请将localhost更改为适当的IP /主机名。
$user="username";
$password="password";
$database="database";
mysql_connect("localhost",$user,$password); //Connect to server
@mysql_select_db($database) or die( "Unable to select database"); //Select your database
$query="SELECT * FROM MyUserTable WHERE MyIdColumn = '" . mysql_real_escape_string($random_chars . $randNum) . "'"; //Define the query
$recordset = mysql_query($query);//Run it
$matchingRecordCount = mysql_numrows($recordset)
mysql_close();//Close the Db connection
if(matchingRecordCount>0) {
//It's already in there, generate another
} else {
//It's not already in there
}
为了确保你知道,数据库已经非常好并且快速发布独特的ID(在AUTO_INCREMENT上阅读),所以除非你因为某种原因真的想要这种格式,所以考虑使用它。
答案 1 :(得分:0)
在循环之前将$random_chars
初始化为空字符串:
$random_chars = "";
foreach($keys as $key) {
$random_chars .= $characters[$key];
}
答案 2 :(得分:0)
您可以在$random_chars = "";
之上声明foreach($keys as $key)
,并且应该修复它
答案 3 :(得分:0)
在开始连接内容之前,您必须声明并初始化$random_chars
。
修正如下。我将random_chars设置为空字符串。 $random_chars = "";
$characters = array("A","B","E","F","G","H","J","K","M","N","P","R","S","T","W","X","Y","Z");
$keys = array();
while(count($keys) < 3) {
$x = mt_rand(0, count($characters)-1);
if(!in_array($x, $keys)) {
$keys[] = $x;}
}
$random_chars = ""; //Here
foreach($keys as $key){
$random_chars .= $characters[$key];
}
$randNum = rand(2327,9987); $randLet = rand(2327,9987);
echo $random_chars . $randNum;