将随机id插入数据库


Insert random id into database

我正在尝试在我的数据库中插入记录,我使用这个代码:

<?php 
$con = mysql_connect('localhost','root','')
or die(mysql_error());
mysql_select_db ("my_db");
$patient_array = array();
$query = "SELECT * FROM accounts";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$patient_array[$row['account_id']] = array("lastname" => $row['lastname'], 
"firstname" => $row['firstname']);
}
foreach($time_table as $tid => $t){
echo array_rand($patient_array, 1);
echo $tid."====".$t["from"]." - " . $t["to"]."<br />";
$sql = "INSERT INTO appointment (appt_id, appt_date, appt_time, appt_doctor, 
patient_id, appt_time_end) VALUES ('', '".$appt_date."', '".$t["from"]."', 
'".$doc."', '".$tid."', '".$t["to"]."')";
mysql_query($sql);
}
?> 

这一个是正确插入,但对于"patient_id"我想存储随机id。$tid给我随机输出,但当我检查数据库时,它是不一样的;它按降序显示id。我试过使用Rand()命令,但我不知道如何使它工作。任何想法?还是我错过了什么?

谢谢!

编辑:我从另一个表中获取patient_id,这是要传递到约会表的帐户表。我能够选择随机的患者id,但我如何将其插入到另一个表中,以随机顺序。

获取随机id为什么不能在PHP中使用uniqid()函数

$randomID = uniqid()

请参考以下链接,

随机/惟一的ID

您可以添加一个名为'time'的额外列,例如,您可以在其中放置UNIX时间,以便当您按'time'排序时,您可以按照您在表中写入的顺序获得随机id。我建议你把时间加起来,把它储存在某个地方真的很有用!

如果你想让它们不是随机排列,而是以精确的顺序排列,我真的不明白为什么你要使用随机id !

我将创建一个名为id的数据库字段,它具有AUTO_INCREMENT属性

您可以使用以下命令

添加列
alter table appointment add (id INT NOT NULL AUTO_INCREMENT);

谢谢你的回复,但是我已经找到了这个问题的答案。这是我的代码修改:

while($row = mysql_fetch_array($result))
{
//I changed this...
//$patient_array[$row['patient_id']] = array("lastname" => $row['lastname'], "firstname" => $row['firstname']);
//to this:
$patient_array[] = $row['patient_id'];
}
foreach($time_table as $tid => $t){
/*
removed this, since it's just an output to check what's happening inside 
the 'rand'      
echo array_rand($patient_array, 1);
echo $tid."====".$t["from"]." - " . $t["to"]."<br />";
*/
//added these...
$rand = array_rand($patient_array); //randomize patient id
$patient_id = $patient_array[$rand];
print_r($patient_id); //displays randomized ids
//and now was able to INSERT RANDOM patient ids
$sql = "INSERT INTO appointment (appt_id, appt_date, appt_time, appt_doctor, patient_id, appt_time_end) VALUES ('', '".$appt_date."', '".$t["from"]."', '".$doc."', '".$patient_id."', '".$t["to"]."')";
mysql_query($sql);
}