MySQL COUNT showing it's working out - php

I would expect the following to output the number "5", since there are 5 rows in the database with with item 68 and user 1. But instead I'm getting this output "12345".
$resultb4 = mysql_query("SELECT COUNT(comparedRating) FROM recComparedRating WHERE user1='1' AND itemID='68' GROUP BY itemID AND user1");
while($rowb4 = mysql_fetch_array($resultb4)){
$countcomparedratings=$rowb4['COUNT(comparedRating)'];
}
echo $countcomparedratings;
What am I doing wrong?

The reason you are getting 12345 is because your query is returning 5 results and your code to output the count is simply outputting the concatenation of the returned array from the query.
Without understanding your database structure, I'm guessing that the reason you're getting the '12345' has something to do with your GROUP BY clause. Use a program like MySQLWOrkbench to connect to your database and test out your query before you include it into your code. It is a time saving technique to debug your queries.
Also, I would alias the COUNT value so that you simply refer to the alias when you refer to your column names.
SELECT COUNT(comparedRating) as ratingCount FROM recComparedRating WHERE user1='1' AND itemID='68' GROUP BY itemID AND user1");

Related

How to display the result from mysql union query

I have a problem displaying the result from the following query:
$sql="SELECT CONCAT(threadID,'',memberID),'posts' as Type
from posts
where memberID=$userid
UNION
SELECT CONCAT(threadID,'',memberID),'replies',as Type
from replies
where memberID=$userid order by 1";
$result=mysqli_query($con,$sql);
while($row=mysqli_fetch_array($result)){
$postid=$row['thread'];
echo $postid;
}
The error I get is
undefined index threadID" $postid=$row['threadID'];
The problem is you don't have a column called "thread" in the output of your query...you aren't outputting that column, instead you're outputting the result of the CONCAT function.
If you write var_dump($row); as a debugging step inside your loop you would see what the row actually looks like.
A simple way to fix this is to give the calculated column an alias, so that it gets a sensible name in the $row variable. You can do this with the AS keyword in SQL. If you just call the alias "thread" then you won't have to change your PHP code at all:
SELECT CONCAT(threadID,'',memberID) AS thread,'posts' as Type
from posts
where memberID=$userid
UNION
SELECT CONCAT(threadID,'',memberID) AS thread,'replies',as Type
from replies
where memberID=$userid order by 1

Find JSON nth value using mysql query

I have this JSON values in MySQL database
Conditions
1- >
[{"offer_id":"158","offer_start":"2017-12-17 09:21:27","offer_ends":"2017-12-17 10:21:27"},{"offer_id":"167","offer_start":"2017-12-17 12:28:57","offer_ends":"2017-12-17 12:58:57"}]
2 ->
[{"offer_id":"170","offer_start":"2018-01-17 04:26:26","offer_ends":"2018-01-17 05:11:26"},{"offer_id":"167"}]
3 ->
[{"offer_id":"170","offer_start":"2017-12-11 20:49:12","offer_ends":"2017-12-11 20:49:12"}]
3 ->
[{"offer_id":"170"}]
So I need to get the nth offer_ends value like "2017-12-11 20:49:12" using mysql query
Considering that you need to find the data from table1 where the column name offers. You need to fetch data where the "offer_ends" has value 2017-12-11 20:49:12
SELECT JSON_CONTAINS(offers, '2017-12-11 20:49:12', '$.offer_ends')
FROM table1;
Get all the records:
SELECT offers, JSON_EXTRACT(offers, "$.offer_ends")
FROM table1
If you want then you can apply the order by on any column and then get the Top 1 record to get the last record.
Here i have one code which get all the offer_ends value by using MySQL -> SELECT REPLACE(REPLACE(JSON_EXTRACT('[{"offer_id":"23","offer_start":"2017-12-11 20:49:12","offer_ends":"2017-12-11 20:49:12"},{"offer_id":"23","offer_start":"2017-12-11 20:49:12","offer_ends":"2017-12-11 20:49:12"}]', '$[*].offer_ends'),'[',''),']','') as offer_dates
and the result is -> "2017-12-11 20:49:12", "2017-12-11 20:49:12" which shows all offer end dates
So i need to find the nth offer_ends value like this -> "2017-12-11 20:49:12"
Guys i found the solution
SELECT JSON_EXTRACT('[{"offer_id":"158","offer_start":"2018-02-21 13:03:15","offer_ends":"2018-02-21 14:03:15"},{"offer_id":"170","offer_start":"2018-02-21 15:03:15","offer_ends":"2018-02-21 16:03:15"}]',CONCAT("$[",JSON_LENGTH('[{"offer_id":"158","offer_start":"2018-02-21 13:03:15","offer_ends":"2018-02-21 14:03:15"},{"offer_id":"170","offer_start":"2018-02-21 15:03:15","offer_ends":"2018-02-21 16:03:15"}]')-1,"].offer_ends")) as offer
Thank you guys

