MySQLi Commands out of sync, with simple query() function - php

I can't figure out why I'm getting the Commands out of sync; you can't run this command now error. I can't seem to find a way to fix this.
As you can probably see from the code, I need to execute TWO SQL statements. One to check if the password is correct, and the other, which runs only if the previous one returns true, to store all user data in session variables.
Here is my code:
$check_pw_query = $conn->query("CALL checkPassword('{$username}', '{$password}')");
$check_pw_fetched = $check_pw_query->fetch_assoc();
$check_pw_query->close();
if($check_pw_fetched['password_correct']) {
unset($check_pw_fetched);
if(!$get_user_data = $conn->query("CALL getUserData('{$username}')")/*->fetch_assoc()*/) {
echo $conn->error;
}
$_SESSION["user_username"] = $username;
$_SESSION["user_id"] = $get_user_data["id"];
$_SESSION["user_name"] = $get_user_data["name"];
$_SESSION["user_email"] = $get_user_data["email"];
$_SESSION["user_type"] = $get_user_data["type"];
$conn->close();
unset($conn);
send_home(false);
}
Help is much appreciated.
Thank you

Ok, as there were no real helpfully answers, I'll answer it myself, to hopefully help someone else with the same problem.
The problem is that, whenever you call a stored procedure, it will output one more result that defined anywhere. So if your procedure returns 1 value, php will get 2. The last one is only there to tell you that there are no more values. BUT you have to deal with that one as well to free the connection ($conn in my example).
So, that you do is, simply, add this to your code, right after the $check_pw_query->close(); :
$conn->next_result();
And there you have it. It will now work perfectly fine.

Related

MySQL Returns different number of rows on localhost vs live server for the same code

I have a simple form that needs a list of stops in the textarea and returns an id for each on the right hand side. This is my screenshot on localhost...I have the same table names, column names, number of records on both localhost and live server.
Here's the screenshot of the same page with same query on live server...
Here's the code I am using on both pages
$conn = new PDO("mysql:host=$host;dbname=$db;charset=$charset", $user, $pass);
if(isset($_POST["busnumber"], $_POST["busroute"])){
$stops = explode(PHP_EOL, $_POST["busroute"]);
$sql = 'SELECT * FROM stops WHERE stop_name LIKE :stop';
$statement = $conn->prepare($sql);
$statement->setFetchMode(PDO::FETCH_ASSOC);
foreach($stops as $stop){
$statement->bindValue(':stop', $stop);
$statement->execute();
$results = $statement->fetchAll();
foreach($results as $result){
echo $result['stop_id'].' '.$result['stop_name']."</br>";
}
}
}
As you can see, it returns the ID of the last row only on the live server. Can someone please tell me how this is possible and what I am missing?
EDIT 1
Notice what happens when I reverse the data entered in the text area
The localhost shows both the ids now
Guess what the server shows after reversing? Only the LAST ROW!
You don't need setFetchMode(). In the time I've used PDO I always had the best results with just using bindParam() and fetch() with the most default setup of PDO, which means just setting the errormode to exception and charset to utf8 like this:
try
{
$con = new PDO("mysql:host=".$host.";dbname=".$db_name, $user, $password);
}
catch(PDOException $e){
die("ERROR ". $e->getMessage());
}
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->exec("SET NAMES utf8");
Fetching any results like this
while($r = $statement->fetch())
{
echo $r['id'];
}
Any time when someone has used a different set up, I've noticed they've faced problems.
Try this, perhaps.
This is very simple. Please check your live db via phpmyadmin if you have access and from phpmyadmin run your queries like you are running it from php code. May be you have some restrictions of mysql or php on live. And also check your db versions on localhost and live with php versions too. Let me know the results of phpmyadmin queries thanks!
Just guessing the problem. I don't really think if this answer is correct. So please pardon me in advance.
PDOStatement::fetchAll() returns an array that consists of all the rows returned by the query. From this fact we can make two conclusions:
This function should not be used, if many rows has been selected. In
such a case conventional while loop ave to be used, fetching rows
one by one instead of getting them all into array at once. "Many"
means more than it is suitable to be shown on the average web page.
This function is mostly useful in a modern web application that
never outputs data right away during fetching, but rather passes it
to template.
Source: PDO Tutorial
I FIXED the error. I have answered it in detail on a different post and I am linking to that post from HERE Thank you all for your time and answers

Basic php/mysql query struggles

I am frustrated and I am beginning to wonder if there is some catch with my hosting company that might be causing this issue. I have done this type of thing before (not with this hosting company) so I am at a loss.
<?php
$q = "SELECT * FROM sunsetUsers";
$r = #mysqli_query($dbh, $q);
if ($r) {
echo 'good job';
} else {
echo 'you suck';
}?>
The connection info is being called in the header and it works. It will connect to the database and supply me with a good message when I tell it to. Yet, when I try to execute a simple query, I get nothing. No errors at all other than it tells me, "you suck." Heh...which is what it should do when the query fails. I am not trying to do anything with the data...I just want to ensure that the query executes with no problems.
Is there any other information I can give that might help here? This seems really simple to me...yet so confused here as to why this isn't working.
You can see your mysql errors with mysql_error (for the purposes of learning):
if (!$r) {
echo mysqli_error(); // display the last error detected
}
Also using the mysql_* & mysqli_* functions are a very old & insecure way of communicating with mysql. Look into pdo for a better way.

sql in php not returning anything

How do I see what is returned from a sql statement in php? I have the following function to get user name from mysql database and I use echo in another php to see the result but nothing shown.
function get_user_name($id_user) {
return mysql_result(mysql_query("SELECT username FROM user WHERE id_user = '$id_user'"));
}
echo $id_user;
$a = get_user_name($id_user);
echo $a;
Can anyone help? Thanks.
Are you echoing the get_user_name(); function?? OR are you even connected to your database? these are two things you need to check before, (if the problem remains) including an error handling method i.e. or die(mysql_error()) at the end of your query to find out the problem.
return mysql_result(mysql_query("SELECT id_user FROM user WHERE id_user = '$id_user'")or die (mysql_error()));
The error handling construct?? in mysql mysql_error() should output the problem in fairly understandable way, as to what is preventing your query not to be shown

mysqli_stmt_prepare returns false from within a function

I am trying my best to object orientate my login scripts and checks for my website. As such, I have created a function that is called named "attempt_login". This function uses a database connection via the "mysqli_connect" function provided by a outside php file that is included and returns the $link variable.
However, when in my "attempt_login" the "mysqli_stmt_prepare" function is reached. It always returns false, and as such, the if statement never runs.
mysql_connect.php
require_once '../conf.php';
$link = mysqli_connect($mysql_server,$mysql_user,$mysql_pass,$mysql_db);
if(mysqli_connect_error())
{
//Fail
echo mysqli_connect_error();
}else{
//Success
}
return $link;
And the code from the "attempt_login" that fails:
$link = require_once 'functions/mysql/mysql_connect.php';
print_r($link);
$stmt = mysqli_stmt_init($link);
echo mysqli_stmt_error($stmt);
echo mysqli_error();
//This if statement always fails.
if(mysqli_stmt_prepare($stmt,"SELECT member_salt FROM members WHERE username=?" ) )
{
mysqli_stmt_bind_param($stmt,'s',$login_details['username']);
mysqli_stmt_execute($stmt);
$member_salt = NULL;
mysqli_stmt_bind_result($stmt,$member_salt);
mysqli_stmt_close($stmt);
}
And calling the function is pretty simple.
attempt_login($login_details);
I have tried many ways to do this, but it seems to only work when it is not within a function. Which defeats the purpose of me trying to have it in a function. If I move the error output to after the if statment, it will print:
No Database Selected
Even though one clearly is set in the link. I also can do a print_r($link); and it does print proper data for the mysql server.
It also has the same issue with procedural and object orientated mysqli styles, and fails as well with "mysqli_prepare".
I do have mysql working on the site, but any attempts to run anything within a function fails.
I have searched for several hours on trying to find a answer, but was unable to locate anything. I look forward to hearing from you! Many thanks in advance.
~Travis
I'd say then you haven't selected a database.
Either $mysql_db isn't set in ../conf.php or there is a typo or $mysql_db isn't visible in mysql_connect.php.
You don't seem to be passing $stmt to your function, I would advise your read this on scopes.

PDO Unbuffered queries

I'm trying to get into PDO details. So I coded this:
$cn = getConnection();
// get table sequence
$comando = "call p_generate_seq('bitacora')";
$id = getValue($cn, $comando);
//$comando = 'INSERT INTO dsa_bitacora (id, estado, fch_creacion) VALUES (?, ?, ?)';
$comando = 'INSERT INTO dsa_bitacora (id, estado, fch_creacion) VALUES (:id, :estado, :fch_creacion)';
$parametros = array (
':id'=> (int)$id,
':estado'=>1,
':fch_creacion'=>date('Y-m-d H:i:s')
);
execWithParameters($cn, $comando, $parametros);
my getValue function works fine, and I get the next sequence for the table. But when I get into execWithParameters, i get this exception:
PDOException: SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute. in D:\Servidor\xampp_1_7_1\htdocs\bitacora\func_db.php on line 77
I tried to modify the connection attributes but it doesn't work.
These are my core db functions:
function getConnection() {
try {
$cn = new PDO("mysql:host=$host;dbname=$bd", $usuario, $clave, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
));
$cn->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
return $cn;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
function getValue($cn, $comando) {
$resul = $cn->query($comando);
if (!$resul) return null;
while($res = $resul->fetch()) {
$retorno = $res[0][0];
break;
}
return $retorno;
}
function execWithParameters($cn, $comando, $parametros) {
$q = $cn->prepare($comando);
$q->execute($parametros);
if ($q->errorInfo() != null) {
$e = $q->errorInfo();
echo $e[0].':'.$e[1].':'.$e[2];
}
}
Somebody who can shed a light for this? PD. Please do not suggest doing autonumeric id, cause i am porting from another system.
The issue is that mysql only allows for one outstanding cursor at a given time. By using the fetch() method and not consuming all the pending data, you are leaving a cursor open.
The recommended approach is to consume all the data using the fetchAll() method.
An alternative is to use the closeCursor() method.
If you change this function, I think you will be happier:
<?php
function getValue($cn, $comando) {
$resul = $cn->query($comando);
if (!$resul) return null;
foreach ($resul->fetchAll() as $res) {
$retorno = $res[0];
break;
}
return $retorno;
}
?>
I don't think PDOStatement::closeCursor() would work if you're not doing a query that returns data (i.e. an UPDATE, INSERT, etc).
A better solution is to simply unset() your PDOStatement object after calling PDOStatement::execute():
$stmt = $pdo->prepare('UPDATE users SET active = 1');
$stmt->execute();
unset($stmt);
The problem seems to be---I'm not too familiar with PDO--- that after your getValue call returns, the query is still bound to the connection (You only ever ask for the first value, yet the connection returns several, or expects to do so).
Perhaps getValue can be fixed by adding
$resul->closeCursor();
before the return.
Otherwise, if queries to getValue will always return a single (or few enough) value, it seems that using fetchAll will be preferred.
I just spend 15 minutes googling all around the internet, and viewed at least 5 different Stackoverflow questions, some who claimed my bug apparently arose from the wrong version of PHP, wrong version of MySQL library or any other magical black-box stuff...
I changed all my code into using "fetchAll" and I even called closeCursor() and unset() on the query object after each and every query. I was honestly getting desperate! I also tried the MYSQL_ATTR_USE_BUFFERED_QUERY flag, but it did not work.
FINALLY I threw everything out the window and looked at the PHP error, and tracked the line of code where it happened.
SELECT AVG((original_bytes-new_bytes)/original_bytes) as saving
FROM (SELECT original_bytes, new_bytes FROM jobs ORDER BY id DESC LIMIT 100) AS t1
Anyway, the problem happened because my original_bytes and new_bytes both where unsigned bigints, and that meant that if I ever had a job where the new_bytes where actually LARGER than the original_bytes, then I would have a nasty MySQL "out of range" error. And that just happened randomly after running my minification service for a little while.
Why the hell I got this weird MySQL error instead of just giving me the plain error, is beyond me! It actually showed up in SQLBuddy (lightweight PHPMyAdmin) when I ran the raw query.
I had PDO exceptions on, so it should have just given me the MySQL error.
Never mind, the bottom line is:
If you ever get this error, be sure to check that your raw MySQL is actually correct and STILL working!!!
A friend of mine had very much the same problem with the xampp 1.7.1 build. After replacing xampp/php/* by the 5.2.9-2 php.net build and copying all necessary files to xampp/apache/bin it worked fine.
If you're using XAMPP 1.7.1, you just need to upgrade to 1.7.2.

Categories