user3055512 user3055512 - 2 years ago 66
PHP Question

Insert an array to mysql databas using php prepared statments

I have an input array that i want to insert to database. I dont 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


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');
echo "Error: " . $stmt->error;


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 Source

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>';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download