MYSQLi - Commands out of sync error - php

Got some code here. Been stuck on it for ages and I can't seem to get around the error.
<?PHP
error_reporting(E_ALL);
ini_set('display_errors',1);
$mysqli = new mysqli('localhost', 'username', 'password', 'table');
$statsObjects = array();
$collatedObjects = array();
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
Global $areRows;
$areRows = 2;
if( $result = $mysqli->query("SELECT * FROM stats WHERE collated = 0", MYSQLI_USE_RESULT) )
{
while($row = $result->fetch_assoc())
{
array_push($statsObjects,
new Statistic(
$row['ID'],
$row['player_GUID'],
$row['shots_fired'],
$row['shots_hit'],
$row['damage_done'],
$row['damage_taken'],
$row['friendly_damage_done'],
$row['friendly_damage_taken']
));
}
$success = true;
} //end if
$result->free_result();
if($success)
{
foreach($statsObjects as $stat)
{
$statsGuid = $stat->getGuid();
$query = "SELECT COUNT(*) AS total FROM collatedStats WHERE player_GUID = '" . $statsGuid . "'";
if( $result2 = $mysqli->query($query, MYSQLI_USE_RESULT) )
{
$value = $result2->fetch_assoc();
$rows = $value['total'];
if($rows > 0)
{
$areRows = 1;
}
else
{
$areRows = 0;
}
}
else
{
echo("Error <br/>");
echo($mysqli->error);
}
if($areRows == 1)
{
echo("Found a row! <br/>");
}
elseif($areRows == 0)
{
Echo("No rows found. =) <br/>");
}
} //end foreach
}
//OBJECT
class Statistic
{
var $GUID;
var $shotsfired;
var $shotshit;
var $damagedone;
var $damagetaken;
var $friendlydamagedone;
var $friendlydamagetaken;
var $ID;
function Statistic($ID, $GUID, $fired, $hit, $ddone, $dtaken, $fddone, $fdtaken)
{
$this->id = $ID;
$this->GUID = $GUID;
$this->shotsfired = $fired;
$this->shotshit = $hit;
$this->damagedone = $ddone;
$this->damagetake = $dtaken;
$this->friendlydamagedone = $fddone;
$this->friendlydamagetaken = $fdtaken;
}
function getID()
{
return $this->ID;
}
function getGuid()
{
return $this->GUID;
}
function getShotsFired()
{
return $this->shotsfired;
}
function getShotsHit()
{
return $this->shotshit;
}
function getDamageDone()
{
return $this->damagedone;
}
function getDamageTaken()
{
return $this->damagetaken;
}
function getFriendlyDDone()
{
return $this->friendlydamagedone;
}
function getFriendlyDTaken()
{
return $this->friendlydamagetaken;
}
function getAccuracy()
{
if($shotsfired == 0)
{
$accuracy = 0;
}
else
{
$accuracydec = $shotshit / $shotsfired;
$accuracy = $accuracydec * 100;
}
return $accuracy;
}
}
Basically every time i run the code, it keeps coming up with the error "Commands out of sync; you can't run this command now". I've spent 2 days trying to fix it - following peoples instructions about freeing the result before running the next one. I even used a prepared statement in previous code however it didn't work either - this is newly written code in an attempt to get it working. All the reading i've done suggests that this error happens when you try to run an sql command while another one is still receiving data - however i've called my first query, stored it all in an array - and then i'm looping through the array to get the next lot of data..and that's giving me an error, which is where i'm getting confused.
Any help would be appreciated!

Thank You to #andrewsi for his help - it turns out that having the MYSQLI_USE_RESULT inside SELECT * FROM stats WHERE collated = 0", MYSQLI_USE_RESULT was giving me the error. Removing that allowed me to do my code normally.
Hopefully this helps others that may have the same problem. =)

Related

how to insert a query within a class?

I am working on a class where I want to check if everything is filled in and if everything is filled in then insert into the database, but I am stuck on how I can insert within my class so I hope you guys could help me. I never got any errors of this problem.
Here is the code:
<?php
class clsCatCheck
{
private $catName;
public function __construct($catName)
{
$this->setCatName($catName);
}
public function setCatName($catName)
{
$connect = new PDO('mysql:host=hostname;dbname=dbname', "username", "password");
$select = $connect->prepare('SELECT * FROM category');
$row = $select->fetch();
if (isset($_POST['addCat'])) {
if (empty($_POST['catName'])) {
throw new Exception('Geen categorienaam is ingevuld<br />');
}
//if (strlen($_POST['catName'] <= 4)) {
// throw new Exception('De categorienaam moet minimaal 4 letters of langer zijn<br />');
//}
if ($_POST['catName'] == $row[1]) {
throw new Exception('Deze categorienaam bestaat al<br />');
}
}
else {
$query = $connect->prepare("INSERT INTO category (catName) VALUES (:catName = catName)");
$query->bindParam(':catName', $_POST['catName'] ,PDO::PARAM_STR);
$query->execute();
}
$this->catName = $catName;
}
public function getCatName()
{
return $this->catName;
}
}
Already thanks for helping.
If you want more code from me just ask.
You are not binding parameters correctly.
Corrected code:
$query = $connect->prepare("INSERT INTO category (catName) VALUES (:catName)");
$query->bindParam(':catName', $_POST['catName'] ,PDO::PARAM_STR);

Error mysqli_insert_id

Using the PHP manual I created following code:
$query = "INSERT INTO inserir(nome) VALUES ('Stefanato');";
$listar = new consultar();
$listar->executa($query);
echo "New record has id: " . mysqli_insert_id($listar->$query);
I also used this answer for class connections: Error mysqli_select_db
But I keep getting this error:
Warning: mysqli_insert_id () expects parameter exactly 1, 2 given in
/home/controle/public_html/demo/teste.php on line 9
How do I fix that?
Here is the simple example for getting the id of last record created-
Code is taken from here
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Glenn','Quagmire',33)");
// Print auto-generated id
echo "New record has id: " . mysqli_insert_id($con);
mysqli_close($con);
?>
Edit: Here is working code
<?php
define("SERVIDOR_BD", "localhost");
define("USUARIO_BD", "usuario");
define("SENHA_BD", "senha");
define("BANCO_DE_DADOS", "dados");
class conecta {
public $database_bancoDados = null;//1. New Added Field
public $bancoDados = null;//2. New Added Field
function conecta($servidor="", $bancoDeDados="", $usuario="", $senha=""){
if (($servidor == "") && ($usuario == "") && ($senha == "") && ($bancoDeDados == "")){
$this->bancoDados = mysqli_connect(SERVIDOR_BD, USUARIO_BD, SENHA_BD) or trigger_error(mysqli_error(),E_USER_ERROR);//3. Store in class variable
$this->database_bancoDados = BANCO_DE_DADOS;//4. Store in class variable
} else {
$this->bancoDados = mysqli_connect($servidor, $usuario, $senha) or trigger_error(mysqli_error(),E_USER_ERROR);//5. Store in class variable
$this->database_bancoDados = $bancoDeDados;//6. Store in class variable
}
}
}
class consultar {
var $bd;
var $res;
var $row;
var $nrw;
var $data;
function executa($sql=""){
if($sql==""){
$this->res = 0; // Pointer result of the executed query
$this->nrw = 0; // Line number the query returned, cruise control
$this->row = -1; // Array of the current query line
}
// Connects to the database
$this->bd = new conecta();//7. Store in class variable
$this->bd->conecta();//8. Store in class variable
mysqli_select_db($this->bd->bancoDados, BANCO_DE_DADOS);//9. Change Here For parameter sequence
$this->res = mysqli_query($this->bd->bancoDados, $sql); //10. Change here for parameter sequence
$this->nrw = #mysqli_num_rows($this->res);
$this->row = 0;
if($this->nrw > 0)
$this->dados();
}
function primeiro(){
$this->row = 0;
$this->dados();
}
function proximo(){
$this->row = ($this->row<($this->nrw - 1)) ?
++$this->row:($this->nrw - 1);
$this->dados();
}
function anterior(){
$this->row = ($this->row > 0) ? -- $this->row:0;
$this->dados();
}
function ultimo(){
$this->row = $this->nrw-1;
$this->dados();
}
function navega($linha){
if($linha>=0 AND $linha<$this->nrw){
$this->row = $linha;
$this->dados();
}
}
function dados(){
mysqli_data_seek($this->res, $this->row);
$this->data = mysqli_fetch_array($this->res);
}
}
$query = "INSERT INTO inserir(uname) VALUES ('Stefanato');";
$listar = new consultar();
$listar->executa($query);
echo "New record has id: " . mysqli_insert_id($listar->bd->bancoDados);//11. Change Here for parameter

function is not showing the success echo on executing?

I am assigning a loop to a function so it's working fine when not enrolled in a function but when it's enrolled in function so it's not showing the echo on success please as :
function questions_query() {
global $mysqli;
global $form_name;
$questions = $_POST['questions'];
for($i=0;$i<count($questions);$i++){
$i_query = $i+1;
$query_2 = mysqli_query($mysqli,"UPDATE forms SET question$i_query='$questions[$i]' WHERE form_name='$form_name'") or die(mysqli_connect_error());
}
}
if (questions_query()) {
echo "All Questions Are Done!";
}
So if you people can please take a look at my code that what is going wrong in there..so I will be thankful to you for that please..!
The function doesn't return anything. There's no return true; or return false; statement.
If it's not successful it never returns, it calls die(), which terminates the whole script. So there's no reason to use if() around the call, just do:
questions_query();
echo 'All Questions Are Done!';
Want to use return
function questions_query() {
global $mysqli;
global $form_name;
$questions = $_POST['questions'];
for($i=0;$i<count($questions);$i++)
{
$i_query = $i+1;
$query_2 = mysqli_query($mysqli,"UPDATE forms SET question$i_query='$questions[$i]' WHERE form_name='$form_name'") or die(mysqli_connect_error());
}
return true;
}
if (questions_query()) {
echo "All Questions Are Done!";
}
else {
//something happened
}
If you want to check MySQL query result, then you need to return error check.
function questions_query() {
global $mysqli;
global $form_name;
$questions = $_POST['questions'];
$has_errors = 0;
for($i=0;$i<count($questions);$i++)
{
$i_query = $i+1;
$query_2 = mysqli_query($mysqli,"...");
if (mysqli_errno($mysqli) > 0) {
$has_errors ++;
}
}
return $has_errors;
}
$errors = questions_query();
if ($errors == 0) {
echo "All Questions Are Done!";
} else {
echo "Errors in questions: $errors times!";
}

Returning a variable that has to be updated from a function, not returning?

There is ALOT of code, but most of it is irrelevant, so i will just post a snippet
$error_message = "";
function died($error) // if something is incorect, send to given url with error msg
{
session_start();
$_SESSION['error'] = $error;
header("Location: http://mydomain.com/post/error.php");
die();
}
This works fine, sends the user away with a error session, which displays the error on the error.php
function fetch_post($url, $error_message) {
$sql = "SELECT * FROM inserted_posts WHERE name = '$name'";
$result = mysqli_query($con, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
$error_message .= $url . " already exists in the database, not added";
return $error_message;
}
}
This also works fine, checks if the "post" exists in the database, if it does, it adds the error the variable $error_message
while ($current <= $to) {
$dom = file_get_html($start_url . $current); // page + page number
$posts = $dom->find('div[class=post] h2 a');
$i = 0;
while ($i < 8) {
if (!empty($posts[$i])) { // check if it found anything in the link
$post_now = 'http://www.somedomain.org' . $posts[$i]->href; // add exstension and save it
fetch_post($post_now, &$error_message); // send it to the function
}
$i++;
}
$current++; // add one to current page number
}
This is the main loop, it loops some variables i have, and fetches posts from a exsternal website and sends the URL and the error_message to the function fetch_posts
(I send it along, and i do it by reference couse i asume this is the only way to keep it Global???)
if (strlen($error_message > 0)) {
died($error_message);
}
And this is the last snippet right after the loop, it is supposed to send the error msg to the function error if the error msg contains any chars, but it does not detect any chars?
You want:
strlen($error_message) > 0
not
strlen($error_message > 0)
Also, call-time pass-by-reference has been deprecated since 5.3.0 and removed since 5.4.0, so rather than call your function like this:
fetch_post($post_now, &$error_message);
You'll want to define it like this:
function fetch_post($url, &$error_message) {
$sql = "SELECT * FROM inserted_posts WHERE name = '$name'";
$result = mysqli_query($con, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
$error_message .= $url . " already exists in the database, not added";
return $error_message;
}
}
Although as you're returning the error message within a loop it would be better to do this:
$error_messages = array();
// ... while loop
if ($error = fetch_post($post_now))
{
$error_messages[] = $error;
}
// ... end while
if (!empty($error_messages)) {
died($error_messages); // change your function to work with an array
}

mysqli and multi_query not working

<?php
$mysqli=mysqli_connect("localhost","root","","politicalforum");
$query="SELECT query_title FROM administrator";
$query.="SELECT thread_id FROM threads";
if($mysqli->multi_query($query))
{
do
{
if($result=$mysqli->store_result())
{
while($row=$result->fetch_row())
{
printf("%s\n",$row[0]);
}
$result->free();
}
if($mysqli->more_results())
{
print("-------------------------------");
}
}while($mysql->next_result());
}
$mysqli->close();
?>
It doesnt work.. it doesnt go to the first if condition that identifies if it is a multiquery..
I have other question, ..why are multi_query() is useful..,
UPDATE:
Strict Standards: mysqli::next_result() [mysqli.next-result]: There is
no next result set. Please, call
mysqli_more_results()/mysqli::more_results() to check whether to call
this function/method in C:\xampp\htdocs\PoliticalForum2\test.php on
line 42
SOLVED:
<?php
$mysqli=mysqli_connect("localhost","root","","politicalforum");
$query="SELECT query_title FROM administrator;";
$query.="SELECT thread_id FROM threads;";
if($mysqli->multi_query($query))
{
do
{
if($result=$mysqli->store_result())
{
while($row=$result->fetch_row())
{
printf("%s<br/>",$row[0]);
}
$result->free();
}
if($mysqli->more_results())
{
print("-------------------------------<br/>");
}
else
{
echo '<br/>';
}
}while($mysqli->more_results() && $mysqli->next_result());
}
$mysqli->close();
?>
You need a semicolon at the end of the first query.
$query="SELECT query_title FROM administrator;";
$query.="SELECT thread_id FROM threads";
mysqli::multi_query
The reason why you get this warning, is simply because you use a do...while loop that evaluates the condition after running the command block. So when there are no more results, the contents of the loop are ran one additional time, yielding that warning.
Using a while ($mysql->next_result())...do loop should fix this. (On a general note: Using post-test loops like you did is quite uncommon in database programming)
If code is poetry, I am trying to be Shakespeare!
You can fix it like this:
if ($res) {
do {
$mycon->next_result(); //// instead of putting it in a while, put it here
if ($result = $mycon->store_result()) {
while ($row = $result->fetch_row()) {
foreach ($row as $cell)
$flag = $cell;
}
///$result->close();
}
$sale=$sale+1;
} while ($sale > 2);
}
I got the answer for the same.
please find my function below.
public function executeStoredProcedureMulti($strQuery)
{
$yml = sfYaml::load(sfConfig::get('sf_config_dir').'/databases.yml');
$params = $yml['all']['doctrine']['param'];
$dsnName = $params['dsn'];
$arrDsn = explode(";",$dsnName);
$hostName = explode("=",$arrDsn[0])[1];
$schemaName = explode("=",$arrDsn[1])[1];
$this->dbconn = mysqli_connect($hostName, $params['username'], $params['password'], $schemaName);
//return if connection was created successfully
if($this->dbconn)
{
mysqli_set_charset($this->dbconn,"utf8");
//return true;
}
else
{
$this->nErrorNumber = mysqli_connect_errno();
$this->strErrorDesc = mysqli_connect_error();
return false;
}
//check if connection exists
if($this->dbconn)
{
/* close connection */
//execute the query
if($this->dbconn->multi_query($strQuery))
{
//create table array in dataset object
$dataSet = array();
do {
//store first result set
if ($result = $this->dbconn->store_result())
{
//create data table passing it the column data
$dataTable = new CDataTable($result->fetch_fields());
//parse through each row
while ($row = $result->fetch_row())
{
$dataTable->AddRow($row);
}
$result->free();
$dataSet[] = $dataTable;
}
if (!$this->dbconn->more_results()) {
break;
}
} while ($this->dbconn->next_result());
$this->dbconn->close();
//return the complete dataset
return $dataSet;
}
else//save the error to member variables
{
$this->nErrorNumber = $this->dbconn->errno;
$this->strErrorDesc = $this->dbconn->error;
}
}
return false;
}
This is working Need to create a Class CTableData. Please make one and it will work great
.

Categories