I am using a script that has a different way of doing a mySQL query to what I am used to. It starts with:
$query = $db->query("SELECT * etc ..... ");
then
while ($result = $db->fetchArray($query)) {
with variables shown as $result['a'], $result['b']. etc.
All I want to do is count the rows that are selected by the query, but mysql_num_rows doesn't work on $result.
What can I use instead?
You can use the count function to count the rows
$query = $db->query("SELECT count(*) as count from (SELECT * etc ..... ) as sq ");
$result = $db->fetchArray($query);
echo $result['count'];
You can change the query to:
SELECT count(*) as cnt etc .....
Then read the results back from the query.
Related
I have a PDO snippet that retrieves a bunch of rows from a MySQL table and assigns the field values (2 fields are returned per row) to two arrays like so:
$connect = dbconn(PROJHOST,'dbcontext', PROJDBUSER, PROJDBPWD);
$sql= "SELECT contextleft, contextright FROM tblcontext WHERE contextleft REGEXP :word LIMIT 0, 25";
$xleft = array();
$xright = array();
$countrows = 0;
$word = "[[:<:]]".$term."[[:>:]]";
$query = $connect->prepare($sql);
$query->bindParam(":word", $word, PDO::PARAM_STR);
if($query->execute()) {
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
$pattern = '/\b'. $term .'\b/ui';
$replacer = function($matches) { return '<span class="highlight">' . $matches[0] . '</span>'; };
$xleft[$countrows] = preg_replace_callback($pattern, $replacer, $row['contextleft']);
$xright[$countrows] = $row['contextright'];
$countrows++;
}
$notfound = null;
}
$connect = null;
This works perfect. As you can see, I use the LIMIT clause to ensure only a maximum of 25 rows are extracted. However, there can actually be many more matching records in the table and I need to also retrieve the total count of all matching records along with the returned rows. The end goal is pagination, something like: 25 of 100 entries returned...
I understand I have 2 options here, both involving 2 queries instead of a single one:
$sql= "SELECT COUNT(*) FROM tblcontext WHERE contextleft REGEXP :word;
SELECT contextleft, contextright FROM tblcontext WHERE contextleft REGEXP :word LIMIT 0, 25";
or...
$sql= "SELECT SQL_CALC_FOUND_ROWS contextleft, contextright FROM tblcontext WHERE contextleft REGEXP :word LIMIT 0, 25;
SELECT FOUND_ROWS();";
But I am still confused around retrieving the returned count value in PHP. Like I could access the fields by running the fetchAll() method on the query and referencing the field name. How can I access the count value returned by either FOUND_ROWS() or COUNT()? Also, is there any way to use a single SQL statement to get both count as well as the rows?
If you have a separate query with the count, then you can retrieve its value exactly the same way as you read the values from any queries, there is no difference.
If you use SQL_CALC_FOUND_ROWS, then you need to have a separate query to call FOUND_ROWS() function:
SELECT FOUND_ROWS();
Since this is again a normal query, you can read its output the same way as you do now.
You can technically retrieve the record count within the query itself by adding a count(*) field to the query:
SELECT contextleft, contextright, (select count(*) from tblcontext) as totalrecords FROM tblcontext WHERE contextleft REGEXP :word LIMIT 0, 25
or
SELECT contextleft, contextright, totalrecords
FROM tblcontext WHERE contextleft, (select count(*) as totalrecords from tblcontext) t REGEXP :word LIMIT 0, 25
Limit affects the number of records returned, but does not affect the number of rows counted by the count() function. The only drawback is that the count value will be there in every row, but in case of 25 rows, that may be an acceptable burden.
You need to test which method works the best for you.
I have a row in my mySQL database called "status". In that row i got three different values, either "S", "R" or "L".
Whats the easiest way to count and output the number of occurrences of each value with php?
Thanks!
You can get the counts as separate rows with:
SELECT status, COUNT(*) as count
FROM yourTable
GROUP BY status
You can get them in a single row with:
SELECT SUM(status = 'S') AS s, SUM(status = 'L') AS l, SUM(status = 'R') as r
FROM yourTable
After this, you can read a single row of results:
$row = $pdo->fetch(PDO::FETCH_ASSOC);
$s_count = $row['s'];
$l_count = $row['l'];
$r_count = $row['r'];
It's hard to tell without a full look at your database, but the basic structure is this (assuming you have another row called id)
Edit: to demonstrate in php
$dbc = new mysqli($host, $username, $password, $dbname);
$query = $dbc->query("select id, count(status) as status_count
where status = 'S'
group by id");
$query->fetch_assoc();
$row = $query->fetch_assoc();
echo $row['status_count'];
OR if you have more than one row do it like this:
while ($row = $query->fetch_assoc()) {
echo $row['status_count'];
}
The better way its to use a mysql query using COUNT
You can count all the raws
SELECT COUNT(*) FROM DATABASE
or one raw
SELECT COUNT(colum_name) FROM DATABASE
To be more easy you can give it a variable name like this:
SELECT COUNT (Colum_name) as name FROM DATABASE
So an example,after you connect to your database
Use this:
$ query = mysql_query ('SELECT COUNT (R) as R FROM status');
$ result = mysql_fetch_array ($ query);
Echo $ result ['R']
Hope this will help you !
I want to fetch the total count of records in MySQL db table and also use the limit with this. For example, there are 100 rows and the limit I want to use let suppose is 10. I know how to do this using two queries but I want to do this in one go.
SELECT count(*) as total_rows FROM mytable; // gets the total count of rows
SELECT col1,col2 FROM mytable LIMIT 0, 10; // gets the 10 rows of col1,col2
I want to do this in one go. Any idea.
Thanks.
Here is the SQL Fiddle that demonstrates how the below works:
SELECT m.*,
(
SELECT COUNT(*)
FROM mytable AS sm
) AS TotalCount
FROM (
SELECT mt.col1, mt.col2
FROM mytable AS mt
LIMIT 0, 10
) AS m
Have a look at Shayan Husaini's answer on How to get the total row count with MySQLi
I have updated his original answer after trying it out myself. You have to add "SQL_CALC_FOUND_ROWS" after SELECT in your query and add a second query as shown in the code snippet below.
$sql1 = "SELECT SQL_CALC_FOUND_ROWS col1,col2 FROM mytable LIMIT 0, 10";
$sql2 = "SELECT FOUND_ROWS()";
$result1 = $conn->query($sql1);
$result2 = $conn->query($sql2);
$TotalRcount = $result2->fetch_row();
// I have added this next line to correct the answer
$TotalNumRows = $TotalRcount[0];
You can use $result1 to access your results as you normally would.
How would I add up all the integers in the column, _view_count_, on my table, 'videos', then echo it to display on my page?
For example:
if row id 1 has view_count == 328
and
if row id 2 has view_count == 271
How would I make MySQL add those together and echo it out?
You can use MySQL's SUM() and your SQL query would look something similar to:
SELECT SUM(view_count) FROM videos;
To query and echo the value, if you're using mysqli methods in your PHP code, you can use:
$result = $mysqli->query('SELECT SUM(view_count) AS sum FROM videos;');
$row = $result->fetch_assoc($result);
echo $row['sum'];
Assuming you have a $mysqli object defined your code should look like:
$query = "SELECT Sum(view_count) as mySum FROM videos";
$result = $mysqli->query($query);
$row = $result->fetch_assoc($result);
echo $row['mySum'];
SELECT SUM(view_count) FROM videos
Assuming you have a COLUMN id, you can use SUM together with IN, like so:
SELECT SUM(view_count) FROM videos WHERE id in (1,2)
Suppose i have 1kk records in my database.
Now i need to select some data, and also i need to know how many fields did i select, so my question is:
Is it better to run one query to count data like this:
SELECT COUNT("id") from table where something = 'something'
And after that run one more querio for selection like this:
SELECT 'some_field' from table where something = 'something';
Or Maybe it's better to just select data and then just count it with php like:
count($rows);
Or maybe there is even better ways to do it, for example do it all in one query?
Reading between the lines, I think what your are probably after is SQL_CALC_FOUND_ROWS. This allows you to select part of a result set (using a LIMIT clause), and still calculate the total number of matching rows in a single operation. You still use two queries, but the actual search operation in the data only happens once:
// First get the results you want...
$result = mysql_query("
SELECT SQL_CALC_FOUND_ROWS
FROM `table`
WHERE `something` = 'something'
LIMIT 0, 10
");
// ...now get the total number of results
$numRows = mysql_query("
SELECT FOUND_ROWS()
");
$numRows = mysql_fetch_row($numRows);
$numRows = $numRows[0];
If you fetch all that 1000 records then you can count while you are fetching:
$res=mysql_query("SELECT 'some_field' from table where something = 'something'");
while($r = mysql_fetch_*($res)) {
$count++;
//> Do stuff
}
This way you make only one query and you don't use mysql_num_rows();
One query would be:
SELECT Count(*) AS NumRows, some_field from table
GROUP BY some_field where something = 'something';