There are many conflicting statements around, what is the best way to row count using PDO in PHP? Before using PDO I just simply used mysql_num_rows.
fetchAll is something I won't want as I may sometimes be dealing with large datasets, so not good for my use.
Any suggestions?
In Mysql $stmt->rowCount(); doesnt work. Try this
$nRows = $pdo->query('select count(*) from yourTable')->fetchColumn();
echo 'Number of rows is = '. $nRows;
Here is an excerpt from a comment and answer regarding the same. Check it out its very resourceful.
mysql_num_rows() worked is because it was internally fetching all the rows to give you that information, even if it didn't seem like it to you. Refer to this anwere
So in PDO, your options are:
Use MySQL's FOUND_ROWS() function.
Use PDO's fetch_all() function to fetch all the rows into an array,
then use count() on it.
Do an extra query to SELECT COUNT(*),
https://stackoverflow.com/a/883523/2536812
Directly out form PHP Manual about PDO Statements
$stmt->rowCount();
The $stmtvalue is for exemple the return of a prepare :
$stmt = $pdo->prepare('MY PREPARED SQL QUERY');
Related
I have a conventional query that works just fine that looks like this:
$result = $mysqli->query("SELECT value FROM activities WHERE name = 'Drywall'");
This succeeds in returning a row. However, for the purposes of diagnosing the problem I'm having with a prepared statement, I tried an identical query as a prepared statement like so:
$stmt = $mysqli->prepare("SELECT value FROM activities WHERE name = 'Drywall'");
$stmt->execute();
Despite the fact these are identical query strings, $stmt->num_rows is always 0. Why would the conventional query work, but the prepared statement not when they are the same exact query? Also, I realize including 'Drywall' in the prepared query string runs counter to the purpose of prepared statements, but I was just trying to eliminate the possibility that bind_param() was the culprit. So I was using bind_param() to fill in placeholders and that wasn't working either, despite my double-checking at runtime that the variable I was binding contained the correct value.
I think you want to use
$stmt->store_result();
before the call
$stmt->num_rows();
see last line of the descripton in the manual for $stmt->num_rows() (http://www.php.net/manual/en/mysqli-stmt.num-rows.php).
Check for proper use of the mysqli->prepare. The function depends on a parameter to be passed. It is different from passing the values directly in the query but can use with another way.
Verify the manual:
http://www.php.net/manual/pt_BR/mysqli.prepare.php
Did you try something like this:
$stmt = $mysqli->prepare("SELECT value FROM activities WHERE name = 'Drywall'");
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
PS:
Prepared statements are Good. I would urge you to ALWAYS consider using them.
But in this case, a simple query would be much more efficient (would incur fewer round trips) than a prepared statement.
$id = $_GET['id'];
$result = mysql_query("select Count(id='$id') As Total from topics");
The above code is only working if we put count(id) but i want to get count of selected variable. How to insert id='$id' in count function it is not working please help related this.
You want a where clause in your sql query, which I believe would look like this:
select count(id) As Total from topics where id='$id'
note: depending on what type of column you have for your id field, you might need to drop the single quotes.
Warning
your code is vulnerable to sql injection you need to escape all get, post and request and the better approach will be using Prepared statement
Good Read
How to prevent SQL injection in PHP?
Are PDO prepared statements sufficient to prevent SQL injection?
Note
The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, is officially deprecated as of PHP v5.5.0 and will be removed in the future. So use either PDO or MySQLi
Good read
The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
PDO Tutorial for MySQL Developers
Pdo Tutorial For Beginners
Your question isn't very clear but perhaps you're looking for COUNT CASE WHEN id = $id THEN 1 ELSE 0 END (you can even skip the ELSE 0 part I believe).
What actually are you trying to do is pretty unclear in the Question.
But if you are trying to count the number of rows then simple select count(*) as Total where {your condition} from table will will do for you.
$id get values of $_GET['id']
if you want other data, use $id="your data here"
The following should work:
$id = $_GET['id'];
$result = mysql_query("SELECT COUNT(`" . $id . "`) AS `Total` FROM `Topics`");
But do note that this isn't very secure since it will be vulnerable to SQL Injection attacks.
Count can be used as below
<?php
$shoes=array("nike","puma","lancer");
echo count($shoes);
?>
Read the documentation in the PHP manual on Count.For inserting id in count:
$result = mysql_query('SELECT COUNT(id) FROM clients');
$count = mysql_result($result,0);
echo $count;
What is the preferred method for getting the number of rows that are returned for a SELECT state when using PDO with prepared statements?
I am currently using rowCount() but the docs say I shouldn't be using that since "most databases" don't support it (It is actually working just fine for me, so I'm tempted to keep using it. I can't find any sources that list exactly which databases do not support it, but apparently mine is fine).
Instead they recommend I use fetchColumn() but that requires writing a completely separate SQL statement that includes the COUNT(*) in my sql statement.
This is what they propose (http://php.net/manual/en/pdostatement.rowcount.php#example-1038):
//SQL TO GET ROWS TO OUTPUT
$sql = 'SELECT *
FROM properties
WHERE lister_id = :lister_id
AND lister_type = "landlord"';
$result = $dbh->prepare($sql);
$result->bindParam(':lister_id', $_SESSION['loggedin_lister_id'], PDO::PARAM_INT);
$result->execute();
//SQL TO GET NUMBER OF RETURNED ROWS
$row_num_sql = 'SELECT COUNT(*)
FROM properties
WHERE lister_id = :lister_id
AND lister_type = "landlord"';
$row_num_result = $dbh->prepare($row_num_sql);
$row_num_result->bindParam(':lister_id', $_SESSION['loggedin_lister_id'], PDO::PARAM_INT);
$row_num_result->execute();
$num_rows = $row_num_result->fetchColumn();
if($num_rows > 0) {
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo $row['name'];
}
}
I find this method that requires me to write a separate and nearly identical sql statement to be redundant and a serious pain when using prepared statements. I can understand how this approach might be acceptable when using a short SQL statement with a basic query, but not in the case of a prepared statement.
1. Is there any other way I can use the fetchColumn() approach
without having to rewrite what is almost exactly the same code?
2. Where can I find an official list of which databases
rowCount() supports when using a SELECT statement? And since it is
working on the database I am currently using, can I assume it is safe
to use(assuming I am not updating my database anytime soon)?
If you don't want to use rowCount I'm think you should two query, or you can use fetchAll and count(fetchAll) for rowCount
the second way, Use SELECT *,COUNT(*) ...
When I run this query `
SELECT id FROM bckoff WHERE left
= 3;
`
in phpmyAdmin, I get the correct response
MySQL returned an empty result set
(i.e. zero rows).
However, when I run the same query through my PHP code using mysql_query('the above query').. then I get "Resource ID#5" or "Resource ID#6" and so on..
How do I get the empty result set (or zero rows) in PHP ?
mysql_num_rows is the answer. This function returns the number of rows affected by a executed query.
$query = "SELECT id FROM bckoff WHERE left = 3";
$result = mysql_query($query);
echo mysql_num_rows($result);
When you execute mysql_query($query) it executes the query and puts it in a resource. This resource can be read by different mysql-functions (like mysql_num_rows). For a complete overview of all MySQL functions have a look at http://nl.php.net/manual/en/ref.mysql.php
Note: Extension used in above code is deprecated as of PHP 5.5.0, Use MySQLi or PDO_MySQL extension.
So instead of mysql_num_rows use mysqli_num_rows()
You can use mysql_num_rows function as:
$result = mysql_query("SELECT id FROM bckoff WHERE left = 3");
$num_rows = mysql_num_rows($result);
// $num_rows will be 0.
You need to use a mysql_fetch_* function to retrieve the results. Look here
Mysql Fetch Functions
There is a mysql_num_rows function that you can call on the $result returned by mysql_query("SELECT ...").
You might look into the MySQLi extension instead. It's a big improvement over the MySQL driver, and allows you to use prepared statements and bind parameters among other things, and I find it much more comfortable to use. You can look at the examples on the documentation page for num_rows.
In using PHP Prepared Statement, what is the syntax for counting number of rows?
$stmt = $conn->stmt_init();
$query = "SELECT * FROM TableName";
if($stmt->prepare($query)){
$stmt->num_row(); //SOMETHING SIMILAR TO THIS.... }
$stmt->num_rows
For mysqli its num_rows. Make sure you call store_result beforehand.
I am assuming your are using mysqli. If so, then affected_rows() should give you the number of rows will give you the number of rows returned by a SELECT operataion.
Also make sure to add
$stmt->store_result();
before
$stmt->num_rows;