MvM
MvM

Reputation: 5

Sending an Array with input values to a database with php

So bassically I can't seem to send the array with the input values to my database.

I tried sending it seperately, it works, but it only sends the array or the way around. There are no errors.

if (isset($_POST['submit'])) {
    $services = implode ("|", $_POST['services']);
    mysqli_query($mysqli, "INSERT INTO klientai (package, name, surname, email, phone, message, services) VALUES('$_POST[package]', '$_POST[name]', '$_POST[surname]', '$_POST[email]', '$_POST[phone]', '$_POST[message]', '$services'");
}

Upvotes: 0

Views: 95

Answers (1)

Tomáš Petr
Tomáš Petr

Reputation: 136

mysql_query function is deprecated and is not secured, You should use another option.

You can use PDO for example: https://www.php.net/manual/en/book.pdo.php

open connection

$pdo = new PDO('mysql:host=localhost;dbname=test', $user, $pass);

insert method 1

$sql = "INSERT INTO users (name, surname, sex) VALUES (?,?,?)";
$stmt= $pdo->prepare($sql);
$stmt->execute([$name, $surname, $sex]);

insert method 2

$data = [
    'name' => $name,
    'surname' => $surname,
    'sex' => $sex,
];

 $sql = "INSERT INTO users (name, surname, sex) VALUES (:name, :surname, :sex)";
 $stmt= $pdo->prepare($sql);
 $stmt->execute($data);

also check https://phpdelusions.net/pdo_examples/insert and https://www.startutorial.com/articles/view/pdo-for-beginner-part-1

In this method, you don't need to escape your strings for SQL injection and it should also solve your problem.

Upvotes: 1

Related Questions