带有消息'SQLSTATE [HY000]的未捕获异常'PDOException'

时间:2012-07-08 16:35:57

标签: php sql pdo

我转换了以下工作代码:

<?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');
?>

到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');
?>

哪个给了我

  

致命错误:带有消息'SQLSTATE [HY000] [2002]的未捕获异常'PDOException'无法通过套接字'/var/lib/mysql/mysql.sock'(2)'连接到本地MySQL服务器/content/58/9508458/html/pabrowser/comsumcompro.php:4堆栈跟踪:#0 /home/content/58/9508458/html/pabrowser/comsumcompro.php(4):PDO-&gt; __ construct('mysql:在第4行的/home/content/58/9508458/html/pabrowser/comsumcompro.php中抛出host =; dbn ...',NULL,NULL)#1 {main}

4 个答案:

答案 0 :(得分:3)

您的$db_host$db_name值错误,或者您提供的凭据无效。

答案 1 :(得分:3)

您忘记了include('config.php');

答案 2 :(得分:1)

请添加

include('config.php');

答案 3 :(得分:0)

您的连接字符串错误或MySQL服务器没有响应。使用try ... catch构造,如下所示:

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();
}

如果您看到“连接失败”消息,您就会明白错误。