我正在尝试将查询结果添加到数组中。我的while语句有效,但我的数组中没有任何内容。这是我的代码:
$res=$pdo->query("select * from questions where category_id='$category' ORDER BY RAND()");
$rows = $res->rowCount();
if ($rows < 1){
echo "There is no question in the database";
exit();}
$questionsArray = array();
while ($item = $res->fetch(PDO::FETCH_ASSOC)){
$questionsArray[] = $item;
echo "There should be some info here<br>";
}
答案 0 :(得分:-1)
您可能希望通过PDO准备好的语句来考虑这样的事情。 另外,带有fetch的while循环是糟糕而缓慢的,并且在15年前用MySQL很好。
这是正确的方法。
define("SQLHOST", "127.0.0.1");
define("SQLUSER", "user");
define("SQLPASS", "password");
define("SQLSGBD", "database");
try {
$con = new PDO('mysql:host=' . SQLHOST . ';dbname=' . SQLSGBD . ';charset=UTF8', SQLUSER, SQLPASS);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
var_dump('Connection failed: ' . $e->getMessage());
}
$categories = ['A', 'B', 'C'];
$questionsArray = array();
$stmt = $con->prepare("select * from questions where category_id=? ORDER BY RAND()");
foreach ($categories as $key => $cat) {
$stmt->bindParam(1, $cat, PDO::PARAM_STR);
$stmt->execute();
$obj = $stmt->fetchall(PDO::FETCH_ASSOC);
if (count($obj) !== 0) {
foreach ($obj as $key2 => $item) {
$questionsArray[] = [$cat => $item];
}
}
}