duan7264 2013-09-23 11:12
浏览 43
已采纳

PHP使用while循环准备语句[关闭]

I am doing some work in php with prepared statements. My task is to first select some data from one table and then insert the data into another table. How can I use while loop in prepared statement to insert the records?

Here is the code:

stmt=$db->prepare("SELECT userid, order_number, balance from plus_wallet  limit 0,3");
$stmt->execute();
$stmt->bind_result($userid, $orderid, $balance);
while($stmt->fetch()) {
    $stmt1=$db->prepare("INSERT INTO `plus_user_wallet`(`userid`, `balance`, `update_time`) VALUES (?,?, NOW() + INTERVAL 45000 second)");
    $stmt1->bind_param('ss' , $userid, $balance);
    $stmt1->execute();
    $stmt1->close();
    $stmt->close();
}
  • 写回答

1条回答 默认 最新

  • dongshi4589 2013-09-23 12:59
    关注

    If the order_number field is not required anywhere else and you're selecting it because it's in the table, you could use:

    insert into
    plus_user_wallet
        (userid,balance,update_time) 
    select 
        userid,balance,now()+interval 45000 second
    from
        plus_wallet
    limit
        0,3;
    

    You could make that into a prepared statement if you require a single userid value by adding where userid=? into the select statement after from plus_wallet

    Obviously, if you do require the order_number for elsewhere then you will need a loop system.

    A few notes regarding your code:

    • Prepare $stmt1 outside of the while loop - that's the point of a prepared statement
    • Close all prepared statements after the while loop is complete
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集