I followed the php.net's doc to get certain object's result from fetch_object,
$mysqli = new mysqli("localhost", "root", "tklau", "xx_2011");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "
SELECT cnt_id, cnt_email1
FROM root_contacts_cfm
ORDER BY cnt_id DESC
";
if ($result = $mysqli->query($query)) {
/* fetch object array */
while ($obj = $result->fetch_object()) {
print_r($obj);
//echo $obj->cnt_email1;
}
/* free result set */
$result->close();
}
/* close connection */
$mysqli->close();
I will get this,
stdClass Object
(
[cnt_id] => 2
[cnt_email1] => rocco#xx.net
)
stdClass Object
(
[cnt_id] => 1
[cnt_email1] => lola#xx.co.uk
)
But I want to make this code into a class instead,
#connects the database and handling the result
class __database {
protected $connection = null;
protected $error = null;
#make a connection
public function __construct($hostname,$username,$password,$database)
{
$this -> connection = new mysqli($hostname,$username,$password,$database);
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
}
public function fetch_object($query)
{
$result = $this -> connection -> query($query);
if($result)
{
while ($row = $result->fetch_object()) {
return $row;
}
}
else
{
$this -> error = $this -> connection -> error;
return false;
}
}
#display error
public function get_error()
{
return $this -> error;
}
#closes the database connection when object is destroyed.
public function __destruct()
{
$this -> connection -> close();
}
}
so, I will call the class function like this,
$sql = "
SELECT cnt_id, cnt_email1
FROM root_contacts_cfm
ORDER BY cnt_id DESC
";
$items = $connection -> fetch_object($sql);
print_r($items);
but I get only one row from the result which is not correct,
stdClass Object
(
[cnt_id] => 2
[cnt_email1] => lau#xx.net
)
it must be something wrong in my class function of fetch_object - how can I fix it? please advise...
You function is returning when it finds the first result.
return $row;
You should store each row in an array and then return the array.
if($result){
$function_result = array();
$i = 0;
while($row = $result->fetch_object()){
$function_result[$i] = $row;
$i++;
}
return $function_result;
}
Related
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
I'm a class execute statement mysql and I don't know how to print a return array variable
class Db {
// The database connection
protected static $connection;
public function connect() {
// Try and connect to the database
if(!isset(self::$connection)) {
self::$connection = new mysqli('localhost','root','123456','dbGanaderia');
}
// 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 select($query) {
$rows = array();
$result = $this -> query($query);
if($result === false) {
return false;
}
while ($row = $result -> fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
}
This when i call the method to execute select statement the rows return an array, but i don't kno how to print... If i do this printr($rows) I verefy that the statement its returning from database
$db = new Db();
$rows = $db -> select("SELECT *FROM user");
if ($rows == true) {
echo "<table border = '1'> \n";
echo "<tr><td>name</td></tr> \n";
while($row = mysql_fetch_array($rows)) {
echo "<tr><td>".$row['1']."</td></tr> \n";
}
echo "</table> \n";
} else {
echo "¡ No data !";
}
Where am I wrong?
You are mixing mysql_ functions with mysqli_ functions
Change your fetch to
$r = mysqli_fetch_array()
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;
}
I am having a small issue with the following
public function getSiteName() {
$query = "SELECT name FROM siteinfo";
$result = $this->con->query($query);
$row = $result->fetch_array(MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["name"]);
}
I do NOT get an error when connecting to the database however I get the following
Fatal error: Call to a member function fetch_array() on a non-object in /Users/russellharrower/Sites/evocca/etrading/system/core.php on line 15
I am wondering why would it not work? I used http://php.net/manual/en/mysqli-result.fetch-array.php
The engine am using is InnoDB
You can always try something like this:
Taken from: http://php.net/manual/en/mysqli-result.fetch-assoc.php
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
?>
So After an hour of debugging I had to do the following.
For my project I am using a config.php as where I put all my Database connection defines.
config.php
<?php
define('DBServer','localhost'); // e.g 'localhost' or '192.168.1.100'
define('DBUser','root');
define('DBPass','PASSWORD');
define('DBName','ET5');
?>
core.php
<?php
class sys
{
protected $con;
public function __construct($con) {
$this->con = $con;
}
public function getSiteName() {
$query = "SELECT name FROM siteinfo";
$result = $this->con->query($query);
$res = array();
while ($row = $result->fetch_array()) {
$res[] = $row['name'];
}
return $res;
}
}
?>
Index.php
<?php
require_once("system/config.php");
require_once("system/core.php");
global $con ;
$con = new mysqli(DBServer, DBUser, DBPass, DBName);
if ($con->connect_errno)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sys = new sys($con);
$result = $sys->getSiteName();
print_r($result);
?>
Hi I have the following code below in a php file
global $server, $mysqlusername, $mysqlpassword, $db;
$conn = new mysqli($server, $mysqlusername, $mysqlpassword, $db);
function getCategories() {
global $conn;
$categories = array();
$sql = "SELECT categoryName FROM reportcategorys";
$maincat = $conn->query($sql);
while($row = $maincat->fetch_array(MYSQLI_ASSOC)) {
// do something with the $row
array_push($categories, $row);
}
$sql1 = "SELECT * FROM reportsubcategorys";
$subcats = $conn->query($sql1);
// Loop through sub categories and append to parent array
while($row = $subcats->fetch_array(MYSQLI_ASSOC)) {
$parent = $row['categoryName'];
$name = $row['subCategoryName'];
// Append subcategory name as child to the parent category
for ($i=0; $i<count($categories); $i++) {
if ($categories[$i]['categoryName'] == $parent) {
array_push($categories[$i], $name);
}
}
}
//print_r($categories);
return $categories;
}
It is giving me an error message saying
"Fatal error: Call to a member function fetch_array() on a non-object in"
Any idea what may be causing this?
Thanks
It is likely that your query has not executed properly.
mysqli->query() will return a boolean value FALSE if the query has not been executed properly, else it will return a mysqli_result object. So after every query, before calling fetch_array() method, check the result of the query. Something like this.
$maincat = $conn->query($sql) or die($conn->error);
or
$maincat = $conn->query($sql);
if(!$maincat){
echo $conn->error;
}
Also, when you established your connection with the database, check if the connection was error-free.
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
Are you using fetch_array for any reason in particular?
Try it like this one...
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* verificar la conexión */
if (mysqli_connect_errno()) {
printf("Conexión fallida: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";
if ($result = $mysqli->query($query)) {
/* obtener array asociativo */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
/* liberar el resultset */
$result->free();
}
/* cerrar la conexión */
$mysqli->close();
?>
I'm having trouble printing out the values from my MySQLi query. Here is the db connection class that I am using.
class db
{
public function __construct()
{
$this->mysqli = new mysqli('localhost', 'root','', 'database');
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
}
public function Query($SQL)
{
$this->SQL = $this->mysqli->real_escape_string($SQL);
$this->Result = $this->mysqli->query($SQL);
if ($this->Result == true)
return true;
else
die('Problem with Query: ' . $this->SQL);
}
public function Get($field = NULL)
{
if ($field == NULL)
{
$data = array();
while ($row = $this->Result->fetch_assoc())
{
$data[] = $row;
}
}
else
{
$row = $this->Result->fetch_assoc();
$data = $row[$field];
}
$this->Result->close();
return $data;
}
public function __destruct()
{
$this->mysqli->close();
}
}
Running a query
$db = new db;
$db->Query("SELECT * FROM tblclients WHERE clientid = $this->id");
$result = $db->Get();
echo $result['clientid'];
I'm getting error
PHP Notice: Undefined index: clientid
However I know the values are getting passed to the $results array when I run
print_r ($result);
I get this returned
Array ( [0] => Array ( [clientid] => 2 [firstname] => John [lastname] => Doe [dob] => 1962-05-08))
For what its worth, if I try echo $db->Get('firstname'); everything works. Been banging my head against the wall for a while now, any help appreciated.
As you can see you have an array inside another array. To get what you need you need to go like this:
$result[0]['clientid'];
So what we're doing here is you are first calling the $result variable which contains an array with an index of [0], then this array contains the column names from your query (ex: ['clientid']).
So you basically have to go deeper than $result['clientid'] to get your data from the database by firstly calling the array that contains those keys from the database.
To un-nest that array, do something like:
$result = $db->Get();
$normal_result = 0;
foreach ($result as $value)
{
$normal_result = $value;
}
You can use this inside your method, so you'll get normal results only in the future.