Aaron
Aaron

Reputation: 11673

Error in inserting data into database

When I try to run this code it will not insert the data into the database?

<?php
class Database {
private $dsn;
function __construct($dbname, $host, $user, $password, $enckey) {
    $this->dsn = "mysql:dbname=" . $dbname . ';host=' . $host;
    $this->user = $user;
    $this->password = $password;
}
private function createDSN() {
    return $this->dsn;
}
public function createConnection() {
    try {
        $dbh = new PDO(self::createDSN(), $this->user, $this->password);
    } 
    catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
    }
    return $dbh;
}
}

$db = new Database('mytest', 'localhost', 'root', 'hashedpassword', null);
$dbh = $db->createConnection();

$sql = $dbh->prepare("INSERT INTO contacts (firstname, lastname) VALUES (?,?)");
$sql->execute(array("abc", "xyz"));


?>

Upvotes: 0

Views: 104

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157828

I don't get an error message

but you have to get it. Asking other people about your database makes very little sense.
Asking the database itself is a way better idea.

add this line to your createConnection() (I dunno what this function for but as you have it)

$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

and run your code this way

try {
    $sql = $dbh->prepare("INSERT INTO contacts (firstname, lastname) VALUES (?,?)");
    $sql->execute(array("abc", "xyz"));
} catch (PDOException $e) {
    echo $e->getMessage();
}

Upvotes: 2

Related Questions