I'm a beginner who has problems with PHP :(
I have a PHP function which shows all the rows from the database table. Now I have to create paging to show only limited number of rows per one page.
I have a problem with retrieving a COUNT result from query. I want to create a condition where PHP & MySQL use LIMIT if number of rows is bigger than needed on one page. The following code:
$count = "SELECT COUNT(*) FROM articles";
$countq = $db->query($count);
$countrs = mysql_fetch_array($countq);
echo $countrs;
should display a number of rows. However, it does not. What am I doing wrong? I want to see a result to make sure that everything else will work fine. But I can't get it working.
Error: mysql_fetch_array() expects parameter 1 to be resource, object given
$db contains database connection information (server, user...) and is working
Use PDO for MySQL query.
$db = new PDO('mysql:host=#YOUR HOST#;dbname=#YOUR DB#;charset=utf8', '#YOUR LOGIN#', '#YOUR PASSWORD#');
$query = $db->query('SELECT COUNT(*) AS count FROM articles');
$countq = $query->fetch();
$query->closeCursor();
echo $countq['count'];
I hope this will help you
You will have to set the limit in the query like
$count = "SELECT COUNT(*) FROM articles LIMIT 5,10";
where 5 is the starting point and 10 is the total number of results you want.
You mention: $db but not what $db is? i mean is it a database object class? this will work directly if you are using the a database class, and if that's the case the class will also have functions which will allow you to query data without using mysql_fetch_array (actually mysqli_fetch_array).
Related
I have quite an issue I can not seem to solve. I am trying to get a row count from a select statement.
I should start by saying I have tried most all methods resulting from google searches on this issue.
I am using the result set so I would prefer not to make a second query.
The query uses a prepared select statement which seems to be a main issue if I understand it correctly.
I decided to try a simple approach using PHP's native count() function. Which lead me here because I finally reached the end of the rope on this.
On to the details...within a class of mine, I make the query like this.
// Create database connection
$database = DatabaseFactory::getFactory()->getConnection();
// Set and execute database query
$sql = "SELECT * FROM `service_orders` WHERE `agency_id` = :agency_id $filter ORDER BY $sort $order $per_page";
$query = $database->prepare($sql);
$query->execute($query_array);
// If results
if ($query->rowCount() > 0) {
$results = $query->fetchAll();
self::$order_count = "Count: " . count($results);
return $results;
}
// Default, return false
return false;
Findings
If I perform count($results) like I did above, I get the total rows in the database (Let's say 50).
If I print_r($results), it shows the array with the proper number of entries (Let's say 10) that of course differs from the total rows in the database.
How can these two differ? It's as if the count($results) is misreading the result array.
More Findings
Within my actual php page, I call the class to retrieve the data like this.
$results = OrderModel::getServiceOrders();
echo count($results);
Strangely enough, if I then perform count($results) it gives me the correct reading of the result array (which in my example here would be 10).
I am perplexed by this as the count function is being performed on the exact same array. The only difference is one is called on the array within the class, and the other is called on the array returned from the class.
Does anyone have any ideas on how to solve this or why there is the discrepancy when using count() in this instance?
Thank you all in advance!
James
Additional Info
This is another mind numbing scenario. If I return the count along with the actual results, I can access it on the page with the correct value (10 rows). Yet, if I set it into a session variable, and access it that way, the count is the whole data set (50 rows). How is it even possible these two values are not the same?!
$results = $query->fetchAll();
Session::set("order_count", $total[0]); // Yields 50 (incorrect)
return [
"results"=> $results,
"count"=> $total[0], // Yields 10 (correct)
];
I'm trying to display how many id's does my procedure finds, but the variable $processz only got the first row of the sql result. It should display that there are 17 rows or id's, and only got 1. Why does it happends?
$conexion = con_abrir();
$sqlquery = "OEE.dbo.VerPlanillas_fechas '$Linea_ID','$fecha1','$fecha2'";
$processz = odbc_exec($conexion,$sqlquery);
con_cerrar($conexion);
$res = count($processz);
echo $res;
count ($processz) tells you how many results you have - one.
If you want to know how many rows are in the result, you need to call odbc_num_rows ($processz);
Look into using PDO rather than odbc specific functions.
I have this function in a linked file:
function getNumberOfHerps() {
$sql = "SELECT COUNT(ID)
FROM HERPES;";
return DBIface::connect()->query($sql);
}
I can call on this function from any other page in the website. What I want to do is to be able to use the result of the COUNT function in my php code on various pages, because I need to know how many herps there are in the database on several occasions in the code.
I tried this:
$result = getNumberOfHerps();
$numberOfHerps = $result['COUNT'];
But it caused a parse error on the second line, saying this:
Cannot use object of type PDOStatement as array.
Please tell me how I can use the result of a Count function in php code. Thanks :D
You are actually facing 2 separate items here that need your attention:
You can't access the COUNT(ID) returned from your query and
You are attempting to access data of a PDOStatement object as an array
So:
You can create an ALIAS for the value returned from the COUNT() function:
$sql = "SELECT COUNT(ID) as COUNT...";
This will provide to your result set a new column named COUNT that you can access your row count from.
Secondly, you need to perform a fetch operation on the PDOStatement in order to access it's data (this is what is causing your parse error). You have several options for accessing the result set in a PDOStatement:
list ($idCount) = $result->fetch();
// $idCount will now have the value of your COUNT column
or
$results = $result->fetch(PDO::FETCH_ASSOC);
// you can then access your COUNT as $results['COUNT'];
or even
$results = $result->fetch(PDO::FETCH_OBJ);
// you can then access your count as $results->COUNT
There are actually several additional FETCH_* styles available to use. The ones I've described though would likely be the most common. You can find more information about fetching PDO result sets at
http://us1.php.net/manual/en/pdostatement.fetch.php
I worked it out for myself, so I'll put my answer up for anyone else who finds this question:
I changed the function to this:
function getNumberOfHerps() {
$sql = "SELECT COUNT(1)
FROM HERPES";
return DBIface::connect()->query($sql)->fetchColumn(0);
}
So what the function now returns is the actual count value (the first column of the query). That means that in the webpage php file, you can access it in this way:
$numberOfHerps = getNumberOfHerps();
Much more simple.
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.
I want to count all the rows and at the same time list them as I usually do, using mysql_fetch_object. I thought I'd do something like this;
$total = mysql_query("SELECT *, COUNT(*) AS totalfound FROM img WHERE state='0'");
But I can't seem to wrap my head around how to get the values out - I just get the first item in the table when I run this;
while ($record = mysql_fetch_object($total)) { echo $record->id; }
If I want to get the totalfound I could do this;
$result = mysql_fetch_assoc($total);
$count = $result['totalfound'];
...but then I can't get the rest. I know I'm thinking wrong but can't seem to get it to work. Can you guys please help me out? Thanks!
Once thing I forgot to mention: mysql_num_rows is too slow, I was thinking of using count(*) instead. As an example, mysql_num_rows on the entire table takes everything from 3 to 9 seconds, and a count(*) always takes 0.6 seconds, getting the same results.
A count is an aggregate function, you cannot select both rows and aggregates without using group by. MySQL will let you do it without the group by, and will produce unpredictable results.
Just use the query without count to get the rows, and use mysql_num_rows() on the result.
Edit: If mysql_num_rows() is slow, you must be returning a lot of rows. You'd then better execute two queries, one simply select count(*) as numrows ..., and one to retreive your data.
Try to add proper indexes and the count(*) will execute within a few miliseconds.
You really don't want this in one query. Every row will then have a column that states how many rows there are, which is unrelated to that row.
Why not just list them normally and get the count by the inbuilt function?
$result = mysql_query("SELECT * FROM img WHERE state='0'");
$count = mysql_num_rows($result);
while ($row = mysql_fetch_array($result))
{
//do your thing here
}
Editing in response to your edit
In normal circumstances, where you only want the Count, a Count() would be far faster than mysql_num_rows() because Count() would only return the count. In your case, since you want the records anyway, mysql_num_rows() should be faster.
If I understand what you need, I think you could use:
$result = mysql_query("SELECT * FROM img WHERE state='0'");
$num_rows = mysql_num_rows($result);
With $result you can get all rows the way you're used to, while $num_rows has the number of returned rows from database.
Aside from the Marco's right answer,
why can't you make it the same way, echo $record->totalfound;?
As for the "mysql_num_rows being slow" - it is no more a delusion.
You have just heard something but didn't get the point.
mysql_num_rows itself isn't being slow by any means.
it is gathering data rows being slow, not getting them count.
mysql_num_rows indeed is slower than count(*) if you need only that number, not all the data
but if you are getting your data anyway, mysql_num_rows is exactly what you need
Use KISS theory and do the below
while ($record = mysql_fetch_object($total)) {$totalData[] = $record; }
count($totalData) // returns total number of rows
Count
My dear haven't you listen about mysql_num_rows
$total = mysql_query("SELECT * FROM img WHERE state='0'");
$total_found=mysql_num_rows($total);