dsgk0386 2016-05-04 22:14
浏览 53
已采纳

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

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. 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? I have never used it so if that is the only solution can someone show me how i use that in this query?

  • 写回答

1条回答 默认 最新

  • dousenjue3214 2016-05-04 22:19
    关注

    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>';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 springboot+vue 集成keycloak sso到阿里云
  • ¥15 win7系统进入桌面过一秒后突然黑屏
  • ¥15 有一台三相异步电动机 M1控制一个小车,有四个控制按钮,一个复位、一个启动、一个停止,还有一个急停,两个行程开关分别为上限位和下限位。 上限位。 下限位。
  • ¥30 backtrader对于期货交易的现金和资产计算的问题
  • ¥15 求C# .net4.8小报表工具
  • ¥15 安装虚拟机时出现问题
  • ¥15 Selenium+docker Chrome不能运行
  • ¥15 mac电脑,安装charles后无法正常抓包
  • ¥18 visio打开文件一直显示文件未找到
  • ¥15 请教一下,openwrt如何让同一usb储存设备拔插后设备符号不变?