In PHP, SQLite3Result object has not been correctly initialised - php

I have that piece of code in my php file (correctly working):
$db = new Database();
$stmt = $db->prepare("SELECT * FROM bills WHERE group_id=:gid");
$stmt->bindValue(":gid", $_SESSION['group_id'], SQLITE3_INTEGER);
if (($result = $stmt->execute()) === false) {
echo "bad";
}
$bills = $result;
while ($bill = $bills->fetchArray()) {
do stuff....
}
Then I try to put all database related code in function:
function getBillsByGID($gid) {
$db = new Database();
$stmt = $db->prepare("SELECT * FROM bills WHERE group_id=:gid");
$stmt->bindValue(":gid", $gid, SQLITE3_INTEGER);
if (($result = $stmt->execute()) === false) {
return null;
}
return $result;
}
And in the original file:
$bills = getBillsByGID($_SESSION['group_id']);
while ($bill = $bills->fetchArray()) {
do stuff...
}
That gives me message: "Warning: SQLite3Result::fetchArray(): The SQLite3Result object has not been correctly initialised in line 61" (line with while($bill = $bills->fetchArray()))
var_dump($bills) after calling the function gives object(SQLite3Result)#10 (0) { }
So how do I make a function which will work properly?

Are you closing the statement in your getBillsByGID? Calling $stmt->close() invalidates the result you got from $stmt->execute(). After that, calling $result->fetchArray() will give the error "The SQLite3Result object has not been correctly initialised in ...".

I think you need to fetch data in your function and then return your variable
function getBillsByGID($gid) {
$db = new Database();
$stmt = $db->prepare("SELECT * FROM bills WHERE group_id=:gid");
$stmt->bindValue(":gid", $gid, SQLITE3_INTEGER);
if ($stmt->execute() === false) {
return null;
}
$array = array();
while($data = $stmt->fetchArray())
{
$array[] = $data;
}
return $array;
}
Now assign the function to a variable and loop throw to get your array's data
$bills = getBillsByGID($_SESSION['group_id']);
foreach($bills as $data) {
//do stuff with $data
}

Related

PHP - Getting: Commands out of sync; you can't run this command now

I know that there were hundreds of similar questions, I have tried everything and nothing really worked for me.
I have got this function that is calling stored procedure in my MariaDB. This is returning array.
<?
class MyClass {
protected static $connection;
public function connect() {
// Try and connect to the database
if(!isset(self::$connection)) {
self::$connection = new mysqli(SERVERNAME,USERNAME,PASS,DBNAME);
}
// If connection was not successful, handle the error
if(self::$connection === false) {
// Handle error - notify administrator, log to a file, show an error screen, etc.
return false;
}
return self::$connection;
}
public function query($query) {
// Connect to the database
$connection = $this -> connect();
// Query the database
$result = $connection -> query($query);
return $result;
}
public function quote($value) {
$connection = $this -> connect();
return $connection -> real_escape_string($value);
}
public function CallStoredProc($query) {
// Connect to the database
$connection = $this -> connect();
// Query the database
$result = $connection -> query($query,MYSQLI_USE_RESULT); //,
if($result === false) {
return false;
}
while ($row = $result -> fetch_assoc()) {
$rows[] = $row;
}
$result->free();
return $rows;
}
function StoreProcessed($Name,$Price){
//escape
$Name = $this->quote($Name);
$Price= $this->quote($Price);
$SQL = "INSERT INTO Result (`Name`,`Price`) VALUES ('$Name','$Price');";
$result = $this->query($SQL);
}
//the function I am using for processing:
function Compare($ID) {
$query = "CALL MyProcedure($ID);";
$result =$this->CallStoredProc($query);
/*After the array is returned I am looping trough each element of array
and storing this in DB with another function. */
$Table = "<table>";
foreach ($result as $key=>$val)
{
$Name = $result[$key]["Name"];
$Price = $result[$key]["Price"];
$this->StoreProcessed($Name,$Price);
//This is where the Commands out of sync is returned
$Table = $Table. "<tr>
<td>$Name</td>
<td>$Price</td>
</tr>";
}
$Table = $Table. "</table>";
return $Table;
}
}
My php file then looks like this:
<?
$auto = new MyClass();
$table = $auto->Compare(14);
echo $table;
?>
I am using MYSQLI_USE_RESULT, after the array is filled, I am using the mysqli_free_result as well. What else should I do?
Many thanks!
I've found answer here . Just added this function:
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());
}
And I called it before returning the results:
public function CallStoredProc($query) {
// Connect to the database
$connection = $this -> connect();
// Query the database
$result = $connection -> query($query); //,
mysqli_store_result($connection);
if($result === false) {
return false;
}
while ($row = $result -> fetch_assoc()) {
$rows[] = $row;
}
$this->free_all_results($connection);
return $rows;
}

