简体   繁体   中英

Update Every row in MYSQL with Unique Value

I'm trying to assign a field called 'uniqueid' to each row present in my database. There are roughly 188,000 rows available.

Here is the code I am using:

$connection = mysql_connect("localhost","root","root");
mysql_select_db("comics",$connection) or die ("Database not found");

$query = mysql_query("select * from comic_issues"); 

if ($query){
  $rows = mysql_num_rows($query);

  foreach($rows as $row){
    $str = strtolower($row['series'].$row['volume'].$row['issue']);
    $str = preg_replace('/[^A-Za-z0-9]/', '', $str);

    $update = "update comic_issues set uniqueid='" . $str . "' where id='" . $row['ID'] . "'";
    mysql_query($update);

    exit();
  }
}

What is happening is that every row gets updated with the same uniqueid, which seems to be a different value each time I run the script.

Just let MySQL do it all for you:

UPDATE comic_issues SET uniqueid = LOWER(CONCAT(series,volume,issue))

If you must also strip all non-alphanumeric characters, you can either write a stored function or else use a UDF.

Instead of

foreach($rows as $row){

you need to do

while ($row = mysql_fetch_row($query)) {

In your code $rows is a number and not an array, therefore you can't do a foreach on it.

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