mysqli array does not print values properly - php

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.

Related

SQL connection dies after one call

I have a custom class that takes a sql connection as a parameter. I use that to populate the class, and then I'm trying to use it again to modify the results on screen. But after the first use, I can't use it anymore.
connection.php:
$conn = new mysqli('localhost', 'root', '', 'loveConnections');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
personalityProfile.php (front end)
if (!isset($_SESSION['interests'])) {
$interests = new Interests($conn, $_SESSION['id']);
$_SESSION['interests'] = $interests;
} else {
$interests = $_SESSION['interests'];
}
interestsObject.php
class Interests {
// properties
public $conn;
public $id;
public $interestsArray = [];
public function __construct($conn, $memberId = null, $intArray = [
'basketball' => false,
'bowling' => false,
'movies' => false,
]) {
$this->conn = $conn;
$this->id = $memberId;
$this->interestsArray = $intArray;
$this->popArraySql();
}
public function popArraySql() {
$memInterests = [];
$sql = "SELECT i.interest
FROM memberInfo m
Join MemberInterestLink mi on (mi.memberID_FK = m.memberID_PK)
Join interests i on (mi.interestID_FK = i.interestID_PK)
WHERE memberID_PK = $this->id";
$result = $this->conn->query($sql);
$this->conn works perfectly here
foreach ($result as $row) {
array_push($memInterests, $row['interest']);
}
foreach ($this->interestsArray as $key => $value) {
for ($i=0; $i<sizeof($memInterests); $i++) {
if ($memInterests[$i] === $key) {
$this->interestsArray[$key] = true;
}
}
}
}
public function insertUpdateQuery() {
var_dump($this->conn);
foreach ($this->interestsArray as $key => $val) {
echo $key . "<br>";
$select = "SELECT interestID_PK from interests where interest = '" . $key . "'";
echo $select;
$result = $this->conn->query($select);
when I try and use it later though, I get a Warning: mysqli::query(): Couldn't fetch mysqli. Additionally, if I try and var_dump it, I get Warning: var_dump(): Property access is not allowed yet
var_dump($result);
if ($val === true) {
$insert = "INSERT INTO MemberInterestLink (memberID_FK, interestID_FK) VALUES ($this->id, $interestKey)";
$this->conn->query($insert);
} else {
$delete = "DELETE FROM MemberInterestLink WHERE interestID_FK = $interestKey";
$this->conn->query($delete);
}
}
}
}
I never close the connection, which is what most of the related answers suggested the cause may be. It's like my $conn variable just stops working after the first use.

PDO Results to array

