problem in mysql nested query in php

3

I am making a nested query to the moodle database, because I am working with your data, the problem is that when making the nested query, it does not return anything, even the common result that the arrays return when there is nothing that is [], so I am a bit confused, I would like you to help me to understand my mistake.

the code is as follows:

the service.php is simply where I make the connection to the database using PDO, so I doubt that the error is from there

<?php
include("servicio.php");

$id= $_REQUEST["id"];

$res = $cnx->query("SELECT c.fullname, a.name, a.intro 
FROM mdl_course AS c, mdl_assign AS a
WHERE c.id = a.course AND a.id IN(
SELECT s.assignment
FROM mdl_assign_submission AS s
WHERE a.id = s.assignment AND c.id IN(
SELECT l.courseid
FROM mdl_user_lastaccess AS l
WHERE l.courseid = c.id AND userid='$id'))");

if($res){
$datos = array();
foreach($res as $row){
    $datos[]=$row;
}
echo json_encode($datos);
}
?>
    
asked by Jose Pablo 28.05.2016 в 03:44
source

2 answers

1

What does $ cnx-> query () do? Do the query and bring the data? Does the query and brings you a resource? try this to see what happens:

<?php

$q = "SELECT c.fullname, a.name, a.intro 
FROM mdl_course AS c, mdl_assign AS a
WHERE c.id = a.course AND a.id IN(
SELECT s.assignment
FROM mdl_assign_submission AS s
WHERE a.id = s.assignment AND c.id IN(
SELECT l.courseid
FROM mdl_user_lastaccess AS l
WHERE l.courseid = c.id AND userid='$id'))";

echo $q , "\n";
$res = $cnx->query( $q );
echo '<pre>';print_r( $res );

and sanitize this $ id = $ _REQUEST ["id"]; to avoid SQL Injections

    
answered by 28.05.2016 в 12:39
1

Why do not you try with a while instead of a foreach? like this:

if ($res) {
    $data = array();
    while ($row = mysql_fetch_array($res)) {
        $data[] = $row;
    }
    echo json_encode($data);
}
    
answered by 28.05.2016 в 04:41