Answers for "PHP MYSQL Commands out of sync"

PHP
0

PHP MYSQL Commands out of sync

<?php
    
/**
 *	Free all resultsets from $dbCon. Object Oriented
 * Originally from https://falseisnotnull.wordpress.com/2013/06/02/mariadbmysql-commands-out-of-sync-error/
 *	@param		mysqli		$dbCon	mysqli object.
 *	@return		void
 */
function free_all_results(mysqli $dbCon)
{
    do {
        if ($res = $dbCon->store_result()) {
            $res->fetch_all(MYSQLI_ASSOC);
            $res->free();
        }
    } while ($dbCon->more_results() && $dbCon->next_result());
}
    
$db = new mysqli('...', '...', '...', '...');
    
$sql = <<<SQL
    DROP TABLE IF EXISTS `test`.`tab1`;
    CREATE TABLE `test`.`tab1` (`col` INT);
    INSERT INTO `test`.`tab1` VALUE (1);
SQL;
$db->multi_query($sql);
    
free_all_results($db);
    
$sql = 'SELECT * FROM `test`.`tab1`;';
$res = $db->query($sql);
    
if ($db->sqlstate !== '00000') {
    echo 'SQLSTATE: ' . $db->sqlstate . '; Error: ' . $db->errno . ' - ' . $db->error;
} else {
    echo $res->num_rows;
}


/**
 * Free all resultsets from $dbCon. Procedural
 * @param mysqli $dbCon mysqli object.
 * @return        void
 */
function free_all_results(mysqli $dbCon): void {
	do {
		if ($res = mysqli_store_result($dbCon)) {
			// $res->fetch_all(MYSQLI_ASSOC);
			mysqli_fetch_all($res, MYSQLI_ASSOC);
			mysqli_free_result($res);

		}
	} while (mysqli_more_results($dbCon) && mysqli_next_result($dbCon));
}






?>
Posted by: Guest on July-17-2021

Browse Popular Code Answers by Language