doulieyu0881 2017-11-27 20:04
浏览 56
已采纳

如何为数组的每个元素插入数据库?

I have a booking system and need to insert the details into mysql database. All of my variables are strings and one of them is an array - so I need to insert the same information for each array element ($ticketnumber). I have tried doing it with a foreach loop, but it doesn't seem to work. How do I do this with only one INSERT statement as people may choose different number of tickets to buy?

Here is part of the code:

<?php

$day = $_SESSION['date'];
$time = $_SESSION['time'];
$name = $_REQUEST['name'];
$ticketnumber = $_REQUEST['tickets']; //this is the array variable

foreach ($ticketnumber as $ticket){
    $sql = "INSERT INTO table VALUES ('$name', '$day', '$time', '$ticket');";
    $handle = $conn->prepare($sql);
    $handle->execute();

}
?>

The values of my array in this case are(it varies depending on how many tickets you check):

array(2) { [0]=> string(3) "010" [1]=> string(3) "011" }

This matched the value of $ticket as well, why is that happening?

My session and connection to the database are established before this. I also tried replacing the array variable with a string and the insert statement works.

Any help is appreciated!

Thank you.

  • 写回答

1条回答 默认 最新

  • doujing6053 2017-11-27 20:12
    关注

    If you concatenate values into the SQL string as you are doing, there's not much benefit to using a prepared statement. Instead, prepare a statement with placeholders and execute it repeatedly for the various different values.

    Create an array of parameters

    $params['day'] = $_SESSION['date'];
    $params['time'] = $_SESSION['time'];
    $params['name'] = $_REQUEST['name'];
    

    Create the prepared statement with placeholders where your values will be bound

    $sql = "INSERT INTO table VALUES (:name, :day, :time, :ticket);";
    $handle = $conn->prepare($sql);
    

    Execute the statement in a loop for each value in $ticketnumber.

    $ticketnumber = $_REQUEST['tickets'];
    
    foreach ($ticketnumber as $ticket) {
        $params['ticket'] = $ticket; // assign the current ticket to the array of values
        $handle->execute($params);   // the values are bound to the prepared statement
    }
    

    You don't really need to explicitly close or null the connection (especially not inside the loop as others have pointed out).

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

报告相同问题?

悬赏问题

  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面