$mysqli->fetch_object($result) not working - php

I am learning mysqli.
I am trying to fetch data from a table "tbllogin".
//DATABASE CONNECTION
$hostname="p:localhost";
$database="dbLogin";
$username="user1";
$password="pwd1";
$mysqli = new mysqli($hostname, $username, $password,$database);
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
// Create Query
$query = "SELECT * FROM tbllogin";
// Escape Query
$query = $mysqli->real_escape_string($query);
echo $query;
// Execute Query
if($result = $mysqli->query($query)){
print_r($result);
while($row = $mysqli->fetch_object($result)){
echo $row->column;
}
//Free result set
$result->close();
}
?>
But $mysqli->fetch_object($result) is not working. The if statement containing $mysqli->fetch_object($result) does not execute. I cannot identify if there is any error.
Please help.
Also, suggest whether mysqli procedural form is better or object-oriented form?
Thanks in advance.

Shouldn't that be $result->fetch_object() ?
http://php.net/manual/en/mysqli-result.fetch-object.php
From Example 1:
if ($result = $mysqli->query($query)) {
/* fetch object array */
while ($obj = $result->fetch_object()) {
printf ("%s (%s)\n", $obj->Name, $obj->CountryCode);
}
According to the answers on this stackoverflow page, there is not much of a difference between the two.

Try this:
if($result = $mysqli->query($query)){
print_r($result);
while($row = $result->fetch_object($result)){
//do something
}
}
You need to chain the commands together.

Related

Why do i get more results from my mysql query in php then what i ask for?

I am getting return values that do not exist in my current database. Even if i change my query the return array stays the same but missing values. How can this be what did i do wrong?
My MYSQL server version is 10.0.22 and this server gives me the correct result.
So the issue must be in PHP.
My code:
$select_query = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > \"[given time]\"";
$result = mysql_query($select_query, $link_identifier);
var_dump($result);
Result:
array(1) {
[1]=> array(9) {
["UID"]=> string(1) "1"
["CreationTimestamp"]=> NULL
["UpdateTimestamp"]=> NULL
["ProcessState"]=> NULL
}
}
Solution:
I have found this code somewhere in my program. The program used the same name ass mine. This function turns the MYSQL result into a array. This happens between the result view and my script. This was done to make the result readable.
parent::processUpdatedAfter($date);
Function:
public function processUpdatedAfter($date)
{
$result = parent::processUpdatedAfter($date);
$array = Array();
if($result != false)
{
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$array[$row["UID"]]["UID"] = $row["UID"];
$array[$row["UID"]]["CreationTimestamp"] = $row["CreationTimestamp"];
$array[$row["UID"]]["UpdateTimestamp"] = $row["UpdateTimestamp"];
$array[$row["UID"]]["ProcessState"] = $row["ProcessState"];
}
return $array;
}
return false;
}
I edited this and my script works fine now thanks for all the help.
Note that, var_dump($result); will only return the resource not data.
You need to mysql_fetch_* for getting records.
Example with MYSQLi Object Oriented:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > \"[given time]\"";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row['UID'];
}
}
else
{
echo "No record found";
}
$conn->close();
?>
Side Note: i suggest you to use mysqli_* or PDO because mysql_* is deprecated and closed in PHP 7.
You are var_dumping a database resource handle and not the data you queried
You must use some sort of fetching process to actually retrieve that data generated by your query.
$ts = '2016-09-20 08:56:43';
$select_query = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > '$ts'";
$result = mysql_query($select_query, $link_identifier);
// did the query work or is there an error in it
if ( !$result ) {
// query failed, better look at the error message
echo mysql_error($link_identifier);
exit;
}
// test we have some results
echo 'Query Produced ' . mysql_num_rows($result) . '<br>';
// in a while loop if more than one row might be returned
while( $row = mysql_fetch_assoc($result) ) {
echo $row['UID'] . '<br>';
}
However I have to mention Every time you use the mysql_
database extension in new code
a Kitten is strangled somewhere in the world it is deprecated and has been for years and is gone for ever in PHP7.
If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions.
Start here
$select_query = "SELECT `UID` FROM `process_state ` WHERE `UpdateTimestamp` > \"[given time]\" ORDER BY UID DESC ";
$result = mysql_query($select_query, $link_identifier);
var_dump($result);
Try this hope it will works

