简体   繁体   English

如何用uniqueid()填充MySQL表中所有记录的字段?

[英]How to populate a field of all of the records in a MySQL table with uniqueid()?

I'm a newbe here and about PHP; 我是关于PHP的新手。 be patient please :-) 请耐心:-)

I have a MySQL table with 15000 rows; 我有一个具有15000行的MySQL表; I need to populate a field of it ( varchar(15) ) - to be used in a way similar to a primary key – with the uniqid() PHP function. 我需要使用uniqid() PHP函数填充它的一个字段( varchar(15) ),以类似于主键的方式使用。

The algorithm is: 该算法是:

  1. positioning to the first row (record); 定位到第一行(记录);
  2. generating a value with the uniqid() function; uniqid()函数生成一个值;
  3. updating with it an empty field of that record; 更新该记录的空白字段;

All of those three steps till the end of the table (all of the records). 所有这三个步骤直到表末尾(所有记录)。

What is the PHP code to do all of that? 完成所有这些工作的PHP代码是什么?

First off, 15000 rows is not very many. 首先,15000行不是很多。 So it could be done a number of ways. 因此,可以通过多种方法来完成。 Second, there is no such concept as "first row" or "second row" or "last row" in SQL. 其次,在SQL中没有“第一行”或“第二行”或“最后一行”这样的概念。 So your algorithm won't work, unless you are saying the first row in your currently grabbed set of records, or your the first row in your cursor. 因此,除非您要说出当前抓取的记录集中的第一行或光标的第一行,否则您的算法将无法工作。

At any rate, I would not do it that way. 无论如何,我不会那样做。 I would do it in two steps, by creating a table with the exact format you want, but with the ID field being an auto-increment field, and then insert into newtable select * from oldtable order by something 我将分两步进行操作,方法是使用所需的确切格式创建一个表,但将ID字段作为自动递增的字段,然后insert into newtable select * from oldtable order by something ,然后insert into newtable select * from oldtable order by something

Lastly, you state this is a PHP problem, but it sounds like you are asking for a one-time solution. 最后,您指出这是一个PHP问题,但是听起来您正在寻求一次性解决方案。 If that is the case, I would just do it in SQL and get it over with, rather than trying to write PHP to do it. 如果是这种情况,我只需要用SQL来完成它,然后再使用它,而不是尝试编写PHP来做到这一点。

$cnt = 0;
$result = mysql_query('SELECT COUNT(*) AS cnt FROM table');
if (($row = mysql_fetch_assoc($result)) !== false) {
    $cnt = $row['cnt'];
}
$ids = array();
$num = 0;
while ($num < $cnt) {
    $id = uniqid();
    while(in_array($id, $ids)) {
        $id = uniqid();
    }
    mysql_query('UPDATE table SET the_column_you_need_to_update='.$id.' LIMIT 1 OFFSET '.$num);
    $num++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM