ending prepared statement queries (stmt->close) - php

currently i'm using mysql (stmt) queries as:
connecting from the main php file, then for each query im doing these:
$stmt = $db->prepare
$stmt->execute();
$result = $stmt->get_result();
and nothing after with the stmt/mysql.
now i saw that i need to use these commands, and then:
$stmt->close()
$conn->close()
for the ending, but when exactly do i have to use them?
correct me if im wrong but, do i need to use the $stmt->close(); after every query, and the $conn->close() at the bottom of each page? or after any query aswell?
how exactly do i use them, and why tho? how its affecting my website/what will happen if i wont use them?

Related

PHP 2 Prepared Statements Error

I have 2 prepared statements in function. After I get result from first, I need one field's value from this result to be used in second statement as bind_param() function's parameter. But I was getting error, until I found out about store_result() function and used it after first statement. So can you tell or give some reference to read, why is there need to use store_result() function and why this problem arises, during using 2 prepared statements.
I don't know if I am right, but in my opinion this happens because I am not closing first statement before starting second and maybe because of both are open, some error arises.
EDIT:
I found out some information, that somehow helps me to solve this problem
Command out of sync:
This can happen, for example, if you are using mysql_use_result() and try to execute a new query before you have called mysql_free_result(). It can also happen if you try to execute two queries that return data without calling mysql_use_result() or mysql_store_result() in between.
store_result() it self for using Transfers a result set from the last query.
Example :
$stmt = $mysqli->prepare("SELECT col1,col2 FROM tabel WHERE col1= ?")
$stmt->bind_param('s', $test);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($col1,$col2);
$stmt->fetch();
You can read it in here how to use prepared-statement.
You can read this documentation how to use mysqli prepared-statement.

MySQLi prepared statement fails where identical regular query succeeds

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.

Using PDO, do I really need to run two separate prepared statements to get the number of rows returned?

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(*) ...

what restrictions are applied on the use of prepared statements?

i am using prepared statements in my project in php, on localhost it work fine but on server i t stops rendering page in the middle. i saw one error like this when i was executing nested queries on single statement and fixed that using 2 statements but this time i am executing 3 independent sql queries on single statement and still it stucks in last query...
all queries are independent i mean queries are not nested.
how should i fix it?
here is the last query
if($stmt->prepare("sql"))
{
$stmt->bind_param("s", $material);
$stmt->bind_result($mid, $subject, $title);
$stmt->execute();
if($stmt->fetch()){ // do something}
}
After a long time i faced the same problem once again and solved it simple by executing my prepared statement first and then binding the result like:
if($stmt->prepare("sql query goes here"))
{
$stmt->bind_param("s", $material);
$stmt->execute();
$stmt->bind_result($mid, $subject, $title);
if($stmt->fetch()){ // do something}
}
hope this will help someone else too.

Cannot figure out why SQL DELETE FROM statement returns an error of "SQLSTATE[HY000]: General error: 25 bind or column index out of range "

So, here's the relevant code from my page. It connects to a sqlite3 database through PDO which I update through forms on the page. I have other sqlite statements, like INSERTS and UPDATES (that does use WHERE id=:id) that work no problem. This DELETE one does not, however. I do have all the code in a try catch block on my page (which is how I got the error, if you were wondeing) but I figured I can omit it here.
Thanks for the help!
<?php
$db = new PDO("sqlite:osuat.sqlite3");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$id = $_POST['id'];
$update = "DELETE FROM pages
WHERE id=:id";
$stmt = $db->prepare($update);
$stmt->bindParam(':id', $id);
$stmt->execute();
?>
Try adding PDO::PARAM_INT to the bind_param method, to make sure that the value being sent is an INT (which I'm assuming your ID field is) i.e.,
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
Echo the actual sql statement and die prior to actually running it. Then inspect and run the statement directly. I suspect $_POST['id'] doesn't contain what you think it does.
I finally figured it out. In my actual page, I have a bunch of if-else constructs in order to construct the correct $update string. I (wrongly) figured that I could just use bindParam() at the end without paying heed to how many bindParam()s each update statement would need. So, for my DELETE FROM pages WHERE id=:id, it was being supplied a whole bunch of other parameters only used in other $update strings, not just :id.
Its my fault for not including the entire source, I'm sure someone here would have caught it right away, but many thanks to duellsy, he/she led me on the right path looking for ways to log the actual SQL statement. In the end, using stmt->debugDumpParams(); helped me figure what I was doing wrong.
Try writing the DELETE command in one line.

Categories