setting php boolean to FALSE not working

I have no records in a table called assessment
I have a function:
function check_assessment_record($p_id, $a_id, $c){
$dataexistsqry="SELECT * FROM assessments WHERE (pupil_id=$p_id && assessblock_id=$a_id)" ;
$resultt = $c->query($dataexistsqry);
if ($resultt->num_rows > 0) {
echo '<p>set $de = true</p>';
$de=TRUE;
}else{
echo '<p>set $de = false</p>';
$de=FALSE;
}
return $de;
$dataexists->close();
}; //end function
I call the function thus:
$thereisdata = check_assessment_record($pupil_id, $assessblock_id, $conn);
However my function is printing out nothing when I was expecting FALSE. It prints out true when there's a record.
When I get the result in $thereisdata I want to check for if its TRUE or FALSE but its not working.
I looked at the php manual boolean page but it didn't help
It seems that you are passing the database connection as an object using the variable $c in your function parameter. This tells me that you would greatly benefit by creating a class and using private properties/variables. Also, there are many errors in your code that shows me what you are trying to achieve, some errors are the way you are closing your db connection using the wrong variable, or how you place the close connection method after the return, that will never be reached.
Anyway, I would create a database class where you can then call on specific functions such as the check_assessment_record() as you wish.
Here's how I would redo your code:
<?php
class Database {
private $conn;
function __construct() {
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
// Create connection
$this->conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($this->conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
}
function check_assessment_record($p_id, $a_id) {
$sql = "SELECT * FROM assessments WHERE (pupil_id=$p_id && assessblock_id=$a_id)";
$result = $this->conn->query($sql);
if ($result->num_rows > 0) {
echo '<p>set $de = true</p>';
$de = TRUE;
} else {
echo '<p>set $de = false</p>';
$de = FALSE;
}
return $de;
}
function __destruct() {
$this->conn->close();
}
}
$p_id = 1;
$a_id = 2;
$db = new Database();
$record = $db->check_assessment_record($p_id, $a_id);
var_dump($record);
?>
are you using PDO's correctly?
A call for me would normally look like;
$aResults = array();
$st = $conn->prepare( $sql );
$st->execute();
while ( $row = $st->fetch() ) {
//do something, count, add to array etc.
$aResults[] = $row;
}
// return the results if there is, else returns null
if(!empty($aResults)){return $aResults;}
if you didnt want to put the results into an array you could just check if a column is returned;
$st = $conn->prepare( $sql );
$st->execute();
if(! $st->fetch() ){
echo 'there is no row';
}
Here is the code
function check_assessment_record($p_id, $a_id, $c){
$dataexistsqry="SELECT * FROM assessments WHERE (pupil_id=$p_id && assessblock_id=$a_id)" ;
$resultt = $c->query($dataexistsqry);
if ($resultt->num_rows > 0) {
echo '<p>set $de = true</p>';
$de=TRUE;
}else{
echo '<p>set $de = false</p>';
$de=FALSE;
}
return $de;
$dataexists->close();
}; //end function
You can check the return value using if else condition as
$thereisdata = check_assessment_record($pupil_id, $assessblock_id, $conn);
if($thereisdata){ print_f('%yes data is present%'); }
else{ print_f('% no data is not present %'); }
The reason is , sometime function returning Boolean values only contain the true value and consider false value as null , that's why you are not printing out any result when data is not found.
Hope this will help you. Don't forget to give your review and feedback.

PHP fetch() not returning results for SELECT query in MySQL

I have a function to search for records by course name:
<?php
function searchByCourse()
{
if (isset($_POST["course_title"])) {
//Copy to local var
$course_title = $_POST["course_title"];
$stmt = self::$conn->prepare("SELECT student_id, student_name, course_title FROM student_info WHERE course_title = ?");
$stmt->bind_param("s", $course_title);
$result = $stmt->execute();
if ($result === FALSE) {
$stmt->close();
return FALSE;
} else {
$results_array = array();
$stmt->bind_result($student_id, $student_name, $course_title_found);
while ($stmt->fetch()) {
echo "Fetch! \n";
$row = array();
$row["student_id"] = $student_id;
$row["student_name"] = $student_name;
$row["course_title"] = $course_title;
$results_array[] = $row;
}
$stmt->close();
return $results_array;
}
} else {
return FALSE;
}
}
?>
The code seems to execute fine but when I test it using curl for course_title=Computing it should return 3 results. However the echo "Fetch!" is never displayed. It seems to be that there is nothing for it to fetch. It's driving me a little crazy. I've checked all the var names in the database and they match up fine. Any ideas what I could be doing wrong here?
EDIT:
This method is part of my class DbHandler. $conn is a protected static MySqli connection object created in function__contruct().
called like this:
$db = new DbHandler();
$db->searchByCourse();
I have other database functions that work fine for this design pattern. The function is being called correctly. I have also checked the $_POST["course_title"] and that is being passed correctly.

PHP database connection class bind_param

I would like to write a database connection class and I dont understand how I have to write the select method with bind_param-s. Here is the full code. And here the part of the code where I need the help:
public function select($sql){
$db = $this->connect(); //This methos connect to the DB
$stmt = $db->prepare($sql);
if($stmt === false){ //If the prepare faild
trigger_error("Wrong SQL", E_USER_ERROR);
}
$error = $stmt->bind_param("i", $id);
if($error){
return "Error: ".$stmt->error, $stmt->errno;
}
$err = $stmt->execute();
if($error){
return "Error: ".$stmt->error, $stmt->errno;
}
$result = $stmt->bind_result($id);
$stmt->close();
$dbConnection->closeConnection($db);
return $result;
}
I need to got it parameters or how can I slove it?
You need to pass your values into this function too. And eventually bind them into prepared statement.
Optionally you can pass string with types, but by default all "s" will do.
Also remember that you should connect only ONCE per script execution. and then use one single connection all the way throughout your code.
And get rid of all these error checks. Set mysqli in exception mode instead.
public function q($sql, $values = array(), $types = NULL)
{
$stm = $this->mysql->prepare($sql);
if (!$types)
{
$types = str_repeat("s", count($values));
}
if (strnatcmp(phpversion(),'5.3') >= 0)
{
$bind = array();
foreach($values as $key => $val)
{
$bind[$key] = &$values[$key];
}
} else {
$bind = $values;
}
array_unshift($bind, $types);
call_user_func_array(array($stm, 'bind_param'), $bind);
$stm->execute();
return $stm->get_result();
}
so it can be used like this
$res = $db->q("SELECT name FROM users WHERE id=?", [$id]);
or
$res = $db->q("SELECT name FROM users WHERE id=?", [$id], "i");
your other functions have to be changed as well.
class DB{
public $con;
function __construct()
{
$this->con = new mysqli("localhost", "root", "", "proba_fferenc");
}
public function select(...)
{
// as shown above
}
}

Trouble with php (call to a member function on a non-object)

I am getting this php error and I can't seem to fix it.
Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\mlrst\database.php on line 26
here is the line that is calling function prepare.
$this->statement->prepare($strQuery);
and here is it being declared.
protected $statement;
any ideas?
Edit: Here is my full code (don't mind the testing dummies)
<?php
$d = new database(); // test
class database {
protected $db_connect;
protected $statement;
function database() {
$db_connect = new MySQLi("localhost", "root" ,"", "test") or die("Could not connect to the server.");
$statement = $db_connect->stmt_init();
$this->preparedQuery("INSERT INTO feedback (name, feedback) VALUES ('?', '?')");
$this->close();
echo "Done!";
}
protected function cleanString($strLine) {
$strCleansedLine = preg_replace("/[^a-zA-Z0-9\s]/", "", $strLine);
return $strCleansedLine;
}
public function preparedQuery($strQuery, $parameters = NULL) {
try {
$this->statement->prepare($strQuery);
$statement->bind_param("ss", $name, $feedback);
for ($i = 0; $i < count($parameters); $i++) {
}
$name = $this->cleanString("this is my name");
$feedback = $this->cleanString("this is some feedback");
$query = $statement->execute();
} catch(Exception $e) {
echo $e->getMessage();
}
}
protected function close() {
try {
if ($this->statement != NULL)
$this->statement->close();
if ($this->db_connect != NULL)
$this->db_connect->close();
} catch (Exception $e) {
$e->getMessage();
}
}
}
?>
You assigned the local variable $statement. You need to set the instance's property using $this->statement.
In other words, change this:
$statement = $db_connect->stmt_init();
To this:
$this->statement = $db_connect->stmt_init();
And this:
$statement->bind_param("ss", $name, $feedback);
To this:
$this->statement->bind_param("ss", $name, $feedback);
...and this:
$query = $statement->execute();
To this:
$query = $this->statement->execute();

Categories