user82302124
user82302124

Reputation: 1143

Combining two query results - php, mysql

So I'm doing something wrong (new to PHP) and I think the issue is related to my inexperience with manipulating arrays in php.

    $query2 = "SELECT * FROM birds where breed = '".$row['breed']."' and wing_span = '".$row['wing_span']."' and id != '".$row['id']."' limit 4";
    $s_query = mysql_query($query2);

    $theArray = array();

    $counter = 0;
    while($row3 = mysql_fetch_assoc($s_query)) {
        $counter = $counter + 1;
        array_push($theArray, $row3);
    }

    if($counter < 4) {
        $new_limit = 4 - $counter;

        $query5 = "SELECT * FROM birds where breed = '".$row['breed']."' and id != '".$row['id']."' limit ".$new_limit."";
        $s_query2 = mysql_query($query5);

        $counter = 0;
        while($row5 = mysql_fetch_assoc($s_query2)) {
            $counter = $counter + 1;
            array_push($theArray, $row5);
        }
    }

The goal is that if I don't reach the maximum of 4 in the first query, I will run a second query with the difference in MAX - count as the limit. But when I run that query, I try to add the rows ($s2_query) to the existing rows ($s_query)

In this attempt, I tried to create a new array, push the elements as I go. I've tried manually combining them too (array_merge), but also didn't work.

Edit It's intentional for there to be two queries. Point is that if the first query doesn't give me a total of 4 results, I run a second query to fill the remaining spots.

Upvotes: 0

Views: 5619

Answers (2)

Tieme
Tieme

Reputation: 65389

Edited answer deceze suggested a UNION in the comments which i think should work fine, try:

$query = "(SELECT *, 1 as SORY_QUERY1 FROM birds where breed = '".$row['breed']."' and wing_span = '".$row['wing_span']."' and id != '".$row['id']."') UNION (SELECT *, 2 FROM birds where breed = '".$row['breed']."' and id != '".$row['id']."') ORDER BY SORY_QUERY1 LIMIT 0, 4";

$theArray = mysql_fetch_array($s_query);

var_dump($theArray); //to debug

btw, you can just use

$theArray[] = $row5;

instead of

array_push($theArray, $row5);

Upvotes: 2

dagfr
dagfr

Reputation: 2384

As deceze said, only 1 request with UNION would best fit your needs.

Btw, use limit as a range

LIMIT 0, 4

Regards,

Upvotes: 0

Related Questions