Why get_result return object in this example?
function db_connect() {
$db_host='localhost';
$db_name='contact_manager';
$db_user='root';
$db_pass='';
$connection = new mysqli($db_host, $db_user, $db_pass, $db_name);
return $connection;
}
$connection = db_connect();
$query = $connection->prepare("SELECT * FROM users");
$query->execute();
$op = $query->get_result();
var_dump($op);
this is the vardump:
object(mysqli_result)#3 (5) {
["current_field"]=> int(0)
["field_count"]=> int(4)
["lengths"]=> NULL
["num_rows"]=> int(24)
["type"]=> int(0) }
According to official documentation (here), get_result() returns a resultset for successful SELECT queries. Next you must extract data from the result set, using for example $result->fetch_assoc():
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
echo $row['user_id'];
}
Related
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'm using this to select data from mysql in php
<?php
error_reporting(E_ALL);
$servername = "localhost";
$username = "******";
$password = "******";
$database = "*******";
// Create connection
$conn2 = new mysqli($servername, $username, $password, $database);
$stmt = $conn2->prepare('SELECT id, title, views from `blog_main`');
$stmt->execute();
var_dump($stmt);
$result = $stmt->get_result();
while($r=$result->fetch_assoc())
{
echo "id: " . $r["id"]. " - Name: " . $r["title"]. " " . $r["views"]. "<br>";
}
$conn->close();
?>
However no result is shown, but if I run this query on phpmyadmin interface it returns rows.
This code worked fine on localhost but when I shifted it to godaddy's server, I'm facing this problem only in prepared statement.
When I'm using normal query method it displays rows, only prepared statements are not working.
This is the value of var dump:
object(mysqli_stmt)#2 (10) { ["affected_rows"]=> int(-1) ["insert_id"]=> int(0) ["num_rows"]=> int(0) ["param_count"]=> int(0) ["field_count"]=> int(3) ["errno"]=> int(0) ["error"]=> string(0) "" ["error_list"]=> array(0) { } ["sqlstate"]=> string(5) "00000" ["id"]=> int(1) }
Is there any kind of extension I need to enable or what might be the problem?
here is my answer for your question,
create file db.php
$dbInfo = array(
'host' => "localhost",
'user' => "******",
'pass' => "******",
'dbname' => "******"
);
create dbcon.php
class database{
protected $databaseLink;
function __construct(){
include "db.php";
$this->database = $dbInfo['host'];
$this->mysql_user = $dbInfo['user'];
$this->mysql_pass = $dbInfo['pass'];
$this->databaseName = $dbInfo['dbname'];
$this->openConnection();
return $this->get_link();
}
function openConnection(){
$this->databaseLink = mysqli_connect($this->database, $this->mysql_user, $this->mysql_pass, $this->databaseName);
}
function get_link(){
return $this->databaseLink;
}
}
create func.php
include "dbcon.php";
function selectData(){
$db = new database();
$selectQuery = "SELECT id, title, views FROM blog_main";
$selectQuery = mysqli_query($db->get_link(), $selectQuery) or die(mysqli_error());
while($r = mysqli_fetch_assoc($selectQuery)) {
$rows[] = $r;
}
return $result = json_encode(($rows));
mysqli_close($db->get_link());
}
and in for example index.php you can get data from which SQL return
include "func.php";
$data = selectData();
$dataJson = json_decode($data, TRUE);
foreach ($dataJson as $key => $value) {
echo "id: " . $value['id']. " - Name: " . $value['title']. " " . $value['views']. "<br>";
}
good luck
Seems like it was the disable driver issue. I enabled the stmt_mysqli driver and it worked.
I have an error in php and I have no idea how to fix this. By the way this is my school lesson example so I don't really know what's happening there. This is supporsed to be master/detail navigation.
<?php
$mysqli = new mysqli("localhost", "root", "", "base");
$stmt = $mysqli->prepare('SELECT * FROM aeromiting WHERE id = ":id"');
echo $mysqli->error;
$stmt->bind_param(':id', $_GET['id']);
var_dump($stmt);
$data = $stmt->execute();
?>
Warning: mysqli_stmt::bind_param(): Number of elements in type
definition string doesn't match number of bind variables in
C:\xampp\htdocs\test1\detail.php on line 20 object(mysqli_stmt)#2 (10)
{ ["affected_rows"]=> int(0) ["insert_id"]=> int(0) ["num_rows"]=>
int(0) ["param_count"]=> int(0) ["field_count"]=> int(4) ["errno"]=>
int(0) ["error"]=> string(0) "" ["error_list"]=> array(0) { }
["sqlstate"]=> string(5) "00000" ["id"]=> int(1) }
If you want to do it in PDO, try this...
<?php
$host = 'localhost'; $db = 'base'; $user = 'root'; $pw = '';
$conn = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pw);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$id = $_GET['id'];
$sql = "SELECT * FROM aeromiting WHERE id=:id";
$query = $conn->prepare($sql);
$query->bindValue(':id', $id, PDO::PARAM_INT);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$totalRows = $query->rowCount();
} catch (PDOException $e) {
die("Could not get the data: " . $e->getMessage());
}
?>
Have a look at pdo_mysql for more information.
You're mixing APIs here. MySQLi can't accept strings or the likes as parameters.
$stmt = $mysqli->prepare('SELECT * FROM aeromiting WHERE id = ":id"');
$stmt->bind_param(':id', $_GET['id']);
Should be
$stmt = $mysqli->prepare('SELECT * FROM aeromiting WHERE id = ?');
$stmt->bind_param('i', $_GET['id']);
This is of course assumed that $_GET['id'] is an integer (hence the 'i' in the bind_param. If it's a string, replace the i with s.
You should probably get a bind_result as well, so you actually bind the results from the database to some variables. Take a look at the MySQLi documentation.
I'm trying to figure a mysqli DB connection in PHP. The problem is everytime I try to fetch the result, literally thousands of queries are executed, and MySQL server and/or browser dies.
Here is the code I use:
$resultQuery = $this->db->prepare($query_id);
var_dump($this->db);
var_dump($resultQuery);
$resultQuery->execute();
//$result = $resultQuery->dbStatement->fetch();
$resultQuery->close();
return $result;
If I uncomment the row with the fetch method, everything goes nuts...
Here is the result of var_dumb's used in the code above:
query:
string(69) " SELECT userid, fname, lname FROM users WHERE finished=0 "
db object:
object(mysqli)#2 (17) {
["affected_rows"]=>
int(-1)
["client_info"]=>
string(6) "5.1.49"
["client_version"]=>
int(50149)
["connect_errno"]=>
int(0)
["connect_error"]=>
NULL
["errno"]=>
int(0)
["error"]=>
string(0) ""
["field_count"]=>
int(0)
["host_info"]=>
string(25) "Localhost via UNIX socket"
["info"]=>
NULL
["insert_id"]=>
int(0)
["server_info"]=>
string(17) "5.1.66-0+squeeze1"
["server_version"]=>
int(50166)
["sqlstate"]=>
string(5) "00000"
["protocol_version"]=>
int(10)
["thread_id"]=>
int(2220)
["warning_count"]=>
int(0)
}
response before fetch():
object(mysqli_stmt)#47 (9) {
["affected_rows"]=>
int(0)
["insert_id"]=>
int(0)
["num_rows"]=>
int(0)
["param_count"]=>
int(0)
["field_count"]=>
int(3)
["errno"]=>
int(0)
["error"]=>
string(0) ""
["sqlstate"]=>
string(5) "00000"
["id"]=>
int(1)
}
Here is how I connect to my DB:
if ($this->persistency)
{
$this->db = new mysqli("p:" . $this->server, $this->user, $this->password);
}
else
{
$this->db = new mysqli($this->server, $this->user, $this->password);
}
$this->db->query("SET CHARACTER SET utf8") or die("Error during character set initialization | " . mysql_error());
$this->db->query("SET NAMES 'utf8'") or die("Error during character set names initialization | " . mysql_error());
if (!$this->db->connect_error)
{
if ($database != "")
{
$this->dbname = $database;
$dbselect = $this->db->select_db($this->dbname);
if (!$dbselect)
{
$this->db->close($this->db);
$this->dbError = "Error choosing database!";
}
else
{
$this->dbResults = new mysqli_result();
$this->dbStatement = new mysqli_stmt();
return $this->dbError = false;
}
}
}
else
{
return $this->dbError = $this->db->connect_error;
}
It seems like mysqli can't decide when to stop sending queries to be fetched...
What am I doing wrong? Can someone help me?
Are you binding your results to a var? You are using mysqli::prepare but I don't see the result of the select binded to any variables:
http://php.net/manual/en/mysqli-stmt.bind-result.php
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'];
}