Conditional counting of records - php

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 .....

Related

How to combine multiple query's into one?

I am running a line graph on RGraph framework, and I am using a SELECT COUNT statement for rejected, accepted, approved etc.....counting how many items was rejected or accepted etc and then dumping the query data into an array, However I am looking for an easier way to implement this query, instead of running a query on each unique row value, also thinking in the way if I have to encounter other column data besides rejected, accepted or etc....I wouldnt, my code doesnt seem very scalable then. Please help
So far, I am running a query for each keyword, hope my code explains this.
The final variable is what i am feeding to RGRAPH, This works fine as it is, however it isn't the right way, and not very scalable, should my row data change.
<?php
$cxn = mysqli_connect("localhost","root","", "csvimport");
$query = "SELECT COUNT(*) FROM table_1 WHERE conclusion = 'rejected'";
$result = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$display = mysqli_fetch_array($result);
$rejected = $display[0];
//echo $rejected;
$query = "SELECT COUNT(*) FROM table_1 WHERE conclusion =
'accepted'";
$result = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$display = mysqli_fetch_array($result);
$accepted = $display[0];
//echo $accepted;
$query = "SELECT COUNT(*) FROM table_1 WHERE conclusion = '-'";
$result = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$display = mysqli_fetch_array($result);
$dash = $display[0];
//echo $dash;
$query = "SELECT COUNT(*) FROM table_1 WHERE conclusion =
'approved'";
$result = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$display = mysqli_fetch_array($result);
$approved = $display[0];
//echo $approved;
$datarray = [$rejected, $accepted, $dash, $approved];
print_r($datarray);
$data_string = "[" . join(", ", $datarray) . "]";
echo "<br>";
print_r($data_string);
?>
You can just use GROUP BY and add the conclusion column to the result set, so
SELECT conclusion, COUNT(*) as total
FROM table_1
WHERE conclusion in ('rejected', 'accepted', '-', 'approved')
GROUP BY conclusion
Then retrieve each row of the result set
$totals = [];
while($row = mysqli_fetch_array($result)) {
$totals [$row[0]] = [$row[1]];
}
and $totals will be an array something like
array( 'accepted' => 12,
'approved' => 20...)
If you want all of the conclusions, then just remove the WHERE conclusion in line and it will return all of the possibilities along with the count.

How can i join or implode the below array code?

In the below code i want to join or implode all arrays of $trackersurl in a single line. i am getting the results in different lines, so i want to join in a single line.
Can anyone help me out?
I am searching results in stackoverflow, but could not follow.
My code is in below:
$sql = "SELECT * FROM announce WHERE torrent = $id ORDER BY seeders DESC";
$query = #mysql_query($sql);
while ($result = #mysql_fetch_array($query)) {
$trackersurl1 = $result['url'];
$trackersurl2 = "&tr=".$trackersurl1;
$trackersurl = array($trackersurl2);
}
Results of [var.trackersurl] in html page is below:
&tr=http:ajgdsjhg/ann
&tr=udp://iuysidfu/ann
&tr=udp:wutefghgw/ann
&tr=http://sdhgsjdhgj/ann
I want to join them in a single line below
&tr=http:ajgdsjhg/ann&tr=udp://iuysidfu/ann&tr=udp:wutefghgw/ann&tr=http://sdhgsjdhgj/ann
You should be careful of sql injection.
Are you looking to create an array['trackers'] with a string of all the trackers for a magnet link?
<?php
$sql = "SELECT * FROM announce WHERE torrent = ".mysql_real_escape_string($id)." ORDER BY seeders DESC";
$query = mysql_query($sql);
$tracker = null;
if(mysql_num_rows($query)>=1){
while ($result = mysql_fetch_array($query)) {
$tracker .= "&tr=".$result['url'];
}
}
$tracker = array('trackers'=>$tracker);
//$tracker['trackers'] = "&tr=a.com&tr=b.com&tr=c.com";
?>
Try this code
$newArray=array();
while ($result = #mysql_fetch_array($query)) {
$trackersurl1 = $result['title'];
$newArray[] = "&tr=".$trackersurl1;
}
$urlString=implode('',$newArray);

