Tom
Tom

Reputation: 244

Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]

I converted the following working code:

<?php
    include('config.php');
    $link = mysql_connect($db_host, $username, $password);
    mysql_select_db($db_name);

    $id= $_POST["uniqi"];
    $comments= $_POST["comments"];
    $comments= mysql_real_escape_string($comments);
    $comments = strip_tags($comments);

    $update = "UPDATE mastertable SET comments = '$comments' WHERE id_pk= '$id'";
    mysql_query($update, $link);
    mysql_close();
    header('Location: ccccc.com/pabrowser/… Updated');
?>

to PDO:

<?php
    $id= $_POST["uniqi"];
    $comments= $_POST["comments"];
    $conn = new PDO("mysql:host=$db_host;dbname=$db_name", $username, $password);

    $sql = "UPDATE mastertable SET comments=?    WHERE id_pk=?";
    $q = $conn->prepare($sql);
    $q->execute(array($comments, $id));

    header('Location: ccccc.com/pabrowser/… Updated');
?>

Which gave me

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)' in /home/content/58/9508458/html/pabrowser/comsumcompro.php:4 Stack trace: #0 /home/content/58/9508458/html/pabrowser/comsumcompro.php(4): PDO->__construct('mysql:host=;dbn...', NULL, NULL) #1 {main} thrown in /home/content/58/9508458/html/pabrowser/comsumcompro.php on line 4

Upvotes: 1

Views: 25002

Answers (4)

Andrey Vorobyev
Andrey Vorobyev

Reputation: 886

Your connection string is wrong or the MySQL server is not responding. Use a try ... catch construction, like this:

include('config.php');

$id = $_POST["uniqi"];
$comments = $_POST["comments"];
try {
    $conn = new PDO("mysql:host=$db_host;dbname=$db_name", $username, $password);
}
catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

And if you will see "Connection failed" message, you understand what's wrong.

Upvotes: 0

Tina
Tina

Reputation: 312

Please add

include('config.php');

Upvotes: 1

ts.
ts.

Reputation: 10709

You've forgotten include('config.php');

Upvotes: 4

CodeCaster
CodeCaster

Reputation: 151588

Your $db_host or $db_name value are wrong or you are supplying invalid credentials.

Upvotes: 3

Related Questions