Get row numbers from mysql_fetch_array result

I have pulled in the data from a mysql database using select * with the intention of using the data several times without doing repeated sql enquiries using WHERE.
Using this data I am extracting rows that contain a search element using
while($row=mysql_fetch_array($query_result)){ <<<if match add to new array>>> }
As there are thousands of rows this is taking a longer time than I want.
I am trying to use:
$row=mysql_fetch_array($query_result);
$a = array_search($word_to_check, $row);
echo $a;
This extracts the correct sql headings but not the row number. What I want to achieve is
if $word is found in mysql_fetch_array($query_result) the add the row where it was found into the new array for processing.
Any thoughts? Thanks in advance.
Don't use mysql_* functions they are depracated. Use mysqli or pdo instead.
It's not wise to search in array of mysql results in php while it can be done in mysql. Let's say you have table and you want to find all numbers in number column that are greater than 5
SELECT FROM table_name WHERE number>5
to find text you can use simple clause
SELECT FROM table_name WHERE name = 'username'
You can also create more complex conditions.
From MYSQL manual:
WHERE clause, if given, indicates the condition or conditions that rows must satisfy to be selected. where_condition is an expression that evaluates to true for each row to be selected. The statement selects all rows if there is no WHERE clause
Check this link
If you want to limit the query to only once, fetch all the results into temporary array and do the search from it like below
<?php
$all_rows=array();
$match_rows=array();
$i=0;
$limit=100000;
while($row=mysql_fetch_array($query_result)){
$all_rows[]=$row;
if($i % $limit == 0){ // this part only functions every 100,000 cycles.
foreach($all_rows as $search_row){
if(array_search($word_to_check, $search_row)
$match_rows[]=$search_row;
}
$all_rows=array();//reset temporary array
}
$i++;
}
//This solution assumes the required word can be found in mulitple columns

PHP MySQL - SELECT SUM return issue

I am attempting to perform the following query:
SELECT SUM(cash) AS total_cash FROM users
The query should give me back a SUM() of the total cash which I've paid out to users in the form of a field named total_cash.
My HTML/PHP is as follows:
<p class="cash_count">
$<?
$total_cash = $db->GetNumRows($db->Query("SELECT SUM(cash) AS total_cash FROM users"));
echo number_format($total_cash);
?>
</p> paid out!
I know GetNumRows will always show 1 as there's only 1 row, but I don't know what to use instead, can anybody guide me?
You are using some class to connect to database - you have not specified anything about that class. If $db->Query() returns the actual mysql resource, you can do this:
$res=$db->Query("....");
$r=mysql_fetch_object($res);
echo $r->total_cash;
Yes, there's only 1 row, because your query ask for the SUM, and returns only 1 row with the sum.
You can do 2 things, or quit the SUM of the SQL or quit the $db->GetNumRows.

How to get the number of results MySql would have returned without limit?

I have a table with a lot of data, so I retrieve it and display it one page at a time (my request is lengthy so there is no way I run it on the entire table).
But I would like to paginate the results, so I need to know what is the total number of elements in my table.
If I perform a COUNT(*) in the same request, I get the number of selected elements (in my case, 10).
If I perform a COUNT(*) on my table in a second request, the result might be wrong because of the where, join and having clauses in my main query.
What is the cleanest way to:
Retrieve the data
Know the maximum number of elements in my table for this specific request
One solution seems to be using the Mysql function FOUND_ROWS :
I tried this, as mysql_query performs one query at a time: (taken here)
$query = 'SELECT SQL_CALC_FOUND_ROWS * FROM Users';
$result = mysql_query($query);
// fetching the results ...
$query = 'SELECT FOUND_ROWS()';
$ result = mysql_query($query);
// debug
while ($row = mysql_fetch_row($result)) {
print_r($row);
}
And I got an array with 0 results:
Array ( [0] => 0 )
Whereas my query does returns results.
What is wrong with my approach ? Do you have a better solution ?
Set mysql.trace_mode to Off if it is On.
ini_set('mysql.trace_mode','Off'); may also work depending on your host configuration if you cannot edit my.cnf
If that doesn't make the code you posted above work, then you will need to run the query again without LIMIT and count it that way.
The code above works fine. I wasn't opening the connection correctly.
Output is :
Array ( [0] => 10976 )
I am still interested for an other way to do it, especially something that is not mysql dependent.

Categories