Pdo查询只在第一次工作


pdo query only works the first time

我已经搜索和搜索,但找不到我做错了什么,所以这是我的第一个StackOverflow问题。

我正试图查询我的实体表以获取关于我的实体的信息,包括地址表上对应地址的id,但我只能进行一次查询。第二个查询给出错误"No database selected"。对于测试,我已经尝试使用完全相同的函数两次,以确保它不是语法错误,这是我得到的结果:

名称:狼,德米特里

第二次尝试相同的查询:

没有选择数据库

:

$entity_id=1;
$row = getEntityById($entity_id);
echo "<p>name:" . $row['entity_name'] . "</p>";
echo "<p>second try to same query:</p>";
$row = getEntityById($entity_id);
echo "<p>name:" . $row['entity_name'] . "</p>";
function dbConnect ()
{
    require_once ('dogs.php');
    try {
        $conn = new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
        return $conn;
    } catch (PDOException $e) {
        return null;
    }
}
function getEntityById ($id)
{
    unset($conn);
    $conn=dbConnect();
    $sql = "select * from entity where id = $id";
    $result = $conn->query($sql);
    $error = $conn->errorInfo();
    if (isset($error[2])) die($error[2]);
    $numRows = $result->fetchColumn();
    $result->closeCursor();
    $theRow = null;
    foreach ($conn->query($sql) as $row) {
        $theRow = $row;
    }
    return $theRow;
}

我不知道我做错了什么。关闭光标似乎没有帮助。有人有什么想法吗?谢谢。

Dmitri,只需更改require_once ('dogs.php');command ('dogs.php');

问题是每次调用函数时都需要dogs.php文件,但是,正如您可能知道的,require_once每次执行时只调用一次文件。只要改一下就行了。

欢呼,