Creating an array of IDs from a while loop

Im trying to generate an array but not sure how to go about it.
I'm currently getting my data like so:
$query = mysql_query("SELECT * FROM users WHERE userEmail LIKE 'test#test.com'");
$row = mysql_fetch_array($query);
$query1 = mysql_query("SELECT * FROM categories");
while($row1 = mysql_fetch_array($query1)){
$query2 = mysql_query("SELECT * FROM usersettings WHERE userId = ".$row['userId']." AND usersettingCategory".$row1['categoryId']." LIKE 'y'");
$isyes = mysql_num_rows($query2);
if($isyes > 0){
$cat1 = mysql_query("SELECT * FROM shops WHERE shopstateId = 1 AND (categoryId1 = ".$row1['categoryId']." OR categoryId2 = ".$row1['categoryId']." OR categoryId3 = ".$row1['categoryId'].")");
$cat1match = mysql_num_rows($cat1);
if($cat1match > 0){
while($cat1shop = mysql_fetch_array($cat1)){
$cat1msg = mysql_query("SELECT * FROM messages WHERE shopId = ".$cat1shop['shopId']." and messagestateId = 1");
while($cat1msgrow = mysql_fetch_array($cat1msg)){
echo $cat1msgrow['messageContent']." - ".$cat1msgrow['messageCode'];
$cat1img = mysql_query("SELECT shopimagePath FROM shopimages WHERE shopimageId = ".$cat1shop['shopimageId']);
$imgpath = mysql_fetch_array($cat1img);
echo " - ".$imgpath['shopimagePath']."<br/>";
}
}
}
}
}
But this can cause duplicates when a user has all 3 of a shops categories picked in their preferences. I am trying to find a way to just pull the message ID out instead of the whole thing and put it into an array giving me, for example:
1,3,5,7,1,3,5,2,4,7,8
Then I can just run a separate query to say get me all messages where the ID is in the array, but i am unsure of the most constructive way to build such an array and examples of array from a while loop I have seen do not seem to be what I am looking for.
Is there anyone out there that can push me in the right direction?
Can't help with this code. But if you want an array from a query without duplicate result, you can use " select DISTINCT (id) " in your query or for more simple solution :
$id_arr = array();
$sql = mysql_query("select id from id_table");
while ($id_result = mysql_fetch_array($sql) {
$id = $id_result['id'];
if (!in_array($id, $id_arr)) {
$id_arr[] = $id;
}
}
I have found a much easier way to create the required result. I think at 6am after a hard night coding my brain was fried and I was making things a lot more complicated than I needed to. A simple solution to my issue is as follows:
$query = mysql_query("SELECT * FROM users WHERE userEmail LIKE 'test2#test2.com'");
$row = mysql_fetch_array($query);
$categories = "(";
$query1 = mysql_query("SELECT * FROM categories");
while($row1 = mysql_fetch_array($query1)){
$query2 = mysql_query("SELECT usersettingCategory".$row1['categoryId']." FROM usersettings WHERE userId = ".$row['userId']);
$row2 = mysql_fetch_array($query2);
if($row2['usersettingCategory'.$row1['categoryId']] == y){
$categories .= $row1['categoryId'].",";
}
}
$categories = substr_replace($categories ,")",-1);
echo $categories."<br />";
$query3 = mysql_query("SELECT * FROM shops,messages WHERE shops.shopId = messages.shopId AND messages.messagestateId = 1 AND (shops.categoryId1 IN $categories OR shops.categoryId2 IN $categories OR shops.categoryId3 IN $categories)");
while($row3 = mysql_fetch_array($query3)){
$query4 = mysql_query("SELECT shopimagePath FROM shopimages WHERE shopimageId = ".$row3['shopimageId']);
$row4 = mysql_fetch_array($query4);
echo $row3['messageContent']." - ".$row3['messageCode']." - ".$row4['shopimagePath']."<br />";
}

SQL QUERY returning all results using OR in WHERE statement

Hoping I am just missing something simple here:
$sql = "Select * FROM user_info, user_login WHERE user_login.status = '0' OR user_login.status = '2' AND user_info.uid = user_login.uid";
$db = new connection();
$results = $db->query($sql);
$user = array();
while($info = mysql_fetch_array($results))
{
$user[] = $info;
}
$total = count($user);
//TEST the amount of rows returned.
echo $total;
for ($i = 0; $i < $total; $i++)
{
//echo data;
}
just trying to pull all data that has the user_login.status field set to "0" or "2" but it shows everything thing and it shows the items marked as 2 twice.
Does anyone see my issue?
Your precedence is getting whacked because of missing parentheses:
SELECT DISTINCT *
FROM user_info, user_login
WHERE (user_login.status = '0' OR user_login.status = '2')
AND user_info.uid = user_login.uid
Without seeing the data I can't give you more than a SELECT DISTINCT with regards to the duplicate records.
Select * FROM user_info, user_login WHERE (user_login.status = '0' OR user_login.status = '2') AND user_info.uid = user_login.uid
Order of precedence :)

