take out my sql out of foreach for my code - php

I have php code like that:
$q = $db->query("SELECT * FROM tabe1_data WHERE status='1' ORDER BY id DESC LIMIT 10");
$cr_onr = array();
while($row = $db->fetchAll($q))
{
$cr_onr[] = $row;
}
?>
<?php foreach($cr_onr as $new_cr_onr):?>
<?php $crinfo = $db->fetchOne("SELECT * FROM tabe2_data WHERE id ='".$new_cr_onr['op_id']."'");?>
<p><?=$new_cr_onr['username'];?> has been complete <?=$crinfo['op_amount'];?></p>
<?php endforeach;?>
I need to take $crinfo = $db-> out of "foreach" to be before "foreach"
How i can do that please ?
Thank you.

You could join the tables instead of having many queries:
$q = $db->query("
SELECT
*
FROM
tabe1_data
INNER JOIN
tabe2_data ON tabe1_data.op_id = tabe2_data.id
WHERE
tabe1_data.status='1'
ORDER BY
tabe1_data.id DESC
LIMIT 10
");
$cr_onr = array();
while($row = $db->fetchAll($q))
{
$cr_onr[] = $row;
}
?>
<?php foreach($cr_onr as $new_cr_onr):?>
<p><?=$new_cr_onr['username'];?> has been complete <?=$new_cr_onr['op_amount'];?></p>
<?php endforeach;?>

Single joined query?
SELECT tabe2_data.*
FROM tabe2_data
LEFT JOIN tabe1_data ON tabe1_data.op_id = tabe2_data.id
WHERE tabe1_data.status='1'

Related

mySQL Order by Most Commented and Least Commented

I'm trying to order a list of items based on the amount of comments for each topic as shown below:
$page = $_GET['page'];
$query = mysql_query("SELECT * FROM topic WHERE cat_id='$page' LIMIT $start, $per_page");
if (mysql_num_rows($query)>=1)
{
while($rows = mysql_fetch_array($query))
{
$number = $rows['topic_id'];
$title = $rows['topic_title'];
$description = $rows['topic_description'];
//get topic total
$sqlcomment = mysql_query("SELECT * FROM comments WHERE topic_id='$number'");
$commentnumber = mysql_num_rows($sqlcomment);
// TRYING TO ORDER OUTPUT ECHO BY TOPIC TOTAL ASC OR DESC
echo "
<ul>
<li><h4>$number. $title</h4>
<p>$description</p>
<p>$topictime</p>
<p>$commentnumber</p>
</li>
</ul>
";
}
}
else
{
echo "<p>no records available.</p><br>";
}
What would be the best way to order each echo by $num_rows (ASC/DESC values)? NOTE: I've updated with the full code - I am trying to order the output by $commentnumber
The first query should be:
SELECT t.*, COUNT(c.topic_id) AS count
FROM topic AS t
LEFT JOIN comments AS c ON c.topic_id = t.topic_id
WHERE t.cat_id = '$page'
GROUP BY t.topic_id
ORDER BY count
LIMIT $start, $per_page
You can get $commentnumber with:
$commentnumber = $rows['count'];
You don't need the second query at all.
First of all you have error here
echo "divs in order from least to greatest "number = $num_rows"";
It should be
echo "divs in order from least to greatest number = " . $num_rows . "";
And about the most commented try with
$sql = "SELECT * FROM `table` WHERE `id` = '$id' ORDER BY column DESC/ASC";
Or if there is not count column try with
$sql = "SELECT * FROM `table` WHERE `id` = '$id' ORDER BY COUNT(column) DESC/ASC";

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]);

Conditional counting of records

Am trying to calculate the number of rows in a table depending on a certain condition.
So, I did manage to write a piece of code that would function as required.
But, it's bit too long. So am wondering if there is any easier way to achieve it.
Code:
// Comments
$sql_total_comments = mysql_query("SELECT * FROM comments");
$sql_pending_comments = mysql_query("SELECT * FROM comments WHERE comment_status = '0'");
$sql_approved_comments = mysql_query("SELECT * FROM comments WHERE comment_status = '1'");
$sql_declined_comments = mysql_query("SELECT * FROM comments WHERE comment_status = '2'");
$total_comments_num = mysql_num_rows($sql_total_comments);
$pending_comments_num = mysql_num_rows($sql_pending_comments);
$approved_comments_num = mysql_num_rows($sql_approved_comments);
$declined_comments_num = mysql_num_rows($sql_declined_comments);
SELECT comment_status, COUNT(comment_status)
FROM comments GROUP BY comment_status;
In your code, either total the counts up for the total number or run a separate query on COUNT(*) as in the other answers.
So your code would look something like this, assuming you're using PDO:
$sql = 'SELECT comment_status, COUNT(comment_status) AS "count" '.
'FROM comments GROUP BY comment_status;';
$query = $db->query($sql);
$count_total = 0;
$count = array( );
while (($row = $query->fetch(PDO::FETCH_ASSOC)) !== FALSE) {
$count_total += $row['count'];
$count[$row['comment_status']] += $row['count'];
}
$query = null; // Because I'm neurotic about cleaning up resources.
Use COUNT() DB FUNCTION to do such job.
$ret = mysql_query("SELECT COUNT(*) FROM comments");
$row = mysql_fetch_row($ret);
$total_comments_num = $row[0];
Use select count(*) from comments where .....

MySQL SUM function

I'm trying to get the sum of a column.
My Schema is as below...
I'd like to get the SUM of 'bill'.
I have the following...
<?php
$uid = $_SESSION['oauth_id'];
$query = mysql_query("SELECT * FROM `users`, `income`, `outgoings` WHERE users.oauth_uid = '$uid' and income.user_id = '$uid' and outgoings.user_id = '$uid'") or die(mysql_error());
$result = mysql_fetch_array($query);
?>
Outgoings = <?php echo $result["SUM(total)"];
I'm not receiving any output, however. Can anybody see where I'm going wrong? There's definitely data in my table.
The SUM function must be used when deciding what to return from the select. Like so.
SELECT SUM(`bill`) FROM `users`, `income`, `outgoings` WHERE users.oauth_uid = '$uid' and income.user_id = '$uid' and outgoings.user_id = '$uid'
Try this if you don't want to do a SUM() query as already proposed by others:
<?php
$sum = 0;
while ($row = mysql_fetch_array($query)) {
$sum += $row['bill'];
}
?>
Outgoings = <?php echo $sum; ?>
But remember that you will need this if you want to reuse the same $query resultset:
<?php
mysql_data_seek($query , 0);
?>
Why not just query for the SUM directly? Like:
<?php
$uid = $_SESSION['oauth_id'];
$sum = mysql_query("SELECT SUM(`bill`) FROM `users` WHERE users.oauth_uid = '$uid'") or die(mysql_error());
?>
This query will get you the sum:
SELECT sum(bill) FROM `the_table`

Categories