简体   繁体   English

使用PHP的准备好的语句将数组插入MySQL数据库

[英]Insert an array to MySQL database using PHP's prepared statements

I have an input array that I want to insert to database. 我有一个要插入数据库的输入数组。 I don't want to have 1 row in database for each item in the array. 我不想在数据库中为数组中的每个项目设置1行。 I want them all to go on same row. 我希望他们都走在同一排。 So this is my code: 这是我的代码:

<?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();
?>

The query runs in database but only the first list item from the array... Do I need to use the implode function? 该查询在数据库中运行,但仅从数组中的第一个列表项开始...是否需要使用implode函数? I have never used it so if that is the only solution can someone show me how i use that in this query? 我从未使用过它,所以如果这是唯一的解决方案,那么有人可以告诉我如何在此查询中使用它吗?

Instead of replacing variable value you have to concatenate 不必替换变量值,而必须串联

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

And this is how to make a little more clean: 这是使它更干净的方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM