Why isn't affected_rows working in this PHP Mysqli code? - php

I have a mysqli database object $DataBase and the following code works as intended:
$stmt = $DataBase->stmt_init();
$stmt->prepare("UPDATE `optshop_stock` SET quantity_b = ? WHERE product_id = ?;");
$stmt->bind_param('ii', $qty, $sku);
$stmt->execute();
$stmt->close();
But when I add:
echo $stmt->affected_rows;
between $stmt->execute() and $stmt->close() no value is echoed, not even a zero if nothing happened. Am I using this statement in a correct manner?
( I followed this http://php.net/manual/en/mysqli-stmt.affected-rows.php example)

The property can be retrieved at database level (reference here):
echo $DataBase->affected_rows;

I think you should try to add $stmt->store_result() after $stmt->execute(), otherwise you can't get right results when use $stmt->affected_rows

Related

mysqli_stmt_bind_result not returning a value

Alright so this bugs the crap out of me, and I can't seem to find anything in the PHP documentation, nor anywhere in the Google resultosphere, so maybe someone can help here.
I'm trying to make a simple request to a database to return a varchar(30).
Code:
$qryID = "select idPhotos from housesphotos where idHouse = ?";
//Prepare the query
$stmt = mysqli_prepare($link, $qryID);
$x = 106;
//Bind the login parameter to the statement
if(mysqli_stmt_bind_param($stmt, "i", $x)){
if(mysqli_stmt_execute($stmt)){
//Bind every column in the select
if(mysqli_stmt_bind_result($stmt, $photoID)){
// $photoID = mysqli_stmt_fetch($stmt);
echo $photoID;
}
}
}
if(empty($photoID)){
printf("EMPTY");
}
As you can guess the output was EMPTY. I have tried using this solution: Strange issue with mysqli_stmt_bind_result but it did not work.
To make sure that everthing was suppost to go correctly I have made the query in the mysql and it worked wonders:
select idPhotos from housesphotos where idHouse = 106
OUTPUT:
591219e92b2fe_591219e92b302
The housephotos is a varchar(30) field. I'm not sure if it's the field type that is messing with the return value. I'm not sure also if it's the connections that I made earlier on the code but I have tried unset($stmt) and other variables to solve the problem but it's not working.
Is this some kind of bug with mysqli_stmt_bind_result() or just a new person's mistake?
You're not actually fetching the results - you commented the mysqli_stmt_fetch() out. The fetch also returns a boolean, not the actual results. Uncomment that line, and remove the variable assignment to it.
$qryID = "select idPhotos from housesphotos where idHouse = ?";
//Prepare the query
$stmt = mysqli_prepare($link, $qryID);
$x = 106;
//Bind the login parameter to the statement
if(mysqli_stmt_bind_param($stmt, "i", $x)){
if(mysqli_stmt_execute($stmt)){
//Bind every column in the select
if(mysqli_stmt_bind_result($stmt, $photoID)){
mysqli_stmt_fetch($stmt); // Remove the comment and variable assignment
echo $photoID;
}
}
}
If you still don't get any results, it might be because the number of rows returned was zero (you can check that with $stmt->num_rows after executing), but since you said the query worked in phpMyAdmin, it's likely that there's some sort of error you're ignoring. To check for errors, add an else to your if conditions, and log $stmt->error inside.
http://php.net/manual/en/mysqli-stmt.fetch.php
It seems that PHP 5.4 (at least the way it's installed on Comcast servers) has a bug that causes bind-result to fail on a varchar field. Changing the field definition to "text" solves the problem.

php sqlite3 bindvalue crash

bindValue crash my script :
$statement = $db->prepare('SELECT * FROM player WHERE login=:login;');
echo "plop1";
$statement->bindValue(':login', $_POST["login"], SQLITE3_TEXT);
echo "plop2";
$result = $statement->execute();
echo "plop3";
plop1 is displayed but not plop2, I tryed to replace $_POST["login"] by a static value, but nothing changed, any idea ?
Thank you for helping me.
Just my bad, the table was not created because my query was wrong then $db->prepare return false. Now it works fine.

How to use mysqli bind_result

im trying to use mysqli with bind_result but all i get is null values. My $stmt
number of rows is greater than 0 so i do have some data in it.
I dont realy understand what value should come into bind_result
I have read at the manual http://php.net/manual/en/mysqli-stmt.bind-result.php
And they dont explain what should i put in the bind_result.
Should i put there the column names? if yes, as strings? how do i get my wanted values?
Here is my code thanks for helping:
$sql = "SELECT * FROM comments WHERE workout_name = ? AND user = ?";
$stmt = $mysqli->prepare($sql) or trigger_error($mysqli->error."[$sql]");
$stmt->bind_param('ss', $workout_name, $user);
$workout_name = "rytg";
$user = "tomer";
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($comment, $commented_user);
if($stmt->num_rows > 0)
{
$response["workouts"] = array();
while ($stmt->fetch())
{
// temp user array
$workouts = array();
$workouts["comment"] = $comment;
$workouts["user"] = $commented_user;
// push single product into final response array
array_push($response["workouts"], $workouts);
}
}
Your only problem is insufficient error reporting
error_reporting(E_ALL);
ini_set('display_errors',1);
Just add these lines at the top of your code and you will be immediately informed of the exact problem with your code.
Note that on the production server you have to turn displaying errors off and logging on
I don't have a working PHP installation next to me at the moment, so I can't verify it, but I believe you might have to bind both parameters and result before you execute the query, like so:
$workout_name = "rytg";
$user = "tomer";
$stmt = $mysqli->prepare($sql) or trigger_error($mysqli->error."[$sql]");
$stmt->bind_param('ss', $workout_name, $user);
$stmt->bind_result($comment, $commented_user);
$stmt->execute();
I'm not too sure about store_result() either. I don't recall having to use it while retrieving the results, so you might want to try running your code without it and see what happens.

Why is one query returning the right value, but the one right after it returns 0?

Here's my code:
$stmt1 = $db->prepare("SELECT wins FROM users WHERE id = ?");
$stmt2 = $db->prepare("SELECT losses FROM users WHERE id = ?");
$stmt1->bind_param("i", $_SESSION["id"]);
$stmt2->bind_param("i", $_SESSION["id"]);
$stmt1->bind_result($db_wins);
$stmt2->bind_result($db_losses);
$stmt1->execute();
$stmt2->execute();
$stmt1->fetch();
$stmt2->fetch();
// Print out user scores
echo "<p><strong>User:</strong> " . $_SESSION["username"] . "</p>\n";
echo "<p><strong>Wins:</strong> " . $db_wins . "</p>\n";
echo "<p><strong>Losses:</strong> " . $db_losses . "</p>\n";
Everything prints correctly except losses, which prints 0 when it should print the value in the table.
Points of note:
It prints the value as intended a little down the page, but without using preparation statements.
If I run it in phpMyAdmin (the query that returns 0) or Sequel Pro it returns the correct loss value.
I agree with the comment from Kolink above, but I think that changing your code to the following should also make the issue go away. The PHP pages offer the following alternative though, maybe that can also be used in your case? EDIT: Obviously you can still encorperate the bind_param into this.
/* prepare statement */
if ($stmt = $mysqli->prepare("SELECT Code, Name FROM Country ORDER BY Name LIMIT 5")) {
$stmt->execute();
/* bind variables to prepared statement */
$stmt->bind_result($col1, $col2);
/* fetch values */
while ($stmt->fetch()) {
printf("%s %s\n", $col1, $col2);
}
/* close statement */
$stmt->close();
}
You're using fetch() with no arguments, so by default it should be returning the data you want. If you pass in PDO::FETCH_BOUND that might trigger the bind operation as per the documentation.
Did you try to count ($db_losses) instead of just printing de variable ?
Sometimes the pointer in Mysql array isn't at the 1rst element and stay on the last element of the array that print 0 !
Try to use reset() function on your array. http://www.php.net/reset

mysqli_stmt to return a result object

When querying using mysqli_stmt::prepare() and execute(), it will not return the result set. But we need to access using the mysqli_stmt:fetch() on the stmt object. There is one function in the php manual called mysqli_stmt::get_result() that will return the result set into a variable we define, but when I use it, it gives me undefined method error. The manual say it is probably in SVC which I am not sure what.
The codes:
$conn = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD, DB_NAME);
$stmt = $conn->stmt_init();
$stmt->prepare("select * from users where u_id = ? ");
$stmt->bind_param('s', $param);
$stmt->execute();
Edit :
I know I can use bind_result() and fetch() function to retrieve the record like :
$stmt->bind_result($column1, $column2, $column3);
while ($stmt->fetch()) {
echo "Column 1: $column1\n";
echo "Column 2: $column2\n";
echo "Column 3: $column3\n";
}
But, my objective is to get the result set (the resource type object) after I execute, something like this:
$result = $stmt->execute();
so I can use the normal mysqli::fetch_object on the result set
$conn->fetch_object($result);
Is there any way to achieve this? thanks
Update:
The get_result function is exactly what I need, but it's not working on my PHP
Well, if you do not want to use mysqli_stmt::fetch() but mysqli_result::fetch_*(), I guess it will be a little cumbersome.
http://www.joekolba.com/node/2
Alternatively, use PDO.
I have done it in the following way:
$stmt->prepare("select * from users where u_id = ? ");
$stmt->bind_param('s', $param);
$stmt->execute();
$stmt->bind_result($columns['column_name1'], $columns['column_name2'], $columns['column_name3']);
while ($stmt->fetch()) {
$row = (object) $columns;
}
That comes quite near the FETCH_OBJECT method. You can access all the data of one row via $row->column_name1 etc. Of course you would have to update the associative columns-array, when you alter your table and change names. But it works quite well for me. Didn't want to switch to PDO - considering the fact I switched to MYSQLi just some days ago ;)
To enable the method mysqli_stmt::get_result(), you need to use the mysqlnd (MySQL Native Driver) extension: http://php.net/manual/en/book.mysqlnd.php
For some reason, this concrete method is not implemented with the more usual libmysqlclient. In my debian server (and also on my ubuntu desktop) this amounted to run:
sudo apt-get install php5-mysqlnd
You need to call bind_result to tell mysqli which variables should hold the columns. Then every time you call fetch, those variables will be automatically filled in, and you can access them like normal. See the code below (not sure if it works, ymmv).
$conn = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD, DB_NAME);
if($stmt = $conn->prepare('select * from users where u_id = ?'))
{
$stmt->bind_param("s", $param);
$stmt->execute();
$stmt->bind_result($column1, $column2, $column3);
while ($stmt->fetch()) {
echo "Column 1: $column1\n";
echo "Column 2: $column2\n";
echo "Column 3: $column3\n";
}
$stmt->close();
}

Categories