Adding count(*) to existing mysql query causes unwanted action in php - php

$results_ts = mysqli_query($connection, "SELECT id, title, description, content
FROM prose WHERE title LIKE '%$search_title%' LIMIT 10");
if(isset ($_GET['search_title'])){
while($title_arr = mysqli_fetch_array($results_ts)){
echo $title_arr[id]; //and so on...
And that works as I wanted.
but when I try to add , count(*) after where content is, than while() loop echoes only one result, even when $title_arr[4](which stands for count) results in many.
Is it possible to do it this sort of way, or should I be running two separate queries?

You shouldn't do that in one query.
Think about the result you're expecting: when you do a count(*) query, what you get back is a result with only one row and one value. If you select multiple lines, then what should it do? Inject the count into each row of the data?
From a logical perspective, those are two different things you're looking for.
EDIT: counting the rows in your result after the fact is probably the best option, but that won't work if you're only looking for the first 10 entries, and there's no reason to SELECT the whole table if you don't need all the data. That's why count(*) is fulfilling such a different role.

COUNT() is an aggregate function so you can't use it like this. But if all you want is the number of rows this query would have returned you can use SQL_CALC_FOUND_ROWS to get the number of rows that would have been returned if thee was no LIMIT clause. You then can get the results by calling SELECT FOUND_ROWS() after your query is run.

Related

Counting rows in mysql select based on criteria

I'd like to have a SQL select statement (in PHP) that grabs all the data in my table. Then I'd like to be able to look for certain criteria and give me a count of rows that meet that criteria.
I already can do it by using mysql_num_rows and a separate select per criteria, but that seems inefficient. (i'd have dozens of select statements going) Is there a way to do it with just one select statement then use PHP to count the various things I want to count?
Edit:
I dont have any relevant code to post since the only code I do have is just an SQL select that does the filtering for me, and then uses mysql_num_rows to count them. This is what I am trying to avoid doing.
Example Select statement:
SELECT MDate, Type, MW, Region, Status FROM Scheduler WHERE Status = 'Complete';
In the above example I am looking for Status = Complete but I have several status' that I'd like get counts of individually without having to put a separate Select for each status.
You'll need to write some SQL along the lines of ...
SELECT COUNT(*) FROM Table WHERE `status` IN ("Complete", ...)
GROUP BY `status`
Without specifics of your database schema or the code you already have, that's the best answer you'll likely get.

Mysql query very slow (group by)

mysql query very slow but i use "group by" function...
i remove group by query and query very fast.
How can I solve this problem?
my query code:
$myquery1 = mysql_query("SELECT * FROM konucuklar
WHERE status=''
and category='football'
GROUP BY matchhour
ORDER BY id asc");
while($myquery1record = mysql_fetch_array($myquery1)){
$myquery2 = mysql_query("SELECT * FROM konucuklar
WHERE mactarihi='$bugunt'
and statu=''
and kategori='futbol'
and macsaati='$myquery1record[matchhour]'
ORDER BY id asc");
$toplams=#mysql_num_rows($myquery2);
while ($myquery2record=mysql_fetch_array($myquery2)) {
// code
}
}
}
Your first query does not comply with SQL standards and will be processed by mysql only if strict sql mode is not enabled.
You are issuing the 2nd query in a loop based on the results returned by the 1st query. So, if the 1st query returns 10 rows, then you will execute the 2nd query 10 times. This is very slow. You should rewrite the 2 queries as one, since both queries query the same table and have almost the same where criteria.
No idea what the 2nd while loop does, as I can't see where $listele is defined.
The slow down might not be related to the GROUP BY clause. Try adding an index on columns you need to .
Link to understand index : http://www.tutorialspoint.com/sql/sql-indexes.htm
MySQL Profiling might also help you in your endeavour
Your queries are not optimized and probably could be done better in other way incluiding using only one composed query (JOIN) to fetch all data at once.
Also if your tables have lots of items is good practice to create INDEXES to the fields uses in the common queries for the filter to make the search faster.
Example, your firs select has this complexity (and probably is not well formed)
SELECT * FROM konucuklar WHERE status=''
and category='football'
GROUP BY matchhour
ORDER BY id asc
But is used only to get the matchhour for the second query. The minimal optimization is to use a query to fetch only the required field.
SELECT DISTINCT matchhour FROM konucuklar WHERE status='' and category='football'

Parse multiple $variable values from single query?

I'm trying to learn a more economical way of parsing out multiple variable values from a single mysql_fetch_array query. I know I could write a whole series of individual queries to resolve this, but that's a lot of extra coding and queries to hit the server with and that just seems grossly inefficient.
The base query I'd like to work with is:
SELECT vehicletype, vehiclelength
FROM my_dbase.my_table
WHERE arriveday = '08/07/2013' AND process_status = 'completed'
vehicletype has one of four fixed values assigned, and vehiclelength has one of five fixed values assigned from option_value fields on a form page.
What I need is to parse the result of the query to count the number of records found for each pair-combination and assign a $variable value to each pair-combination to display in a PHP-generated table. I have four different dates that I need to run this operation for.
I've tried some iterations of creating an array() or using array_count_values() with the output of the mysql_fetch_array result with no success.
Perhaps you can try,
SELECT COUNT(*), vehicletype, vehiclelength
FROM my_dbase.my_table WHERE arriveday = '08/07/2013'
AND process_status = 'completed' and vehicletype
in ('t1','t2','t3','t4') and vehiclelength
IN('1','2','3','3') GROUP BY vehicletype, vehiclelength
ORDER BY vechicletype
I like to let mysql do all the work.

Why does mysql_num_rows return 1 for a SELECT on an empty table?

The code:
$review = mysql_query("SELECT conceptID, MIN(nextReview) FROM userconcepts WHERE userID='$userID'");
$nrows = mysql_num_rows($review);
echo "$nrows<br />\n";
The query works when the table has such entries and returns the correct column values. However, when the table is empty, as I can confirm right now in HeidiSQL, mysql_num_rows still returns 1, but the column values are empty. (The problem still remains if the table has other values for different userIDs).
I expect this query to return the empty set sometimes during normal operations, and I want to take action based on the existence of a result, but I also want to use the result if it exists. Any idea why this code is not working as I expect it to work (I expect it to return 0 if the table is empty)?
First of all, the query has a very simple problem: you're showing the conceptID field, but not grouping by it. If you want to show a field on a SELECT that uses aggregate functions, you should show it; not doing so is an error, and will make many engines not execute your query.
That aside, whenever you have an aggregate function, and you don't group by anything (i.e., don't add a GROUP BY clause), the result is one row. Regardless of the amount of rows in the table.
The reason why is because when a SQL engine executes a query with only aggregation functions, then it returns one row. So:
select count(*)
from table
where 1 = 2
is going to return 1 row with the value 0. This is the way that all SQL engines work.
Your query is a little different:
select conceptID, MIN(nextReview)
FROM userconcepts
WHERE userID='$userID'"
In most SQL dialects, you would get an error of the from "conceptID not in group by clause" or something like that. That is, the query would have a syntax error.
MySQL supports this. It will return the minimum value of nextReview (from the rows that meet the where condition) along with an arbitrary value of conceptID (from those same rows). In this case, there are no rows, so the values will be set to NULL.
Perhaps, you want one row per conceptId. That query would be:
select conceptID, MIN(nextReview)
FROM userconcepts
WHERE userID='$userID'
group by conceptId

Get size of max possible result set

For my application most of my SQL queries return a specified number of rows. I'd also like to get the maximum possible number of results i.e. how many rows would be returned if I wasn't setting a LIMIT.
Is there a more efficient way to do this (using just SQL?) than returning all the results, getting the size of the result set and then splicing the set to return just the first N rows.
You can use SELECT COUNT(*), but this isn't ideal for large data sets.
A more efficient solution is to use SQL_CALC_FOUND_ROWS and FOUND_ROWS():
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows
First query:
SELECT SQL_CALC_FOUND_ROWS id, name, etc FROM table LIMIT 10;
Second query:
SELECT FOUND_ROWS();
You'll still need two queries, but you run the main query once, saving resources.
I'd also like to get the maximum possible number of results i.e. how many rows would be returned if I wasn't setting a LIMIT.
Use:
SELECT COUNT(*)
FROM YOUR_TABLE
...to get the number of rows that currently exist in YOUR_TABLE.
Is there a more efficient way to do this (using just SQL?) than returning all the results, getting the size of the result set and then splicing the set to return just the first N rows.
Only fetch the rows/information you need.
Getting everything means a lot of data is going over the wire, that likely won't be used at all. In this situation, data is being cached - which means it can get stale because it isn't fresh from the database.
This sounds like pagination...
To get the specified number of rows you could use select count(*). Is that what you are looking for ?

Categories