This question already has answers here:
Row count with PDO
(21 answers)
Closed 2 years ago.
Having issues returning number of results in PHP SQLSRV PDO connection, when I try $stmt->rowCount(); get -1 result, really don't get it.
...
...
...
if(empty($region)){
$query2 = "SELECT [QuotID], [QuotNumber], CreationDate, QuotDate
FROM [dbo].[vQuotaion]
GROUP BY [QuotID]
,[QuotNumber]
,[CreationDate]
,[QuotDate]
HAVING CreationDate >='".$fdate."' AND CreationDate <='".$edate."' AND ProType = 'OPSFi' ORDER BY CreationDate DESC";
$stmt2 = $conn->query( $query2 );
} else {
...
...
...
}
...
...
...
<?php
if(empty($stmt2)){
echo '';
}else{
while ($result = $stmt2->fetch(PDO::FETCH_ASSOC)){
bla bla bla;
}
}
?>
If you want to count the rows without a separate query you can do this with PDO:
$rows = $stmt2->fetchAll();
$num_rows = count($rows);
There is no way to directly count rows when using a SELECT statement with PDO for all database drivers. You could create a function using the code above if you need to retrieve counts regularly.
Warning!
Little Bobby says your script is at risk for SQL Injection Attacks.. Even escaping the string is not safe! Learn about prepared statements for PDO.
You can get the row count of a select query with the PDO versions of the sqlsrv drivers however, like the standard version of the drivers (non-PDO), you have to specify a scrollable cursor. Like so:
$query = "SELECT * FROM myTable";
$stmt = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
$rows = $stmt->rowCount();
The default cursor used is PDO::CURSOR_FWDONLY which, when rowCount() is used, returns -1.
Microsoft documentation.
Related
This question already has answers here:
php pdo get only one value from mysql; value that equals to variable
(3 answers)
Closed 2 years ago.
I am trying to convert my mysqli to PDO using PostgreSQL and I am wondering what is the equivalent way of writing the following code in PDO
$result = $mysqli->prepare("SELECT FOUND_ROWS()");
$result->execute();
$result->bind_result($total_rows);
$result->fetch();
What I tried is the following:
$stmt = $this->pdo->prepare('SELECT FOUND_ROWS()');
$stmt->execute();
but I am not sure how to convert the rest of the my_sqli logic to my new PostgreSQL PDO, in particular the $result->bind_result($total_rows); and fetch().
PDO doesn't have anything equivalent to bind_result(). PDOStatement::fetch() returns the row as an array or object, and you extract the result columns from that. So instead of
$result->bind_result($total_rows);
$result->fetch();
echo $total_rows;
you use
$row = $stmt->fetch(PDO::FETCH_NUM);
echo $row[0];
It's generally easier if you assign aliases to the columns being selected, then you can fetch an associative array.
$stmt = $this->pdo->prepare('SELECT FOUND_ROWS() AS total_rows');
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo $row['total_rows'];
I just started learning PHP today and am trying to write a few queries using prepared statements. so far I have this:
$query = "select * from users where 1 = ?";
$result = sqlsrv_query($connection,$query,array(1));
if($result === false){
echo "error";
}
while($row = sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC)){
print_r($row);
}
It produces the desired result (simply printing everything returned).
I am struggling on making it a prepared query, to avoid SQL injection
This already is a prepared query, where the third argument of sqlsrv_query is the array of variables you want to bind.
I'm having some trouble using a variable declared in PHP with an SQL query. I have used the resources at How to include a PHP variable inside a MySQL insert statement but have had no luck with them. I realize this is prone to SQL injection and if someone wants to show me how to protect against that, I will gladly implement that. (I think by using mysql_real_escape_string but that may be deprecated?)
<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'hospital_name' AND value = '$q'";
$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo $row['value'];
}
?>
I have tried switching '$q' with $q and that doesn't work. If I substitute the hospital name directly into the query, the SQL query and PHP output code works so I know that's not the problem unless for some reason it uses different logic with a variable when connecting to the database and executing the query.
Thank you in advance.
Edit: I'll go ahead and post more of my actual code instead of just the problem areas since unfortunately none of the answers provided have worked. I am trying to print out a "Case ID" that is the primary key tied to a patient. I am using a REDCap clinical database and their table structure is a little different than normal relational databases. My code is as follows:
<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'case_id' AND record in (SELECT distinct record FROM database.table WHERE field_name = 'hospital_name' AND value = '$q')";
$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo $row['value'];
}
?>
I have tried substituting $q with '$q' and '".$q."' and none of those print out the case_id that I need. I also tried using the mysqli_stmt_* functions but they printed nothing but blank as well. Our server uses PHP version 5.3.3 if that is helpful.
Thanks again.
Do it like so
<?php
$q = 'mercy_west';
$query = "SELECT col1,col2,col3,col4 FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
if($stmt = $db->query($query)){
$stmt->bind_param("s",$q); // s is for string, i for integer, number of these must match your ? marks in query. Then variable you're binding is the $q, Must match number of ? as well
$stmt->execute();
$stmt->bind_result($col1,$col2,$col3,$col4); // Can initialize these above with $col1 = "", but these bind what you're selecting. If you select 5 times, must have 5 variables, and they go in in order. select id,name, bind_result($id,name)
$stmt->store_result();
while($stmt->fetch()){ // fetch the results
echo $col1;
}
$stmt->close();
}
?>
Yes mysql_real_escape_string() is deprecated.
One solution, as hinted by answers like this one in that post you included a link to, is to use prepared statements. MySQLi and PDO both support binding parameters with prepared statements.
To continue using the mysqli_* functions, use:
mysqli_prepare() to get a prepared statement
mysqli_stmt_bind_param() to bind the parameter (e.g. for the WHERE condition value='$q')
mysqli_stmt_execute() to execute the statement
mysqli_stmt_bind_result() to send the output to a variable.
<?php
$q = 'Hospital_Name';
$query = "SELECT value FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
$statement = mysqli_prepare($conn, $query);
//Bind parameter for $q; substituted for first ? in $query
//first parameter: 's' -> string
mysqli_stmt_bind_param($statement, 's', $q);
//execute the statement
mysqli_stmt_execute($statement);
//bind an output variable
mysqli_stmt_bind_result($stmt, $value);
while ( mysqli_stmt_fetch($stmt)) {
echo $value; //print the value from each returned row
}
If you consider using PDO, look at bindparam(). You will need to determine the parameters for the PDO constructor but then can use it to get prepared statements with the prepare() method.
I have an existing MySQLi query:
$conn = dbConnect('query');
$galNumb = "SELECT COUNT(pj_gallery_id) FROM pj_galleries WHERE project = {$project}";
$gNumb = $conn->query($galNumb);
$row = $gNumb->fetch_row();
$galTotal = $row[0];
This counts the number of galleries per project that match the value in the query string contained in $project.
It works perfect but is not secure compared to a prepared statement. I have been researching this for two days and can not learn how to write this statement as a prepared statement. Any and all help will be insanely appreciated.
UPDATE:
I am flying by the seat of my pants here. I simply need to be shown how to code the above as a prepared statement. This sort of thing isn't resonating with my brain like learning PHP did and I'm just not getting any of this. The PHP manual is confusing and seems to be written for people who already understand PHP.
In short, I need a prepared statement version of the above code so that I can echo the result on the page. Currently, with what is in my DB, the number should be 3, and it consistently returns 1.
I wish I knew more so that I could better phrase my questions, but alas, I'm still learning. My apologies.
UPDATE 2:
Based on suggestions and research, I have this query written, but it ALWAYS returns the value 1, regardless of what's actually in the database:
$galNumb = "SELECT COUNT(pj_gallery_id) FROM pj_galleries WHERE project_part = ?";
$stmt = $conn->prepare($galNumb);
$stmt->bind_param('i', $project);
$gNumb = $stmt->execute();
Again, All I want to do is COUNT how many galleries are in each project. I know this should be simple but it isn't for me. There is currently 1 project in the DB with 3 galleries. The query should return 3.
This is as simple as it gets. This will prepare a sql statement, execute it and fetch the first row.
<?php
// create the prepared statement
$stmt = $conn->prepare('SELECT COUNT(pj_gallery_id) FROM pj_galleries WHERE project = ?');
// bind a variable to the statment
// the character denotes the type of the variable
// 's' for string
// 'i' for integer
$stmt->bind_param('i', $project);
// execute the query
$stmt->execute();
// get the result variable
$result = $stmt->get_result();
// fetch the row
$row = $result->fetch_row();
if ($row) {
echo "The count is " . $row[0];
}
?>
The documentation is pretty straightforward. You have a code example at the bottom.
http://php.net/manual/en/mysqli.prepare.php
$stmt = $dbConnection->prepare('SELECT COUNT(pj_gallery_id) FROM pj_galleries WHERE project = ?');
$stmt->bind_param('s', $project);
$stmt->execute();
This question already has answers here:
How to apply bindValue method in LIMIT clause?
(11 answers)
Closed 7 years ago.
In my PDO implementation, I am attempting to use an inserted value in the limit clause of the SQL statement:
$sql = "SELECT * FROM table ORDER BY datetime DESC LIMIT :limit";
$params = array(":limit" => 5);
$query = $dbh->prepare($sql);
$query->execute($params);
$result = $query->fetchall(PDO::FETCH_ASSOC);
$params and $query are correctly returned, but $result is empty.
Upon running print_r($query->errorInfo);, I get the following:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''5'' at line 1
How can I use PDO's insert values in this query? Am I doing it right?
See PHP PDO bindValue in LIMIT
Basically, you need to cast the limit value to int using intval() when binding.
You cannot bind variables into LIMIT clause’s operand (exactly, it probably depends on your database system vendor). Instead, use just string interpolation. :-(
$limit = 5;
$sql = "SELECT * FROM table ORDER BY datetime DESC LIMIT $limit";
$stmt = $dbh->query($sql);
$result = $stmt->fetchall(PDO::FETCH_ASSOC);