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

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

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题