PDO insert array

sam thenoob

Reccently I have been attempting to insert an array into a database, I keep getting the error message "Notice: Array to string conversion", I not really sure how to resolve this issue, any advice would be greatly appreciated

<?php 

try{
    $db = new PDO("mysql:host=localhost;dbname=test", 'root', '');
    $db ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}  catch(PDOException $e){
    echo $e->getMessage();
    die();
}


if ($_SERVER["REQUEST_METHOD"] == "POST"){


    $sort  = $_POST['sort'];
    $count = $_POST["count"];
    $error = $_POST["error"];

    $audit = array( ':sort' => $sort,
        ':count' => $count,
        ':error' => $error
    );


    foreach($audit as $completeAudit => $display) {
        //print_r($display);    

        $sql = implode("INSERT INTO `audits` (`sort`, `count`, `error`, `timeentered`) VALUES ('$sort','$count','$error', NOW())");
    }

    $query = $db->prepare($sql);

    $query->execute(array(
        ':sort' => $sort,
        ':count' => $count,
        ':error' => $error
    ));
}

EDIT

$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');
$db ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    if ($_SERVER["REQUEST_METHOD"] == "POST"){
        $sql = "INSERT INTO `audits` (`sort`, `count`, `error`, `timeentered`) VALUES (?,?,?, NOW())";
        $stmt = $db->prepare($sql);
        $query->execute(array($_POST['sort'], $_POST["count"], $_POST["error"]));
    }

This is how it looks now, I deleted everything and used code supplied below

Your Common Sense

this error has nothing to do with PDO - it's just basic PHP syntax.

However, your PDO is wrong as well. Here is the proper code:

$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');
$db ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if ($_SERVER["REQUEST_METHOD"] == "POST"){
    $sql = "INSERT INTO `audits` (`sort`, `count`, `error`, `timeentered`) VALUES (?,?,?, NOW())");
    $stmt = $db->prepare($sql);
    $stmt->execute(array($_POST['sort'], $_POST["count"], $_POST["error"]));
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related