【问题标题】:How can I prepare mysqli statement that uses arrays?如何准备使用数组的 mysqli 语句?
【发布时间】:2013-07-20 04:04:51
【问题描述】:

我使用下面的表格

<form method="get" action="daily_process.php">
Horse / Course / Time 

<input type='text' name='horse[]' />
<input type="text" name="course[]" />
<input type="text" name="time[]" />

<input type='text' name='horse[]' />
<input type="text" name="course[]" />
<input type="text" name="time[]" />

<input type='text' name='horse[]' />
<input type="text" name="course[]" />
<input type="text" name="time[]" />


<input name="submit" type="submit" />
</form>

我使用下面的代码来处理表单数组并将其输出为打印

<?php 
$horse = $_POST['horse'];
$course = $_POST['course'];
$time = $_POST['time'];

foreach( $horse as $key => $h ) {

if ($horse[$key] != "") {
  print "The horse is ".$h.", course is ".$course[$key].
        ", and time is ".$time[$key]." Thank you <br/>" ;
}}
?>

我的问题是如何为 mysqli 准备这些结果?

我在 StackOverflow 上看到了下面的示例,但是如何编辑它以适合我的目的?

即。我需要保存 $horse、$course 和 $timeto 数据库—— table (horse,course, time) VALUES (?, ?, ?)

$query = "INSERT INTO table (link) VALUES (?)"; 
$stmt = $mysqli->prepare($query); 
foreach ($array as $one) { 
    $stmt ->bind_param("s", $one); 
    $stmt->execute(); 
} 
$stmt->close();

【问题讨论】:

  • 如果你有三个参数,为什么只准备和绑定一个?
  • @Gumbo 他只是展示了一个他从其他问题中复制的示例,而不是他的实际代码。

标签: php forms mysqli


【解决方案1】:
$query = "INSERT INTO table (horse,course,time) VALUES (?,?,?)"; 
$stmt = $mysqli->prepare($query); 

foreach( $horse as $key => $h ) {
    $stmt ->bind_param("sss", $h, $course[$key], $time[$key]); 
    $stmt->execute();
}

假设所有值都是字符串

the PHP docs 中的 bind_param 示例确实展示了如何绑定多个值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多