how can i controll while loop into another while loop

Suppose I have a while loop like:
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
}
then if first query return 5 results i.e 1-5 and second query returns 3 results than if i want to echo out second query it gives me like this..........
111112222233333
than how can i fix to 123 so that the second while loop should execute according to number of times allowed by me........!! how can i do that.........!!
I'm not sure I 100% understand your question - it's a little unclear.
It's possible you could solve this in the query with a GROUP BY clause
$sql_2 = mysql_query("SELECT id FROM secondtable WHERE id != $id GROUP BY id");
But that would only work if you need just secondtable.id and not any of the other columns.
When you say "number of time allowed by me" do you mean some sort of arbitrary value? If so, then you need to use a different loop mechanism, such as Greg B's solution.
Do you want to explicitly limit the number of iterations of the inner loop?
Have you considered using a for loop?
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
for($i=0; $i<3; $i++){
$ro = mysql_fetch_array($sql_2);
$id2 = $ro["id2"];
echo $id2;
}
}
Your first while loop is iterating over all 5 results, one at a time.
Your second while loop is iterating over each of the 5 results, producing it's own set of results (i.e. 3 results for each of the 5 iterations, totaling 15 results).
I believe what you are trying to do is exclude all IDs found in your first loop from your second query. You could do that as follows:
$sql = mysql_query("SELECT * FROM tablename");
$exclude = array();
while($row = mysql_fetch_array($sql)) {
array_push($exclude, $row['id']);
}
// simplify query if no results found
$where = '';
if (!empty($exclude)) {
$where = sprintf(' WHERE id NOT IN (%s)', implode(',', $exclude));
}
$sql = sprintf('SELECT * FROM secondtable%s', $where);
while($row = mysql_fetch_array($sql_2)) {
$id2 = $row["id2"];
echo $id2;
}
$sql = mysql_query("SELECT * FROM tablename");
$tmp = array();
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
if(!in_array($id, $tmp)) {
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
$tmp[] = $id;
}
}
Saving all queried $id's in an array to check on the next iteration if it has already been queried. I also think that GROUPing the first query result would be a better way.
I agree with Leonardo Herrera that it's really not clear what you're trying to ask here. It would help if you could rewrite your question. It sounds a bit like you're trying to query one table and not include id's found in another table. You might try something like:
SELECT * FROM secondtable t2
WHERE NOT EXISTS (SELECT 1 FROM tablename t1 WHERE t1.id = t2.id);

Categories