I moved over from plain MYSQL to PDO MYSQL and started using prepared statements. With my old system I was able to query the database and store the information in a array. I would then use usort to sort the table by money amount.
Since I've moved to PDO I'm having trouble using the array I get out of it. My origional code is as follows:
$sql = "SELECT name, item, cash, props FROM Donators";
$result = $conn->query($sql);
$result_array = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$result_array[] = $row;
//var_dump($result_array);
}
} else {
echo "You have yet to join our servers!";
}
$conn->close();
function custom_sort($a,$b) {
return $a['cash']<$b['cash'];
}
usort($result_array, "custom_sort");
This results in the table being sorted by the column 'cash'. The code below is from my PDO code.
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT name, item, cash, props FROM Donators");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$result_array = array();
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
$result_array[$k] = $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
function custom_sort($a,$b) {
return $a['cash']<$b['cash'];
}
//print_r($result_array);
usort($result_array, "custom_sort");
$length = count($result_array);
usort will cause this error:
Warning: Illegal string offset 'cash'
Printing the array $result_array shows
Array ( [name] => Жэка90 [item] => none [cash] => 1000 [props] => 0 )
I use the following code:
// In case an error occured during statement execution, throw an exception
if (!$stmt->execute()) {
// Error handling with $stmt->errorInfo()
}
// Fetch all results
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
It doesn't need a foreach loop to process the data afterwards.
Changing the for loop to
foreach($stmt->fetchAll() as $k=>$v) {
Fixed this.

PHP Rest Web Service Response

I am new to writing web services and I cannot seem to figure this out! I have a simple php restful service that returns a json response, but I don't have any keys in the response (I don't know if that's the right term) What I get is something like this.
(
(
"name",
qty,
"image",
"price",
"date"
)
I am positive I am doing something wrong here.
Here is my service:
<?php
header('Content-type: application/json');
class InventoryAPI {
private $db;
function __construct() {
$this->db = new mysqli('localhost', 'user', 'pass', 'dbname');
$this->db->autocommit(FALSE);
}
function __destruct() {
$this->db->close();
}
function checkInv() {
$query = "SELECT model, sku, quantity, stock_status_id, image, price, date_available FROM table_name";
$result = $this->db->query($query);
$rows = array();
$i = 0;
while($row = $result->fetch_row())
{
$rows[] = $row;
$i++;
}
$result->close();
$this->db->close();
echo json_encode($rows);
}
}
$api = new InventoryAPI;
$api->checkInv();
?>
I'm assuming you will want to use fetch_assoc() instead of fetch_row(). fetch_assoc() will return an array with keys the same name as the columns. fetch_row() will return an enumerated array based on the column position. For example: model is 0, sku is 1.
You can always test this out by printing out the array.
while($row = $result->fetch_row())
{
print_r($row);
}

class: mysqli_fetch_object

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;
}

PHP & PDO: Can connect to DB; can't seem to query

It appears I can connect to my database using PDO, but can't execute any queries with it. Example:
private function connect() {
try {
$link = new PDO("mysql:host=$this->sHost;dbname=$this->sName", $this->sUser, $this->sPass);
}
catch (PDOException $e) {
die ($e);
}
print_r($link);
$result = $link->query("select * from mt3_users");
var_dump($result);
$row = $result->fetch($result);
die("Your id is: ".$row["id"]);
//$link = mysql_connect($this->sHost, $this->sUser, $this->sPass);
if (!$link) {
echo "Failed to connect to $this->sHost!";
return false;
}
return $link;
}
This returns the following:
PDO Object ( ) bool(false)
Fatal error: Call to a member function fetch() on a non-object in Database.php on line 32
So basically, $link is coming back as a PDO object (I changed my username and password to see if an exception was caught; it was) and PDOConnection::Query is returning null for some reason. This is my first time dealing with PDOs -- am I doing something funny?
Most likely the query fails, are you sure of the name of the table mt3_users and that you have selected the right database? That error message shows that $result is not an object and that's due to an error in the query.
Also:
$row = $result->fetch($result);
should be
$row = $result->fetch();
unless you want to specify options to fetch(), but you don't pass the object as argument.
Array ( [0] => 00000 [1] => 1046 [2] => No database selected ) Array ( )
Nevermind, I guess. It turns out that while migrating from using regular MySQL functions, I wasn't setting $this->sName ($this->sName was null. I'm half surprised it didn't throw an exception. Only half, though)
Fixed.
But thank you guys for the answers :)
can you give this a try
private function connect() {
try {
$link = new PDO("mysql:host=$this->sHost;dbname=$this->sName", $this->sUser, $this->sPass);
return $link ;
}
catch (PDOException $e) {
die ($e);
}
}
$pdolink = $this->connect();
$rows = $pdolink->query("select * from mt3_users");
foreach($rows as $row ){
echo("Your id is: ".$row["id"]);
}
and if you need to stick with fetchAll function
private function connect() {
try {
$link = new PDO("mysql:host=$this->sHost;dbname=$this->sName", $this->sUser, $this->sPass);
return $link ;
}
catch (PDOException $e) {
die ($e);
}
}
$pdolink = $this->connect();
$q = $pdolink->prepare("select * from mt3_users");
$q->exectue();
$rows = $q->fetchAll();
var_dump($rows);
foreach($rows as $row ){
echo("Your id is: ".$row["id"]);
}
In order to get the error in your query:
$result = $link->query(...);
if($result===FALSE){
print_r( $link->errorInfo);
exit();
}
// the correct way to fetch one row
$link->fetch(PDO::FETCH_ASSOC); // or whatever way you want to fetch data

Categories