Get the first 3 results in a mysql_query query

2

I'm retrieving data from the database that would be "The Indicator of the Indicated", but it catches all up to retrieve all. What I need to do is get only the first 3 results.

And if I tell you how many results I want to get, that is, set this in the function or in some variable and when I get the X value of the variable, then it stops searching because it does not have any more need.

Currently I have done this function, but it is returning all the right data, but it is returning more than 3 and I only want 3 for now. I need to get the top 3 only.

<?php
$db = mysql_connect('localhost', 'root', 'vertrigo');
$bd = mysql_select_db('cotas', $db);

$array = array();

function indicadores($id){

    global $array;

    $query = mysql_query("SELECT * FROM indicadores WHERE id_indicado = '$id'");

    if(mysql_num_rows($query) > 0){

        $fetch = mysql_fetch_object($query);

        $id = $fetch->id_indicador;

        $array[] = $id;

        indicadores($id);

    }
}

indicadores(10);

echo var_dump($array);
?>
    
asked by anonymous 15.01.2016 / 03:43

3 answers

6

If I understand correctly, you just have to change your SQL query.

Try this:

$query = mysql_query("SELECT * FROM indicadores WHERE id_indicado = '$id' LIMIT 3 ORDER BY id_indicado DESC");
    
15.01.2016 / 03:51
1

I took the liberty of making some changes to your code. Note, you should not use mysql_, are deprecated functions and will no longer work in future versions of php. Use mysqli_. Note: Test the query in a phpmyadmin or whatever you have, to see if it is returning data, if the query is correct.

<?php
$db = mysqli_connect('localhost', 'root', 'vertrigo');
$bd = mysqli_select_db($db, 'cotas');

function indicadores($id){

    global $db;

    $array = array();

    $query = mysqli_query($db, "SELECT * FROM indicadores WHERE id_indicado = '$id' ORDER BY id_indicador DESC LIMIT 3");
    if(mysqli_num_rows($query) > 0){

        while($fetch = mysqli_fetch_object($query)){
            $id = $fetch->id_indicador;
            $array[] = $id;
        }

    }

    return $array;
}

$array = indicadores(10);

var_dump($array);
    
15.01.2016 / 04:24
0

RESOLVED

I found this solution:

<?php
$db = mysql_connect('localhost', 'root', 'vertrigo');
$bd = mysql_select_db('cotas', $db);

$array = array();

function indicadores($id, $niveis){

    global $array;

    if($niveis > 0){

    $query = mysql_query("SELECT * FROM indicadores WHERE id_indicado = '$id'");

        if(mysql_num_rows($query) > 0){

            $fetch = mysql_fetch_object($query);

            $id = $fetch->id_indicador;

            $array[] = $id;

            indicadores($id, $niveis-1);

        }

    }
}

indicadores(10, 3);

echo var_dump($array);
?>
    
15.01.2016 / 04:21