我已经搜索了又搜索,但找不到我做错了什么,所以这是我的第一个 StackOverflow 问题。
我正在尝试对我的实体表进行查询以获取有关我的实体的信息,包括地址表中相应地址的 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;
}
我不知道我做错了什么。关闭光标似乎没有帮助。 有人有主意吗? 谢谢。
最佳答案
德米特里,只需更改 require_once ('dogs.php'); require('dogs.php');
问题是每次调用该函数时都需要 dogs.php 文件,但是,正如您可能知道的那样,require_once 每次执行时只调用一次文件。只需更改它即可正常工作。
干杯,
关于php - pdo 查询仅在第一次有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16512931/