Convert SQL results into PHP array

I'm fairly new to PHP and I've been looking around and can't seem to find the specific answer I'm looking for.
I want to make a SQL query, such as this:
$result = mysqli_query($connection, $command)
if (!$result) { die("Query Failed."); }
// Create my array here ... I'm thinking of maybe having to
// make a class that can hold everything I need, but I dunno
while($row = mysqli_fetch_array($result))
{
// Put the row into an array or class here...
}
mysqli_close($connection);
// return my array or class
Basically I want to take the entire contents of the result and create an array that I can access in a similar fashion as the row. For example, if I have a field called 'uid' I want to be able to get that via myData['uid']. I guess since there could be several rows, maybe something more like myData[0]['uid'], myData[1]['uid'], etc.
Any help would be appreciated.
You can do:
$rows = [];
while($row = mysqli_fetch_array($result))
{
$rows[] = $row;
}
You might try to use mysqli_result::fetch_all() for arrays:
$result = mysqli_query($connection, $command)
if (!$result) { die("Query Failed."); }
$array = $result->fetch_all();
$result->free();
mysqli_close($connection);
NOTE: This works with MySQLND only.
For class, you might try to use something like this:
$result = mysqli_query($connection, $command)
if (!$result) { die("Query Failed."); }
while($model = $result->fetch_assoc()){
// Assuming ModelClass is declared
// And have method push() to append rows.
ModelClass::push($model);
}
$result->free();
mysqli_close($connection);
OR this:
// Base Model - abstract model class.
class ModelClass extends BaseModel {
// constructor
public function __construct(mysqli &$dbms){
// $this->dbms is MySQLi connection instance.
$this->dbms = &$dbms;
// $this->models is buffer for resultset.
$this->models = array();
}
// destructor
public function __destruct(){
unset($this->dbms, $this->models);
}
public function read(){
$result = $this->dbms->query($command);
if($this->dbms->errno){
throw new Exception($this->dbms->error, $this->dbms->errno);
}
$this->models = $result->fetch_all();
$result->free();
}
}
//object oriented style mysqli
//connect to your db
$mysqli = new mysqli("host", "user", "password", "dbname");
$result = $mysqli->query("SELECT * FROM `table`");
//use mysqli->affected_rows
for ($x = 1; $x <= $mysqli->affected_rows; $x++) {
$rows[] = $result->fetch_assoc();
}
//this will return a nested array
echo "<pre>";
print_r($rows);
echo "</pre>";
edit this and put it on a class and just call it anytime you're going to make a query with your database.
fetch_array: https://www.php.net/manual/en/mysqli-result.fetch-array.php
$result = $mysqli_connection->query($sql);
$row = $result->fetch_array(MYSQLI_ASSOC);
print_r($row);

how to acess my database elements using the for loop?

