PDO Not working in php on wamp server [closed]

2019-07-31 04:02发布

问题:

I am facing difficulty getting data into my database using PDO. The insertion works when I use mysql_connect/mysql_query though, so I am sure it's something about PDO I am not getting right:

$db = new PDO("mysql:host=localhost;dbname=XXXXXX","root","");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try{
    $query= "INSERT INTO tableC VALUES ('1111','2222','XX YY','ERTY','33');";
    $result = $conn ->prepare($query);
    $result ->execute();
} catch {
    echo "PDO error:" . $exception->getMessage();
}

Couple of points: I am using PHP and connecting to WAMP server. PHP version is 5.3.13. I have also checked that my query works.

回答1:

You are using $conn-> where as you are using $db for connection so the below snippet

$conn ->prepare($query);

Should be written as

$db->prepare($query);

Also, where did you got $exception from? Your catch statement should look like

catch(PDOException $exception) {

}


回答2:

You have an issue that you are not storing the exception

Replace your catch line with the following

} catch (Exception $exception) {