简体   繁体   English

查询在正确执行时未获取数据

[英]Query does not fetch data while it executes correctly

I find it very strange but something does not feel right. 我觉得这很奇怪,但是感觉不对。 I want to populate a JSON Array with data from mysql. 我想用来自mysql的数据填充JSON数组。 The first query will bring data for categories and questions and then for each question i want to get the answers. 第一个查询将带入有关类别和问题的数据,然后针对每个我想得到答案的问题。 I get the data from 1st query but from second i do not. 我从第一查询中获取数据,但是从第二查询中我没有。

My code: 我的代码:

<?php
error_reporting(E_ALL ^ E_NOTICE);
ini_set("default_charset", "UTF-8");
header('Content-type: text/html; charset=UTF-8');
try {
    $handler = new PDO('mysql:host=localhost;dbname=database', 'root', '');
    $handler->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES utf8");
    $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $handler->exec("SET CHARACTER SET 'utf8'"); 
} catch (Exception $e) {
    echo $e->getMessage();
    die();
}

$query = $handler->query('SELECT DISTINCT c.cat_name, c.cat_id, q.question FROM `categories` c
LEFT JOIN `questions` q ON c.cat_id = q.cat_id WHERE c.cat_id = 1');
$records = array();

$records = $query->fetchAll(PDO::FETCH_ASSOC);
echo "<pre>";
print_r($records);
echo "</pre>";
$answers = array();
foreach($records as $k => $v){
    $ques = $v['question'];
    $ques = trim($ques);
    $qu = $handler->query("SELECT a.answer, a.iscorrect FROM `answers` a INNER JOIN `questions` q ON a.quest_id = q.q_id WHERE q.question = '".$ques."' ");
    echo "SELECT a.answer, a.iscorrect FROM `answers` a INNER JOIN `questions` q ON a.quest_id = q.q_id WHERE q.question = '".$ques."'<br>";
    $answers = $qu->fetch(PDO::FETCH_BOTH);
    /*$answers = $qu->fetchAll(PDO::FETCH_ASSOC);
    foreach ($answers as $key => $value) {
        echo "Key: " . $key . " Value: " . $value;
    }
    //$answersR = $qu->fetchAll(PDO::FETCH_ASSOC);*/
    echo "<pre>";
    print_r($answers);
    echo "</pre>";
}
$j['quiz'] = $json;
echo json_encode($j);
/*$json[] = array(
        "category_name" => $v['cat_name'], "category_id" => $v['cat_id'],  "question_name" => $v['question'],
        "answers" => array(
            "answer" => $answers['answer'],
            "iscorrect" => $answers['iscorrect']
    ));*/
?>

UPDATE 更新

I managed to fix it with this code: 我设法用以下代码修复它:

foreach($records as $k => $v){
    $a[] = array("category_name" => $v['cat_name'], "category_id" => $v['cat_id'],  "question_name" => $v['question'], "question_answers" => array() );
    $normal[] = $v['question'];
}
foreach ($normal as $key => $value) {
        $ques = $value;
        $qu = $handler->query("SELECT a.answer, a.iscorrect FROM `answers` a INNER JOIN `questions` q ON a.quest_id = q.q_id WHERE q.question = '".$ques."' ");
        $ans = $qu->fetchAll(PDO::FETCH_ASSOC);
        foreach ($ans as $key => $value) {
            $times[] = array('answer' => $value['answer'], 'iscorrect' => $value['iscorrect']);
        }
}

Now i want for each item in the a array the array "question_answers" to be populated with the values of each item of the array times. 现在,我要为数组中的每个项目使用数组时间每个项目的值填充“ question_answers”数组。

I have tried this: 我已经试过了:

foreach ($times as $w => $e) {
    $a['question_answers'][]  = array("answer" => $e['answer'], "iscorrect" => $e['iscorrect']);
}

But it does not give me the desired result. 但这并没有给我想要的结果。

I want result to be like this: 我希望结果是这样的:

"category_name" => categoryname,
"category_id" => categoryid,
"question_name" => questionname,
"question_answers" =>[
    "answer" => answer1,
    "iscorrect" => yes,

    "answer" => answer2,
    "iscorrect" => no,

    "answer" => answer3,
    "iscorrect" => no,
]

How is this possible to do. 这怎么可能。 With the last method i tried it does not work. 我尝试的最后一种方法不起作用。 gives me empty array. 给我空数组。

I have tried while loops and foreach but still nothing. 我尝试了while循环和foreach,但还是没有。 I would appreaciate any help! 我将不胜感激!

I believe that the problem is that you're using the same PDO resource for both queries. 我认为问题在于您在两个查询中都使用了相同的PDO资源。 Try adding $handler->closeCursor() before your foreach loop. 尝试在foreach循环之前添加$handler->closeCursor()

You should also probably be using a prepared statement within the loop. 您可能还应该在循环中使用准备好的语句。

Finally i managed to solve it like this: 最后,我设法解决了这个问题:

I executed the 1st query that returned 2 arrays for me. 我执行了第一个查询,该查询为我返回了2个数组。 1 with the normal data and 1 with just questions in it using this code: 使用以下代码,其中1个包含正常数据,而1个包含问题:

$query = $handler->query('SELECT DISTINCT c.cat_name, c.cat_id, q.question FROM `categories` c
INNER JOIN `questions` q ON c.cat_id = q.cat_id WHERE c.cat_id = 1');
$records = array();
$records = $query->fetchAll(PDO::FETCH_ASSOC);
$a = array();
$ans = array();
foreach($records as $k => $v){
    $first[] = array("category_name" => $v['cat_name'], "category_id" => $v['cat_id'],  "question_name" => $v['question'], "question_answers" => array());
    $second[] = $v['question'];
}

Then i looped through the second array with another foreach to execute second query like this: 然后,我与另一个foreach遍历第二个数组,以执行第二个查询,如下所示:

foreach ($second $key => $value) {
        $ques = $value;
        $qu = $handler->query("SELECT a.answer, a.iscorrect FROM `answers` a INNER JOIN `questions` q ON a.quest_id = q.q_id WHERE q.question = '".$ques."' ");
        $third = $qu->fetchAll(PDO::FETCH_ASSOC);
        foreach ($first as $k => $v) {
            $first[$key]['question_answers'] = $third;
        }
}

and then i got the desired result. 然后我得到了预期的结果。 Thanks everyone for your time. 谢谢大家的宝贵时间。

Hope i help someone!!! 希望我能帮助一个人!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM