PHP can anyone explain this var dump - php

This var dump is returned when results are found, why would it be throwing an error if it is finding results.
object(DB)#3 (5) { ["_pdo":"DB":private]=> object(PDO)#4 (0) { } ["_query":"DB":private]=> object(PDOStatement)#6 (1) { ["queryString"]=> string(80) "SELECT * FROM `activity` WHERE `name` = ? AND `act_date` = ? AND `time_from` = ?" } ["_error":"DB":private]=> bool(false) ["_results":"DB":private]=> array(3) { [0]=> object(stdClass)#7 (7) { ["activity_id"]=> string(1) "6" ["name"]=> string(7) "Archery" ["act_date"]=> string(10) "12/01/2015" ["time_from"]=> string(5) "10.00" ["time_to"]=> string(5) "11.00" ["num_people"]=> string(2) "12" ["booking_id"]=> string(1) "1" } [1]=> object(stdClass)#8 (7) { ["activity_id"]=> string(2) "13" ["name"]=> string(7) "Archery" ["act_date"]=> string(10) "12/01/2015" ["time_from"]=> string(5) "10.00" ["time_to"]=> string(5) "11.00" ["num_people"]=> string(2) "10" ["booking_id"]=> string(1) "1" } [2]=> object(stdClass)#9 (7) { ["activity_id"]=> string(2) "56" ["name"]=> string(7) "Archery" ["act_date"]=> string(10) "12/01/2015" ["time_from"]=> string(5) "10.00" ["time_to"]=> string(5) "11.00" ["num_people"]=> string(2) "10" ["booking_id"]=> string(1) "2" } } ["_count":"DB":private]=> int(3) }
This var dump is returned when the query cannot find any results:
object(DB)#3 (5) { ["_pdo":"DB":private]=> object(PDO)#4 (0) { } ["_query":"DB":private]=> object(PDOStatement)#6 (1) { ["queryString"]=> string(80) "SELECT * FROM `activity` WHERE `name` = ? AND `act_date` = ? AND `time_from` = ?" } ["_error":"DB":private]=> bool(false) ["_results":"DB":private]=> array(0) { } ["_count":"DB":private]=> int(0) }
The query is called:
!$activity->checkDateTimeAvailability($act_name, $act_date, $time_from)
// Method to check if the activity is available at the requested date and time.
public function checkDateTimeAvailability($act_name, $act_date, $time_from) {
$fields = array($act_name, $act_date, $time_from);
$result = $this->_db->query("SELECT * FROM `activity` WHERE `name` = ? AND `act_date` = ?
AND `time_from` = ?", $fields);
var_dump($result);
if(!empty($result)){
echo "query successful";
return true;
} else {
return false;
}
}
The DB Query Method:
// Generic query method.
public function query($sql, $params = array()) {
// reset to ensure an error from a previous query is not returned.
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)) {
$x = 1;
if(count($params)) {
foreach($params as $param) {
$this->_query->bindValue($x, $param);
$x++;
}
}
if($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error = true;
echo 'Error: ', $this->_error;
}
}
return $this;
}

Looks like this code works pretty fine.
First you save link to the DB object to $result variable, then you use var_dump and there should be a message "query successful" and checkDateTimeAvailability function will always return true to the calling side.
Probably, you should get query result from DB object or selected rows count. !empty($result) will always be true, because $result - is object, not array of data, fetched from query.
EDITED
You have serveral opportunities:
First
Look up DB class, where query method described and look for methods like Count() or GetResult(). If such methods exists - use them.
if ($result->count() > 0){
echo "query successful";
return true;
} else {
return false;
}
Second
If there is no such methods in DB class, and this is not some library class you can add your own realisation of Count method
public function count() {
return $this->_count;
}
It would be much easier, if i could see all DB class.

Related

please i just want to know how can i get the first value from the array list as id only

controller
$data['userInfo'] = $this->user_model->get15();
User_model
function get15()
{
$this->db->select('userId');
$this->db->from('tbl_security');
$this->db->order_by('userId','ASC');
$this->db->where('status', 0);
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
the array i get
array(1) { [0]=> array(1) { [0]=> array(1) { ["userInfo"]=> array(7) { [0]=> array(1) { ["userId"]=> string(2) "15" } [1]=> array(1) { ["userId"]=> string(2) "17" } [2]=> array(1) { ["userId"]=> string(2) "18" } [3]=> array(1) { ["userId"]=> string(2) "19" } [4]=> array(1) { ["userId"]=> string(3) "178" } [5]=> array(1) { ["userId"]=> string(4) "1444" } [6]=> array(1) { ["userId"]=> string(5) "12778" } } } } }
you can use array_column()
$user_ids = array_column($data[0][0]['userInfo'], 'userId');
print_r($user_ids);
output:
array(15,17,18,19,178,1444,12778);
Simply modify your model like below. This code will give you first array data . it same as code $statement->fetch(PDO::FETCH_OBJ). Write below code and modify it.
function get15()
{
$this->db->select('userId');
$this->db->from('tbl_security');
$this->db->order_by('userId','ASC');
$this->db->where('status', 0);
$query = $this->db->get();
$result = $query->row();
return $result;
}

Unable to iterate an array in a PHP foreach loop

My request PHP file elaborates some Ajax POST data:
POST data
data[0][id]:359
data[0][position]:1
data[1][id]:321
data[1][position]:2
data[2][id]:354
data[2][position]:3
Request.php
if(isset($_POST['data'])) {
if(isset($_SESSION['username']) && isset($_SESSION['password'])) {
$verify = $loggedIn->verify();
if($verify['username']) {
$Profile = new Profile();
$Profile->db = $db;
//Call my function
$messages = $Profile->setOrder($_POST['data']);
}
}
}
Profile.php
function setOrder($post) {
var_dump($post);
foreach($post as $item)
{
return "Area ID ".$item["id"]." and person located ".$item["position"]."<br />";
}
}
My function returns nothing and the dump of $post is as below
array(3) {
[0]=>
array(2) {
["id"]=>
string(3) "359"
["position"]=>
string(1) "1"
}
[1]=>
array(2) {
["id"]=>
string(3) "321"
["position"]=>
string(1) "2"
}
[2]=>
array(2) {
["id"]=>
string(3) "354"
["position"]=>
string(1) "3"
}
}
Inside my function I can dump correctly something like var_dump($post[0]["id"]); so why my foreach loop is empty?
It is because you are using return inside loop. It will terminate the loop after first iteration. You need to do something like this.
$return = null;
foreach($data as $item)
{
$return .= "Area ID ".$item["id"]." and person located ".$item["position"]."<br />";
}
return $return;

How to compare PHP variable to value from PHP array

I am trying to execute an SQL query to pull one column of data from my database into a PHP array, and then search for my session variable in that array. I've printed the contents of my array and it looks like the query is working and is filling the array, but my comparison if (in_array("$session", $result)) is not working correctly.
I know the string my session variable contains is inside the PHP array. But $execute never flips to FALSE. Any idea why?
$confirm = $_GET['name'];
$execute = TRUE;
session_start();
$session = $_SESSION['sessionID'];
$result = array();
try{
$conn = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(substr($session, 0, 2) === 'DS'){
$sql = $conn->prepare("SELECT confirmNum FROM `DSattendance`");
$sql->execute();
$result = $sql->fetchAll();
}
else if (substr($session, 0, 2) === 'BYOD'){
$sql = $conn->prepare("SELECT confirmNum FROM BYODattendance");
$sql->execute();
$result = $sql->fetchAll();
}
}
catch(PDOException $e){echo $sql . "<br>" . $e->getMessage();}
if (in_array("$session", $result)) {
echo "true";
$execute = FALSE;
}
if ($execute == FALSE)
echo "ALREADY REGISTERED";
var_dump($result) yields:
array(10) {
[0]=> array(2) { ["confirmNum"]=> string(11) "adfafafafaa" [0]=> string(11) "adfafafafaa" }
[1]=> array(2) { ["confirmNum"]=> string(11) "adsfafafaff" [0]=> string(11) "adsfafafaff" }
[2]=> array(2) { ["confirmNum"]=> string(11) "asdfafafafa" [0]=> string(11) "asdfafafafa" }
[3]=> array(2) { ["confirmNum"]=> string(11) "christrader" [0]=> string(11) "christrader" }
[4]=> array(2) { ["confirmNum"]=> string(11) "christradfe" [0]=> string(11) "christradfe" }
[5]=> array(2) { ["confirmNum"]=> string(11) "sadfadfafaf" [0]=> string(11) "sadfadfafaf" }
[6]=> array(2) { ["confirmNum"]=> string(11) "sadfsfafaaf" [0]=> string(11) "sadfsfafaaf" }
[7]=> array(2) { ["confirmNum"]=> string(11) "sdfsafsadfa" [0]=> string(11) "sdfsafsadfa" }
[8]=> array(2) { ["confirmNum"]=> string(11) "trraafafafa" [0]=> string(11) "trraafafafa" }
[9]=> array(2) { ["confirmNum"]=> string(11) "wesdfdfasfa" [0]=> string(11) "wesdfdfasfa" } }
The PDO Statement fetchAll is returning a multi-dimensional array of the results found in the database. You need to loop through them first and format a new array that you can use to check your session against.
foreach($result as $value) {
$array[] = $value['confirmNum'];
}
if( in_array($session, $array)) {
// your code here
}
As noted by #mr12086, depending on the version of PHP you are using, you can avoid the foreach loop by using: $result = array_column('confirmNum', $result); instead. However, this does require PHP 5.5.0 or higher.

Recursive traversal of object

I'm having trouble writing a recursive function to traverse this hierarchical structure
object(stdClass)#290 (6) {
["category_id"]=>
int(1)
["parent_id"]=>
int(0)
["name"]=>
string(4) "Root"
["position"]=>
int(0)
["level"]=>
int(0)
["children"]=>
array(2) {
[0]=>
object(stdClass)#571 (7) {
["category_id"]=>
int(2)
["parent_id"]=>
int(1)
["name"]=>
string(18) "Root MySite.com"
["is_active"]=>
int(0)
["position"]=>
int(0)
["level"]=>
int(1)
["children"]=>
array(11) {
[0]=>
object(stdClass)#570 (7) {
["category_id"]=>
int(15)
["parent_id"]=>
int(2)
["name"]=>
string(9) "Widgets"
["is_active"]=>
int(1)
["position"]=>
int(68)
["level"]=>
int(2)
["children"]=>
array(19) {
[0]=>
object(stdClass)#566 (7) {
["category_id"]=>
int(24)
["parent_id"]=>
int(15)
["name"]=>
string(16) "Blue widgets"
["is_active"]=>
int(1)
["position"]=>
int(68)
["level"]=>
int(3)
["children"]=>
array(0) {
}
}
<snip....>
As you can see this nested set can go on forever.. .
What I want to return is something like this
$categories("Root" => array("Root MySite.com" => array("Widgets" => array("Blue Widgets",...))))
[EDIT] : pasting my starting point for my recursive function that will simply "flatten out" an arry or object. I would think i could modify this to make get the data structure I'm looking for but haven't been able to get it quite right.
function array_flatten($array, $return)
{
// `foreach` can also iterate through object properties like this
foreach($array as $key => $value)
{
if(is_object($value))
{
// cast objects as an array
$value = (array) $value;
}
if(is_array($value))
{
$return = array_flatten($value,$return);
}
else
{
if($value)
{
$return[] = $value;
}
}
}
return $return;
}
The question is I can't quite figure out to build the structure I'm looking for recursively, or maybe there is a more elegant php way to do this?
Try this
function run($o) {
$return = array();
foreach ($o->children as $child) {
$return[$child->name] = run($child);
}
return empty($return) ? null : $return;
}
I don't have time to write a working answer, but here's some pseudo code to do it (half PHP, half JS)
This would create a flattened version of the tree by removing the children property of each element in your list.
$flattened = array();
function addElement(&$flattened, $list) {
for ($element in $list) {
$children = $element->children;
delete $element->children;
$flattened[] = $element;
if ($children) {
addElements($flattened, $children)
}
}
}
addElements($flattened, $treeHierarchy);
deep_order object or assoc_array
namespace a_nsp
class object_utils{
static function deep_order($IN, $desc = NULL) { // object or assoc_array
$O = new \stdClass;
$I = (array) $IN;
$keys = array_keys($I);
$desc ? rsort($keys) : asort($keys);
foreach ($keys as $k) {
$v = $I[$k];
//$v = json_decode($I[$k],1) ?: $I[$k]; // force conversion of json_string
if (is_array($v) || is_object($v)) {
$O->$k = self::deep_order($v, $desc);
}
else {
$O->$k=$v;
}
}
return $O; // object
}
}
use like
$ordered_obj = \a_nsp\object_utils::deep_order($orig_obj)

Listing Array Issue

I am calling a webservice and I am getting a complex object back. I need to display variables reg_no, opening_inventory_weight.
RESULT:-
object(stdClass)#12 (3) {
["TxnErrors"]=> object(stdClass)#13 (0) { }
["TxnStatus"]=> bool(true)
["headers"]=> object(stdClass)#14 (1) {
["RPMHeader"]=> array(1) {
[0]=> object(stdClass)#15 (7) {
["opening_inventory_weight"]=> int(1001)
["prepared_by"]=> string(5) "James"
["reg_no"]=> string(7) "5000005"
["reporting_period"]=> string(19) "2010-02-01T00:00:00"
["rsid"]=> int(49) ["status"]=> string(1) "D"
["web_user_id"]=> string(1) "0" } } } }
I am calling it like
$result = call_search_existing_manufacturer();
$rows = array();
foreach ($result->RPMHeader as $data)
{
$rows[] = array(
$data->reg_no,
$data->opening_inventory_weight,
$data->status
);
}
But its not working. Any Idea what am I missing? Thank you in advance
I think it should be
$result = call_search_existing_manufacturer();
$rows = array();
foreach ($result->headers->RPMHeader as $data)
{
$rows[] = array(
$data->reg_no,
$data->opening_inventory_weight,
$data->status
);
}
Your result dump isn't esay too read, so I may be wrong, but it looks like RPMHeader is part of headers field, so you should access it like
$result->headers->RPMHeader

Categories