user3055512 user3055512 - 7 months ago 9
SQL Question

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. 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?

Answer

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>';
}