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 脱敏项目合作,ner需求合作
  • ¥15 脱敏项目合作,ner需求合作
  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密