Insert multiple rows using form and PDO

2019-09-21 18:04发布

问题:

Hello guys i am stuck in PHP code to Insert multiple rows using form and PDO Below my code please help me to fix it I'll appreciate all comments and suggested solutions and forgive my mistakes because I am new i PHP

HTML code

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Firstname: <input type="text" name="firstname[]"><br>
Lastname: <input type="text" name="lastname[]"><br>
Email: <input type="text" name="email[]"><br>
<hr>
Firstname: <input type="text" name="firstname[]"><br>
Lastname: <input type="text" name="lastname[]"><br>
Email: <input type="text" name="email[]"><br>
<input type="submit" name="submit" value="Submit">
</form>

PHP Code

<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $firstname = input_checker($_POST["firstname"]);
        $lastname = input_checker($_POST["lastname"]);
        $email = input_checker($_POST["email"]);   

        foreach ($row as $rows) {
            // prepare sql and bind parameters
            $stmt = $conn->prepare("INSERT INTO memo (firstname, lastname, email) 
            VALUES (:firstname, :lastname, :email)");
            $stmt->bindParam(':firstname', $rows);
            $stmt->bindParam(':lastname', $rows);
            $stmt->bindParam(':email', $rows);
            $stmt->execute();

            echo "New records created successfully";
        }
    }
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;

function input_checker($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
?>

回答1:

Indent please, it's hard to read.

It can't work. DONT FOREACH THE QUERY. You'll send one query with bad datas as many times as you have elements in $rows array

What you're doing here is sending nothing cause $rows don't exist.

So here are the steps. Do

$rows = array($firstname, $lastname, $email);
$stmt = $conn->prepare("INSERT INTO memo(ID, firstname, lastname, email) 
VALUES (NULL, :firstname, :lastname, :email)");
foreach($rows as $key => $value){
         $stmt->bindParam($key, $value);
}
$stmt -> execute();

OR you can try building the query this way : DB_connect :

<?php
    $db_username = "root";
    $db_password = "";
    $db_host = "localhost";
    $db_name = "veterinaires";
    /* PDO EN FR OU EN ARABE C ISSI */
    $db_options = array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");

        try {
            $db = new PDO("mysql:host={$db_host};dbname={$db_name};charset=utf8", $db_username, $db_password, $db_options);
        } catch(PDOException $ex) {
            die("Failed to connect to the database: " . $ex->getMessage());
        }

    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
?>

Query :

        $query = "INSERT INTO patients
                    (ID,
                    pet_name,
                    breed,
                    colour,
                    sex,
                    date_of_birth,
                    microchip_tatoo,
                    comment,
                    owner_ID)
                VALUES
                    (NULL,
                    :pet_name,
                    :breed,
                    :colour,
                    :sex,
                    :date_of_birth,
                    :microchip_tatoo,
                    :comment,
                    :owner_ID)";
        $query_params = array(':pet_name' => $pet_name,
                              ':breed' => $breed,
                             ':colour' => $colour,
                             ':sex' => $sex,
                             ':date_of_birth' => $date_of_birth,
                             ':microchip_tatoo' => $microchip_tatoo,
                             ':comment' => $comment,
                             ':owner_ID' => $_SESSION['ID']);
        try {
            $stmt = $db->prepare($query);
            $result = $stmt->execute($query_params);
            $check = true;
        }catch(PDOException $ex){
            $check = false;
            die("Failed to run query: " . $ex->getMessage());
        }
?>