0

I'm trying to preg_match_all the first 12 digit number found in a mysql field, and insert that number in another field, looping through all results from the Select statement. I have the following, which puts only the first result it finds in all the fields, so every field3 gets the same 12 digit number inserted, that 12 digit number being from the lowest unique ID field found by the Select statement. Any help with this would be greatly appreciated.

<?php


$query = mysql_query("SELECT * FROM `dbase`.`table` WHERE field1 IS NOT NULL AND field3 IS NULL");
$regexp ='/[0-9]{12}/';

while ($row = mysql_fetch_assoc($query)){
$result=($row["field1"]);

preg_match_all($regexp,$result,$matches,PREG_PATTERN_ORDER);

foreach($matches[0] as $match => $where){
$id=($row["field2"]);
$sql="UPDATE `dbase `.`table ` set field3 = $where WHERE field2 = '$id'";

mysql_query($sql);
}
}
?>

I added

print_r( $matches );

and the output was an array with one result, the number being place in all the fields:

Array ( [0] => Array ( [0] => 290970571788 )

)

The curly bracket change fixed the print_r output to show the the list of 12 digit numbers in this format (only first two are shown): Array ( [0] => Array ( [0] => 151104658286 )

) Array ( [0] => Array ( [0] => 271249191324 )

) Thanks for that.

Utilizing the answers and suggestions given here, I've edited the code to show the final working version. The last big issue was getting the 2nd select statement to use the array result, properly looping and inserting each value in the proper row. Also cleaned up the 1st select statement and changed from preg_set_order to preg_pattern_order.

kidcobra
  • 23
  • 3

1 Answers1

2

It shouldn't be

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

}

but

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

}

You don't want to create code block with while statement but you want to provide code block for it.

And also you're using same WHERE condition in SELECT and UPDATE so it'll update all selected rows with same value (all will match that condition).

Elon Than
  • 9,603
  • 4
  • 27
  • 37