简体   繁体   中英

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

I'm a newbe here and about PHP; be patient please :-)

I have a MySQL table with 15000 rows; 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.

The algorithm is:

  1. positioning to the first row (record);
  2. generating a value with the uniqid() function;
  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?

First off, 15000 rows is not very many. 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. 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

Lastly, you state this is a PHP problem, but it sounds like you are asking for a one-time solution. 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.

$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++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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