I'm learning PHP and I'm well versed with Java and C. I was given a practice assignment to create a shopping project. I need to pull out the products from my database. I'm using the product id to do this. I thought of using for loop but I can't access the prod_id from the database as a condition to check! Can anybody help me?! I have done all the form handling but I need to output the products. This is the for-loop I am using. Please let me know if I have to add any more info. Thanks in advance :)
for($i=1; $i + 1 < prod_id; $i++)
{
$query = "SELECT * FROM products where prod_id=$i";
}
I would suggest that you use PDO. This method will secure all your SQLand will keep all your connections closed and intact.
Here is an example
EXAMPLE.
This is your dbc class (dbc.php)
<?php
class dbc {
public $dbserver = 'server';
public $dbusername = 'user';
public $dbpassword = 'pass';
public $dbname = 'db';
function openDb() {
try {
$db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
} catch (PDOException $e) {
die("error, please try again");
}
return $db;
}
function getproduct($id) {
//prepared query to prevent SQL injections
$query = "SELECT * FROM products where prod_id=?";
$stmt = $this->openDb()->prepare($query);
$stmt->bindValue(1, $id, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
?>
your PHP page:
<?php
require "dbc.php";
for($i=1; $i+1<prod_id; $i++)
{
$getList = $db->getproduct($i);
//for each loop will be useful Only if there are more than one records (FYI)
foreach ($getList as $key=> $row) {
echo $row['columnName'] .' key: '. $key;
}
}
First of all, you should use database access drivers to connect to your database.
Your query should not be passed to cycle. It is very rare situation, when such approach is needed. Better to use WHERE condition clause properly.
To get all rows from products table you may just ommit WHERE clause. Consider reading of manual at http://dev.mysql.com/doc.
The statement selects all rows if there is no WHERE clause.
Following example is for MySQLi driver.
// connection to MySQL:
// replace host, login, password, database with real values.
$dbms = mysqli_connect('host', 'login', 'password', 'database');
// if not connected then exit:
if($dbms->connect_errno)exit($dbms->connect_error);
$sql = "SELECT * FROM products";
// executing query:
$result = $dbms->query($sql);
// if query failed then exit:
if($dbms->errno)exit($dbms->error);
// for each result row as $product:
while($product = $row->fetch_assoc()){
// output:
var_dump($product); // replace it with requied template
}
// free result memory:
$result->free();
// close dbms connection:
$dbms->close();
for($i=1;$i+1<prod_id;$i++) {
$query = "SELECT * FROM products where prod_id=$i";
$result = mysqli_query($query, $con);
$con is the Database connection details
you can use wile loop to loop thru each rows
while ($row = mysqli_fetch_array($result))
{
......
}
}
Hope this might work as per your need..
for($i=1; $i+1<prod_id; $i++) {
$query = "SELECT * FROM products where prod_id = $i";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
print_r($row);
}
}
I think you want all records from your table, if this is the requirement you can easily do it
$query = mysql_query("SELECT * FROM products"); // where condition is optional
while($row=mysql_fetch_array($query)){
print_r($row);
echo '<br>';
}
This will print an associative array for each row, you can access each field like
echo $row['prod_id'];

Basic mysql query giving no results

I got a simple query looking like this:
$con = mysqli_connect("host","username","password","default_database");
if(mysqli_connect_errno($con))
{
mysqli_connect_error();
}
else
{
$query = "SELECT * FROM `users_t`";
$result = mysqli_query($query) or die (mysql_error());
while($row = mysqli_fetch_assoc($result))
{
echo $row['email'];
}
}
Running this query gives me absolutely nothing. No errors but no result at the same time. I can't figure out whats wrong, help me please.
It looks like there may be a few things going on here:
According to the mysqli_connect_errno() Documentation, you should be checking for !$con rather than mysqli_connect_errno($con) in your if statement.
When a connection error is encountered, you're calling the error function but not printing it.
According to the mysqli_query() documentation, the first argument should be the database connection, the second being the query itself.
When a query errors out, you're calling mysql_error() when you should be calling mysqli_error(), passing it the connection. Again, according to documentation
Try this out and see if this resolves your problems:
<?php
$con = mysqli_connect("host","username","password","default_database");
if(!$con) {
print mysqli_connect_error();
} else {
$query = "SELECT * FROM `users_t`";
$result = mysqli_query($con, $query) or die (mysqli_error($con));
while($row = mysqli_fetch_assoc($result)) {
echo $row['email'];
}
}
$result = mysqli_query($query) or die (mysql_error());
Needs a mysqli resource link and also its not mysql_error()
if ($result = mysqli_query($con,$query))
{
while($row = mysqli_fetch_assoc($result))
{
echo $row['email'];
}
}
PHP is case-sensitive, so there is a very good change that your column in the database is actually named Email and then you have no result when you check $row['email'], because the E has to be upper case.
What you can do is make sure you use the right case in PHP, or select just the fields you want. MYSQL isn't case-senstive, so if you do the following it will work.
Also a good way to check if you have the right case: use var_dump($row) (I've added it to the code just to show you)
$con = mysqli_connect("host","username","password","default_database");
if(mysqli_connect_errno($con))
{
mysqli_connect_error();
}
else
{
$query = "SELECT email FROM `users_t`";
$result = mysqli_query($query) or die (mysql_error());
while($row = mysqli_fetch_assoc($result))
{
echo $row['email'];
var_dump($row);
}
}

How to get a list of databases?

I was wondering if there's a way in PHP to list all available databases by usage of mysqli. The following works smooth in MySQL (see php docs):
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$db_list = mysql_list_dbs($link);
while ($row = mysql_fetch_object($db_list)) {
echo $row->Database . "\n";
}
Can I Change:
$db_list = mysql_list_dbs($link); // mysql
Into something like:
$db_list = mysqli_list_dbs($link); // mysqli
If this is not working, would it be possible to convert a created mysqli connection into a regular mysql and continue fetching/querying on the new converted connection?
It doesn't appear as though there's a function available to do this, but you can execute a show databases; query and the rows returned will be the databases available.
EXAMPLE:
Replace this:
$db_list = mysql_list_dbs($link); //mysql
With this:
$db_list = mysqli_query($link, "SHOW DATABASES"); //mysqli
I realize this is an old thread but, searching the 'net still doesn't seem to help. Here's my solution;
$sql="SHOW DATABASES";
$link = mysqli_connect($dbhost,$dbuser,$dbpass) or die ('Error connecting to mysql: ' . mysqli_error($link).'\r\n');
if (!($result=mysqli_query($link,$sql))) {
printf("Error: %s\n", mysqli_error($link));
}
while( $row = mysqli_fetch_row( $result ) ){
if (($row[0]!="information_schema") && ($row[0]!="mysql")) {
echo $row[0]."\r\n";
}
}
Similar to Rick's answer, but this is the way to do it if you prefer to use mysqli in object-orientated fashion:
$mysqli = ... // This object is my equivalent of Rick's $link object.
$sql = "SHOW DATABASES";
$result = $mysqli->query($sql);
if ($result === false) {
throw new Exception("Could not execute query: " . $mysqli->error);
}
$db_names = array();
while($row = $result->fetch_array(MYSQLI_NUM)) { // for each row of the resultset
$db_names[] = $row[0]; // Add db name to $db_names array
}
echo "Database names: " . PHP_EOL . print_r($db_names, TRUE); // display array
Here is a complete and extended solution for the answer, there are some databases that you do not need to read because those databases are system databases and we do not want them to appear on our result set, these system databases differ by the setup you have in your SQL so this solution will help in any kind of situations.
first you have to make database connection in OOP
//error reporting Procedural way
//mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//error reporting OOP way
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL & MYSQLI_REPORT_STRICT;
$conn = new mysqli("localhost","root","kasun12345");
using Index array of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($row = $result->fetch_array(MYSQLI_NUM)){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if($row[0] == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'.$row[0];
}
}
same with Assoc array of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if($row["Database"] == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'.$row["Database"];
}
}
same using object of search result
$dbtoSkip = array("information_schema","mysql","performance_schema","sys");
$result = $conn->query("show databases");
while($obj = $result->fetch_object()){
$print = true;
foreach($dbtoSkip as $key=>$vlue){
if( $obj->Database == $vlue) {
$print=false;
unset($dbtoSkip[$key]);
}
}
if($print){
echo '<br/>'. $obj->Database;
}
}

Categories