Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php pdo查询只在第一次工作_Php_Mysql_Database_Pdo_Connection - Fatal编程技术网

Php pdo查询只在第一次工作

Php pdo查询只在第一次工作,php,mysql,database,pdo,connection,Php,Mysql,Database,Pdo,Connection,我搜索了又搜索,但找不到我做错了什么,所以这里是我的第一个问题 我试图对我的实体表进行查询,以获取有关我的实体的信息,包括地址表上相应地址的id,但我只能进行一次查询。第二个查询给出错误“未选择数据库”。为了进行测试,我尝试使用完全相同的函数两次,以确保它不是语法错误,我得到的结果如下: 姓名:沃尔夫,德米特里 第二,尝试相同的查询: 未选择任何数据库 根据该代码: $entity_id=1; $row = getEntityById($entity_id); echo "<p>na

我搜索了又搜索,但找不到我做错了什么,所以这里是我的第一个问题

我试图对我的实体表进行查询,以获取有关我的实体的信息,包括地址表上相应地址的id,但我只能进行一次查询。第二个查询给出错误“未选择数据库”。为了进行测试,我尝试使用完全相同的函数两次,以确保它不是语法错误,我得到的结果如下:

姓名:沃尔夫,德米特里

第二,尝试相同的查询:

未选择任何数据库

根据该代码:

$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;
}
$entity_id=1;
$row=getEntityById($entity\u id);
回声“名称:”$行['entity_name']。“

”; echo“第二次尝试相同的查询:

”; $row=getEntityById($entity\u id); 回声“名称:”$行['entity_name']。“

”; 函数dbConnect() { 一次需要_('dogs.php'); 试一试{ $conn=newpdo(“mysql:host=$host;dbname=$db”,$user,$pwd); 返回$conn; }捕获(PDO$e){ 返回null; } } 函数getEntityById($id) { 未结算($康涅狄格); $conn=dbConnect(); $sql=“从id=$id的实体中选择*”; $result=$conn->query($sql); $error=$conn->errorInfo(); 如果(isset($error[2])死亡($error[2]); $numRows=$result->fetchColumn(); $result->closeCursor(); $theRow=null; foreach($conn->query($sql)作为$row){ $theRow=$row; } 返回$theRow; }
我不知道我做错了什么。关闭光标似乎没有帮助。 有人有什么想法吗?
谢谢。

Dmitri,只需更改require_一次('dogs.php');需要('dogs.php')

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


干杯,

我想这可能是由于一个例外。。调试引发的异常。。只需输出$e堆栈跟踪,并确认如果再次尝试连接到db,是否存在异常..太棒了。谢谢你,麦地那!