Problem with function

0

I am creating a blog and the following function has been created to take the topics of the blog:

function getPostTopic($post_id) {
    global $conn;
    $sql = "SELECT * FROM topics WHERE id=
            (SELECT topic_id FROM post_topic WHERE post_id=$post_id) LIMIT 1";
    $result = mysqli_query($conn, $sql);
    $topic = mysqli_fetch_assoc($result);
    return $topic;
}

Which gives me an error:

  

Warning: mysqli_fetch_assoc () expects parameter 1 to be mysqli_result, boolean given in   C: \ wamp \ www \ includes \ public_functions.php on line 30

    
asked by ricardo leiva sikic 15.11.2018 в 22:00
source

1 answer

1

If you are going to use a sub-query as a criterion you must ensure that it returns a single row / column.

To do this, you must move the parenthesis at the end:

function getPostTopic($post_id){
    global $conn;
    /*¿La conexión es válida?*/
    if($conn){
        $sql = "SELECT * FROM topics WHERE id=
               (SELECT topic_id FROM post_topic WHERE post_id=$post_id LIMIT 1)";
        /*¿Es correcta la consulta?*/
        if($result = mysqli_query($conn, $sql)){
            $topic = mysqli_fetch_assoc($result);
        }else{
            $topic="Error en la consulta: ".mysqli_error($conn);
        }
    }else{
        $topic="Error en la conexión: ";
    }
    /*Prueba*/
    var_dump($topic);
    return $topic;
}

The LIMIT 1 is the one that indicates to the sub-query that must return a single row. If you close the parenthesis before, you would be indicating the limit to the entire query, and you will have this error:

  

Subquery returns more than 1 row

    
answered by 15.11.2018 / 22:25
source