I am making a simple Log-in feature, with code that has definitely worked (from a tutorial).
It results in an error notice:
Notice: Trying to access array offset on value of type bool in
Why does $row = $query->fetch(); return a boolean value and not an array?
Result of the var_dump($query) with a correct login data:
object(mysqli_stmt)#2 (10) {
["affected_rows"]=> int(-1)
["insert_id"]=> int(0)
["num_rows"]=> int(0)
["param_count"]=> int(1)
["field_count"]=> int(3)
["errno"]=> int(0)
["error"]=> string(0) ""
["error_list"]=> array(0) { }
["sqlstate"]=> string(5) "00000"
["id"]=> int(1)
}
Result of the var_dump($row): bool(true)
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
$email = trim($_POST["email"]);
$password = trim($_POST["password"]);
if($query = $db->prepare("SELECT * FROM user WHERE email = ? ")) {
$query->bind_param("s",$email);
$query->execute();
var_dump($query);
$row = $query->fetch();
var_dump($row);
if($row) {
if(password_verify($password, $row['password'])) {
header("location:https://stackoverflow.com/");
exit;
}
}
}
}
mysqli_stmt::fetch() method does not return an array. It always returns a boolean.
What you are looking for is the mysqli_result object. You can get that object by calling get_result(). This object has methods like fetch_assoc() that will return an array of values. For example:
$query = $db->prepare("SELECT * FROM user WHERE email = ? ");
$query->bind_param("s", $email);
$query->execute();
$row = $query->get_result()->fetch_assoc();
if ($row && password_verify($password, $row['password'])) {
header("location:https://stackoverflow.com/");
exit;
}
However, if you wish to select a single field from the database then you can use mysqli_stmt::fetch() but you must bind the SQL column to a PHP variable.
$query = $db->prepare("SELECT password FROM user WHERE email = ? ");
$query->bind_param("s", $email);
$query->execute();
$query->bind_result($hashedPassword);
if ($query->fetch() && password_verify($password, $hashedPassword)) {
header("location:https://stackoverflow.com/");
exit;
}
I've searched this here and on the internet but can't find a solution.
I'm posting a JSON array like :
[{"phone_number":"+12345678"},
{"phone_number":"+23456789"},
{"phone_number":"34567890"},
{"phone_number":"45678901"}
etc... etc...
Here's my code :
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require('dbConnect.php');
//post all contacts in my phone as a JSON array
$json = $_POST['phonenumber'];
$array = json_decode($json);
foreach ($array as $value)
{
$phonenumber = $value->phone_number;
$stmt = $con->prepare('SELECT * FROM user WHERE username = ?');
$stmt->bind_param('s', $phonenumber);
$stmt->execute();
echo $phonenumber . "<br>";
var_dump($stmt);
}
?>
Only the first phone number in the array echos properly. Then I get :
object(mysqli_stmt)#131 (10) { ["affected_rows"]=> int(-1) ["insert_id"]=> int(0) ["num_rows"]=> int(0) ["param_count"]=> int(1) ["field_count"]=> int(2) ["errno"]=> int(0) ["error"]=> string(0) "" ["error_list"]=> array(0) { } ["sqlstate"]=> string(5) "00000" ["id"]=> int(1) }
Fatal error: Call to a member function bind_param() on a non-object in /var/www/html/checkcontact.php on line 28
Line 28 is : $stmt->bind_param('s', $phonenumber);
When I use this code (not safe though) it works fine, all the phone numbers get echoed correctly :
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require('dbConnect.php');
//post all contacts in my phone as a JSON array
$json = $_POST['phonenumber'];
$array = json_decode($json);
foreach ($array as $value)
{
$phonenumber = $value->phone_number;
$sql = "SELECT * FROM user WHERE username = '$phonenumber'";
$result = mysqli_query($con, $sql);
echo $phonenumber . "<br>";
}
?>
this is code i am trying to work with. i am checking number of total row in a table(how many people registered). my output don't have any error or so, i dont know what am i doing wrong. same thing was working yesterday. god knows what happened now
$query = "SELECT count(*) FROM team";
$result = $db->prepare($query);
$result->execute();
$number= $result->fetch();
print_r($number);
var_dump($result);
OUTPUT:
1
object(mysqli_stmt)#2 (10) { ["affected_rows"]=> int(-1) ["insert_id"]=> int(0) ["num_rows"]=> int(0) ["param_count"]=> int(0) ["field_count"]=> int(1) ["errno"]=> int(0) ["error"]=> string(0) "" ["error_list"]=> array(0) { } ["sqlstate"]=> string(5) "00000" ["id"]=> int(1) }
You could do the following:
$query = "SELECT count(1) FROM team";
if($stmt = $db->prepare($query)){
$stmt->execute();
$stmt->bind_result($number);
$stmt->fetch();
$stmt->free_result();
$stmt->close();
}
echo $number;
or
$query = "SELECT * FROM team";
if($stmt = $db->prepare($query)){
$stmt->execute();
$stmt->store_result();
$number = $stmt->num_rows;
$stmt->free_result();
$stmt->close();
}
echo $number;
I'm fairly new to PHP, and I'm working with mysqli, OOP and prepared statements.
My question is this:
I'm trying to pass an user(object) to an Insert_user(func) in my database(class).
I have 3 classes, 'logic', 'data' and 'index'. Index includes data and logic, and initiates
the connection and user.
In my function (insert_user), I'm using an array to pass user variables into, before
binding and executing my statement.
Hers is my code:
<?php
function insert_user($user) {
$query = "INSERT INTO user VALUES (?,?,?,?,?,?,?,?,?,?)";
$binding = 'issssiisss';
$variables = array( $user->user_id, $user->f_name, $user->l_name, $user->address, $user->city, $user->zipcode, $user->mobile_number, $user->mail, $user->pass_key, $user->pass_word);
$stmt = $this->mysqli->prepare($query);
$stmt->bind_param($binding,$variables[0],$variables[1],$variables[2],$variables[3],$variables[4],$variables[5],$variables[6],$variables[7],$variables[8],$variables[9]);
$stmt->execute();
}
?>
Here is my var_dump from browser:
object(user)#1 (10) { ["user_id"]=> int(1) ["f_name"]=> string(5) "pelle" ["l_name"]=> string(5) "kanin" ["address"]=> string(7) "vænget" ["city"]=> string(6) "aaaaaa" ["zipcode"]=> int(123) ["mobile_number"]=> int(123) ["mail"]=> string(4) "fedt" ["pass_key"]=> string(3) "ert" ["pass_word"]=> string(4) "erto" }
string(10) "issssiisss"
array(10) { [0]=> int(1) [1]=> string(5) "pelle" [2]=> string(5) "kanin" [3]=> string(7) "vænget" [4]=> string(6) "aaaaaa" [5]=> int(123) [6]=> int(123) [7]=> string(4) "fedt" [8]=> string(3) "ert" [9]=> string(4) "erto" }
object(mysqli_stmt)#4 (10) { ["affected_rows"]=> int(-1) ["insert_id"]=> int(0) ["num_rows"]=> int(0) ["param_count"]=> int(10) ["field_count"]=> int(0) ["errno"]=> int(0) ["error"]=> string(0) "" ["error_list"]=> array(0) { } ["sqlstate"]=> string(5) "00000" ["id"]=> int(1) }
What am i doing wrong!?
Thank you.
EDIT: The problem is inserting the data into the database. It simply doesn't work. When i execute no data is put in.
I think the problem lies with the $stmt->bind_param function, and inserting the data from the array.
param_count = 10 and field_count = 0!
EDIT !2!:
OK. So, it actually works! what i did wrong was specify a integer value in my user_id, i.e. when i created the user. My database uses AUTO.INCREMENT on that value, and therefore it didn't work..
Anyways, thanks for the answer. G'day!
Check if you have any errors when after each mysqli statement to isolate the error:
$stmt = $this->mysqli->prepare($query);
if ( false===$stmt ) {
die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}
$stmtBindResult = $stmt->bind_param($binding,$variables[0],$variables[1],$variables[2],$variables[3],$variables[4],$variables[5],$variables[6],$variables[7],$variables[8],$variables[9]);
if ( false===$stmtBindResult ) {
die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}
$stmtExecuteResult = $stmt->execute();
if ( false===$stmtExecuteResult ) {
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
else you can use basic PDO. I would use PDO insert with following basic function:
$Query = "INSERT INTO user VALUES (?,?,?,?,?,?,?,?,?,?)";
$Params = array($variables[0],$variables[1],$variables[2],$variables[3],$variables[4],$variables[5],$variables[6],$variables[7],$variables[8],$variables[9]);
$InsertResult = PDOInsert($Query, $Params);
function PDOInsert($Query, $Parameters)
{
try
{
$PDOConnection = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.'', DB_USER, DB_PASS);
$PDOConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$Statement = $PDOConnection->prepare($Query);
foreach ($Parameters as $Key => $Val)
$Statement->bindValue($Key+1, $Val);
$Statement->execute();
$PDOConnection = null;
return true;
}
catch(PDOException $e)
{
die('ERROR: ' . $e->getMessage());
return false;
}
}
I am running
$this->db->query("SELECT `id` FROM $table WHERE $table.id ='$product_id'");
that should return 92 but its returning the below why?
object(CI_DB_mysqli_result)#150 (8) { ["conn_id"]=> object(mysqli)#16
(18) { ["affected_rows"]=> int(1) ["client_info"]=> string(6) "5.5.30"
["client_version"]=> int(50530) ["connect_errno"]=> int(0)
["connect_error"]=> NULL ["errno"]=> int(0) ["error"]=> string(0) ""
["field_count"]=> int(1) ["host_info"]=> string(25) "Localhost via
UNIX socket" ["info"]=> NULL ["insert_id"]=> int(0) ["server_info"]=>
string(10) "5.5.31-cll" ["server_version"]=> int(50531) ["stat"]=>
string(150) "Uptime: 106781 Threads: 14 Questions: 30097132 Slow
queries: 13 Opens: 1937675 Flush tables: 1 Open tables: 400 Queries
per second avg: 281.858" ["sqlstate"]=> string(5) "00000"
["protocol_version"]=> int(10) ["thread_id"]=> int(373292)
["warning_count"]=> int(0) } ["result_id"]=> object(mysqli_result)#161
(5) { ["current_field"]=> int(0) ["field_count"]=> int(1)
["lengths"]=> NULL ["num_rows"]=> int(1) ["type"]=> int(0) }
["result_array"]=> array(0) { } ["result_object"]=> array(0) { }
["custom_result_object"]=> array(0) { } ["current_row"]=> int(0)
["num_rows"]=> NULL ["row_data"]=> NULL}
It is returning mysqli_ object.So Try to get the result like
$query = $this->db->query("SELECT `id` FROM $table WHERE $table.id ='$product_id'");
$result = $query->result();
foreach($result as $row)
{
echo "Id is ".$row['id']."<br>";
}
And it is appreciable that you are using mysqli_* functions instead of deprecated mysql_* functions
It's returning a mysqli_result object, exactly as the manual says it does.
To get the actual id you need to call fetch_assoc() (or similar) on the object.
if ($result = $this->db->query("SELECT id FROM $table WHERE $table.id ='$product_id'")) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("Fetched ID: %s\n", $row["id"]);
}
/* free result set */
$result->free();
}
Basically the statement:
$this->db->query("SELECT 'id' FROM $table WHERE $table.id ='$product_id'");
returns an object that can be used to extract the result set or table and assigned to a variable... so you need to create a variable and assign the result set to it as:
$mysqli = new mysqli("localhost","rinonymous","03318987165oo","rinonymous");
if ($mysqli->connect_errno) {
print_r($mysqli->connect_error);
exit();
}
$site_title = "Rinonymous";
$page_title = "";
$page_body = "";
#Page Setup
$query_page_info = "select * from pages where id = 1";
foreach ($mysqli->query($query_page_info) as $row) {
print_r($mysqli->query($query_page_info));
#query method returns an associate array
print_r($row);
$page_title = $row['title'];
$page_body = $row['body'];
}