使用PHP的预处理语句将数组插入MySQL数据库

时间:2016-05-04 22:14:07

标签: php mysql arrays

我有一个我要插入数据库的输入数组。我不希望数组中的每一项都有1行。我希望他们都能在同一排。所以这是我的代码:

<?php
session_start();
include('../../config/dbconf.php');

mysqli_select_db($conn, $webdb);

$stmt = $conn->prepare("INSERT INTO changelog (title, type, content, author, post_date) VALUES (?, ?, ?, ?, ?)");

$title = $_POST['title'];
$type = $_POST['type'];
$change = $_POST['change'];
$author = $_SESSION['waradmin'];
$date = time();

foreach($_POST['change'] as $key => $value) {
   $changes = "<li>" . $change[$key] . "</li>";
}

$stmt->bind_param("sissi", $title, $type, $changes, $author, $date);
if($stmt->execute()) {
   header('location: ../?p=dashboard');
}else{
   echo "Error: " . $stmt->error;
}

$stmt->close();
?>

查询在数据库中运行但只有数组中的第一个列表项...我是否需要使用implode函数?我从来没有使用它,所以如果这是唯一的解决方案,有人可以告诉我如何在此查询中使用它吗?

1 个答案:

答案 0 :(得分:4)

不必替换变量值,而是必须连接

$changes = '';
foreach($_POST['change'] as $key => $value) {
   $changes .= "<li>" . $change[$key] . "</li>";
}

这是如何使一点干净:

$changes = '';
foreach($_POST['change'] as $value) {
   $changes .= '<li>' . $value . '</li>';
}