dongmei1911 2013-09-03 12:12
浏览 69
已采纳

preg_match_all数组插入mysql数据库循环不能正常工作

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.

  • 写回答

1条回答 默认 最新

  • dongyan2267 2013-09-03 12:18
    关注

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障