Pdo select语句不显示数据库中的数据

时间:2017-07-18 06:30:57

标签: php mysql pdo

<?php
$localhost ="localhost";
$username = "root";
$password = "";
$dbname = "sbnhs";
try {
    $db = new PDO("mysql:host=$localhost;dbname:$dbname", $username, $password);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    // echo "Success";
    $x = 0128;
    $sql = $db->prepare("SELECT * FROM $dbname.refcitymun WHERE provCode = :provcode");
    $sql->bindValue(':provcode', $x);
    if($sql->execute()) {
        while($result = $sql->fetch()){
            $desc = $result['citymunDesc']; 
            echo $desc;
        }   
    }else {
        echo 'Query Error';
    }
}catch (PDOException $e) {
    print 'Error: ' . $e->getMessage() . '</br>';
    die();
}   

?>

我想在我的地址栏中显示数据,但它不会显示任何内容或错误。我不知道代码有什么问题

<?php
$localhost ="localhost";
$username = "root";
$password = "";
$dbname = "sbnhs";
try {
    $db = new PDO("mysql:host=$localhost;dbname:$dbname", $username, $password);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    // echo "Success";
    // $x = 0128;
    $sql = $db->prepare("SELECT * FROM $dbname.refcitymun WHERE provCode = 0128");
    // $sql->bindValue(':provcode', $x);
    if($sql->execute()) {
        while($result = $sql->fetch()){
            $desc = $result['citymunDesc']; 
            echo $desc;
        }   
    }else {
        echo 'Query Error';
    }
}catch (PDOException $e) {
    print 'Error: ' . $e->getMessage() . '</br>';
    die();
}   

?>

但是当我尝试上面的格式时,它会显示我想要的数据。但我需要在声明中使用变量。请检查第一个代码

的错误

1 个答案:

答案 0 :(得分:0)

bindValue中提供第三个参数(适当的数据类型):

更改以下行:

$sql->bindValue(':provcode', $x);

$sql->bindValue(':provcode', $x, PDO::PARAM_STR);// This will work if your provcode is of type int, provide appropriate datatype