Running 2 database querys from an array - php

I am trying to run 2 database querys the second using an array from the first, any one have any ideas why this stops the page from loading?
$query = $this->db->query("SELECT category_id FROM listings WHERE listing_id = '1' LIMIT 1");
foreach ($query->result() as $row)
{
$query2 = $this->db->query("SELECT listing_title FROM listings WHERE listing_type = '".$row->category_id."' ORDER BY RAND() LIMIT 2");
foreach ($query2->result() as $row)
{
echo $row->listing_title;
}
}

You are overwriting the outer $row in your inner loop
$query = $this->db->query("SELECT category_id FROM listings WHERE listing_id = '1' LIMIT 1");
foreach ($query->result() as $row)
{
$query2 = $this->db->query("SELECT listing_title FROM listings WHERE listing_type = '".$row->category_id."' ORDER BY RAND() LIMIT 2");
foreach ($query2->result() as $row2) // <--- $row2 not $row
{
echo $row2->listing_title;
}
}

Try this:
(Take advantage of prepare statements, the prepare() function, etc)
$query = "SELECT category_id FROM listings WHERE listing_id = '1' LIMIT 1;";
$query2 = "SELECT listing_title FROM listings WHERE listing_type = :categoryId ORDER BY RAND() LIMIT 2;";
$db = $this->db;
$statement = $db->prepare($query);
$statement->execute();
$statement->setFetchMode(PDO::FETCH_ASSOC);
while($row = $statement->fetch())
{
$categoryId = $row['category_id'];
$statement2 = $db->prepare($query2);
$statement2->execute(array(':categoryId' => $categoryId));
$statement2->setFetchMode(PDO::FETCH_ASSOC);
while($row2 = $statement2->fetch())
{
$listingTitle = $row2['listing_title'];
echo $listingTitle;
}
}

This is not very good code. Why use a foreach loop when the Select query has Limit 1?
Since you are going for a category id where listing_id=1 (with LIMIT 1), your code could just be shortened to:
SELECT listing_title FROM listings WHERE listing_id=1 ORDER BY RAND() LIMIT 2
Also, ORDER BY RAND() is a big resource killer on large tables. I recommend finding a more proper way to order your results.
EDIT: Full code that I would use:
$db=$this->db; //Just so we don't have to keep referencing $this (assuming you are not in a class)
$sql="SELECT listing_title
FROM listings
WHERE listing_id=?
ORDER BY RAND()
LIMIT 2";
$statement=$db->prepare($sql);
$statement->execute(array(1));
while($result=$statement->fetchObject()){
echo $result->listing_title;
}

Related

sql statement select from DB limit didn't work

i have a question which is my limit statement didn't work i want the content select from database and limit the show content in 40 only but it didn't work
here is my SQL statement with php code
$chatroomID=$_GET['chatroomID'];
$userID = $_SESSION['id'];
$sql="SELECT * FROM chatroom_chat WHERE chatroom_id ='$chatroomID'";
$result1 = mysqli_query($connection, $sql) or die(mysqli_error($connection));
while ($row = mysqli_fetch_array($result1)) {
$chat = $row['chat_id'];
$sql3 ="SELECT * FROM (
SELECT * FROM chat WHERE id = '$chat' ORDER BY id DESC LIMIT 0,40
) sub
ORDER BY id ASC ";
$getChatData = mysqli_query($connection,$sql3) or die(mysqli_error($connection));
/*here have statement to get username*/
while($row3 = mysqli_fetch_array($getChatData)) {
echo "<div>all content</div>";
}
}
does my code have any syntax error? i no sure why it didn't work
SELECT * FROM (
SELECT * FROM chat WHERE id = '$chat' ORDER BY id DESC LIMIT 40
) sub
ORDER BY id ASC

How to select rows in MySQL/PHP?

I am trying to display my first 10 users and their information by uid. When I use the code below, it only returns a single uid:
include "db_conx.php";
$sql = ('SELECT uid,username,country FROM users ORDER BY uid DESC LIMIT 10');
$result = mysqli_query($db_conx, $sql);
echo $result->fetch_object()->uid;
What function am I supposed to use to display rows correctly?
include "db_conx.php";
$sql = ('SELECT uid,username,country FROM users ORDER BY uid DESC LIMIT 10');
$result = mysqli_query($db_conx, $sql);
while($var = $result->fetch_object()->uid){
echo $var;
}
Should do the trick
If you get a list of object you should use a loop for show them
include "db_conx.php";
$sql = ('SELECT uid,username,country FROM users ORDER BY uid DESC LIMIT 10');
$result = mysqli_query($db_conx, $sql);
while($row = mysqli_fetch_object($result)) {
$row->uid;
}

Need help in displaying last 5 rows. PHP, MYSQL

Can anyone tell me what am I doing wrong. I would like to display the last 5 rows in desc order.
$pull_activity_logs = mysql_query("SELECT * FROM activity_logs WHERE ac_no = '$logined_acc' order by id desc limit 0,5")
or die(mysql_error());
while($row = mysql_fetch_array( $pull_activity_logs )) {
$activity_time = $row["datetime"];
$activity = $row["activity"];
}
echo "$activity";
Help would be deeply appreciated
Well, you can always select the first five in asc order, that would be last five in desc order, and then you could reverse their order in php if needed (5 values isnt anything what an array couldn't handle)
CODE:
$pull_activity_logs = mysql_query("SELECT * FROM activity_logs WHERE ac_no = '$logined_acc' order by id asc limit 5");
$temp_arr = array();
while($row = mysql_fetch_array( $pull_activity_logs )) {
$temp_arr[] = $row; //add to end
}
$final_arr = array_reverse($temp_arr);
foreach($final_arr as $row) //this doesn't have to be named $row
$activity_time = $row["datetime"];
$activity = $row["activity"];
echo "$activity";
}
EDIT:
now when i look at it maybe whole problem was in wring position of your echo:
$pull_activity_logs = mysql_query("SELECT * FROM activity_logs WHERE ac_no = '$logined_acc' order by id desc limit 0,5")
or die(mysql_error());
while($row = mysql_fetch_array( $pull_activity_logs )) {
$activity_time = $row["datetime"];
$activity = $row["activity"];
echo "$activity"; //this goes INSIDE the loop
}
You can retrieve the first five in ascending order and then order them in SQL by using a subquery:
select al.*
from (SELECT al.*
FROM activity_logs al
WHERE ac_no = '$logined_acc'
order by id asc
limit 0, 5
) al
order by id desc;

Echo the 2 last columns of tabel

I have a table and i want to echo the 2 last rows of my tabel, I used the below code but just the last one showed, what is the problem.
$result1 =(mysql_fetch_array(mysql_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2")));
Print $result1['time'];
mysql_fetch_array = 1 fetch.
do it again for fetching 2nd result.
Also, use mysqli eh.
You're doing mysql_fetch_array only one time, so it gets the first element. If you want to get all the elements, then do it again, or use a loop.
Something like:
$query = "SELECT * FROM $table ORDER BY id DESC LIMIT 2";
while($row = mysql_fetch_array(mysql_query($query) )
{
echo $row['time'].'<br>';
}
For 2 Or more rows you need to loop it
$sql = mysql_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2")
while($row=mysql_fetch_array($sql))
{
echo $row['time']."<br>";
}
$query = mysqli_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2");
while ($result = mysqli_fetch_array($query)) {
echo $result['time'];
}
Gives out every return of your database (2 in this case). You should use mysqli_-functions.
Maybe you should try like this, since mysql_fetch_array returns only one row
while ($row = mysql_fetch_array($yourQuery)) {
echo $row["yourAlias"];
}
Further details here : http://fr2.php.net/manual/en/function.mysql-fetch-array.php
My solution:
$limit = 2;
$sql = "SELECT * FROM $table ORDER BY id DESC LIMIT $limit";
$result = mysql_query($sql);
$array = array(); $i = 0;
while($row = mysqli_fetch_array($result))
{
$array[$i] = $row;
$i++;
}
var_dump($array[0]);
var_dump($array[1]);

PDO multiple SELECT statements

How can i do multiple select statements in one file? For example i have a list of products - i then want to get the stock level's for each of the products. However, it only ever returns the first product, not any other additional products.
$query = $db->query("SELECT * FROM `products` ORDER BY `productName` ASC");
while ($row = $query->fetch(PDO::FETCH_ASSOC)){
$productId = stripslashes($row['productId']);
$productName = stripslashes($row['productName']);
echo "<b>".$productName."</b><br />";
$query = $db->query("SELECT * FROM `stock` WHERE `productId` = $productId");
while ($row = $query->fetch(PDO::FETCH_ASSOC)){
$stockId = stripslashes($row['stockId']);
$stockFilename = stripslashes($row['stockFilename']);
}
echo "Stock level= " . $query-> rowCount();
}
Because your second $query is overwriting the first. Rename the second to $query2 (and change the the $query variables to $query2 beneath it). And change $row to $row2
By the way, you can also change your first query into a join to eliminate the second query alltogether.

Categories