PHP Get variable value out of Object - php

I got following invalid code: (e.g. $column->Field == 'email')
echo $row[$column->Field];
With the Error:
Fatal error: Cannot use object of type stdClass as array
Thats the var_dump of $row:
object(stdClass)[17]
public 'id' => string '1' (length=1)
public 'email' => string 'master' (length=9)
public 'Name' => string 'THE MASTER' (length=28)
public 'reply' => string '1' (length=1)
I now what the error means i just can'T figure out how to work around it (i Might be too tired)
Im looking for something like that: What is the correct/working way to do so?
echo $row->$column->Field;
IDK how i didnt got to that earlier but i just defined a variable before hand
$field = $column->Field
echo $row->$field;

So 2 Solutios to this one:
1) Define a Variable:
$field = $column->Field;
echo $row->$field;
2) Credit to Abdo Adel:
If you want to do it in one line, try
$row->{$column->Field}

Related

is_null function is not working in object values

I would like to loop through an object like this
0 =>
object(stdClass)[13]
public 'first_name' => string 'toto' (length=7)
public 'last_name' => string 'titi' (length=7)
public 'phone_1' => null
1 =>
object(stdClass)[14]
public 'first_name' => string 'tutu' (length=7)
public 'last_name' => string 'tata' (length=8)
public 'phone_1' => string '123' (length=9)
This object come from a PDO::FetchAll(PDO::fetchobject).
My foreach loop:
foreach($users as $user){
echo (!is_null($user->phone)) ? $user->phone : '';
}
But I got this error message: trying to get property 'phone_1' of non-object in
May someone help me for this ?
Thank you
This:
echo (!is_null($user->phone)) ? $user->phone : '';
... can be simplified to:
echo $user->phone;
If the property is null, it'll cast automatically to empty string ('').
If you get trying to get property 'phone' of non-object1 it's because you don't have an object to begin with. That's a different problem.
If you're looping the results of a database query, you shouldn't need to check for object existence, and doing so might mask a bug in some other part of your code. A possible cause is that your query is failing and fetchAll() returns false.
1 Please note I've fixed the property name in the error message, assuming it was a copy+paste error. If you really read phone and get an error about phone_1, you didn't check the correct line.
I found a solution:
<?php echo isset($user->phone) ? $user->phone : ''; ?>

Undefined property within foreach unless print_r'd

I feel I must be missing something here. PHP displays: "Notice: Undefined property: DateTime::$date" when trying to display a property from an outer loop but if I print_r() the line before, then it prints the value with no error. Comment it out again, and the error comes back?
I suspect perhaps $iteration['EventTime']->date is getting confused with the date() function in PHP but am not sure how to overcome this via an escape. I cannot change the format of the object.
Object:
array (size=6)
'LINE' => string '2' (length=1)
'EventTime' =>
object(DateTime)[2]
public 'date' => string '2019-09-11 01:25:10.000000' (length=26)
public 'timezone_type' => int 3
public 'timezone' => string 'Europe/London' (length=13)
'Tag' => string 'PLC32.J.A.10.NOREAD' (length=19)
'Area' => string 'Material\PLC32' (length=14)
'Message' => string '32JA10 Consecutive No-read Fault' (length=32)
'FAULT_STATE' => int 1
Loop:
foreach ($sqlsrv_fetch_all as $index => $row) {
if ($row['FAULT_STATE'] == 1) {
foreach ($sqlsrv_fetch_all as $iteration) {
if ($iteration['LINE'] < $row['LINE'] || $iteration['Tag'] != $row['Tag'] || $iteration['FAULT_STATE'] == 1) {
continue;
} else {
//print_r($row);
echo "row: ".$row['EventTime']->date;
}
}
}
}
Should output "row: 2019-09-11 01:25:10.000000";
But unless I call print_r() first, it errors and outputs nothing.
This is actually a bug in PHP (I'm yet to find its ID in the bugtracker) that has been fixed with PHP 7.4 - see here.
print_r is one of a few ways to display internals of an object, including its private properties. Apparently, before PHP 7.4, calling print_r on an object caused its properties to become public (presumably using reflections, so that their contents could be displayed), but never turned back after that.
The documentation does not name \DateTime::$date as a public field. If you want to display date, use \DateTime::format() method instead.

Unable To Show Data in PHP Using ASP.NET Web Service

I've created a simple web service in ASP.NET and want that service to be consumed in a PHP application. The web service is as follows:
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public List<Customer> GetCustomers(int id)
{
id = Convert.ToInt32(HttpContext.Current.Request.QueryString["id"]);
List<Customer> lst = null;
using (var context = new DemoEntities())
{
lst = (from c in context.Customer
where c.CustomerID == id
select c).ToList();
}
return lst;
}
In the above web service, a customer id is passed to retrieve customer details. So to consume this service in PHP, I've tried to do the following using nuSoap library as follows and it works almost:
<?php
require_once("lib/nusoap.php"); //Using the nuSoap library
$client = new nuSoap_Client('http://localhost:1284/MyCustomers.asmx?wsdl', TRUE); //Passed the ASP.NET web service and an object created
$result = $client->call('GetCustomers', array('id' => 1)); //Called the GetCustomers method and passed a default parameter
foreach($result as $item) //Tried to iterate in a foreach loop
{
echo $item; //Here is the issue - The output returns or returned only the name 'Array'
}
?>
I've done PHP programming a long time ago and trying to figure the issue searching google. I've even tried to access the array index with the web service property directly like the below but seems like missing something or may be not the correct way: Any idea would be appreciated
echo $item[1]->CustName;
echo $item[1]; //Even this
Right now, I am getting the Xml data as follows using the Soap web service:
<ArrayOfCustomer>
<Customer>
<CustomerID>2</CustomerID>
<CustName>John</CustName>
<CustAddress>On Earth</CustAddress>
<CustLocation>On Earth</CustLocation>
<CustSex>Male</CustSex>
<CustType>3</CustType>
<CustStatus>2</CustStatus>
<CustDetails>Great guy - Always regular.</CustDetails>
</Customer>
</ArrayOfCustomer>
Update 1: Used var_dump($item) and currently getting the array elements as follows:
array
'Customer' =>
array
'CustomerID' => string '2' (length=1)
'CustName' => string 'John' (length=7)
'CustAddress' => string 'On Earth' (length=25)
'CustLocation' => string 'On Earth' (length=10)
'CustSex' => string 'Male' (length=4)
'CustType' => string '3' (length=1)
'CustStatus' => string '2' (length=1)
'CustDetails' => string 'Great guy - Always regular.' (length=47)
But when tried with this $item->Customer->CustName, getting this error again - Trying to get property of non-object.
Update 2: Again used var_dump($item) and the result is as follows with PHP programming:
<?php
require_once("lib/nusoap.php");
$client = new nuSoap_Client('http://localhost:1284/MyCustomers.asmx?wsdl', TRUE);
$result = $client->call('GetAllCustomers'); //Without any parameter
foreach($result as $item)
{
echo var_dump($item);
}
?>
Output:
array
'Customer' =>
array
0 =>
array
'CustomerID' => string '1' (length=1)
'CustName' => string 'Jack' (length=7)
'CustAddress' => string 'On Earth' (length=25)
'CustLocation' => string 'On Earth' (length=10)
'CustSex' => string 'Male' (length=4)
'CustType' => string '3' (length=1)
'CustStatus' => string '2' (length=1)
'CustDetails' => string 'Regular Customer and always happy to cooperate.' (length=47)
1 =>
array
'CustomerID' => string '2' (length=1)
'CustName' => string 'John' (length=4)
'CustAddress' => string 'On Earth' (length=7)
'CustLocation' => string 'On Earth' (length=10)
'CustSex' => string 'Male' (length=4)
'CustType' => string '3' (length=1)
'CustStatus' => string '2' (length=1)
'CustDetails' => string 'Great guy - Always regular.' (length=25)
Again, tried to use two loops to get the values that's as follows but it only returns first two results and there are total 10 records in the database:
<?php
require_once("lib/nusoap.php");
$client = new nuSoap_Client('http://localhost:1284/MyCustomers.asmx?wsdl', TRUE);
$result = $client->call('GetAllCustomers');
$count = count($result);
foreach($result as $item)
{
for($i = 0; $i <= $count; $i++)
{
echo 'Name: ' . $item['Customer'][$i]['CustName'].'<br/>';
}
}
?>
Output:
Name: Jack //Returns only first two records though it should return all the records
Name: John
Simply do a var_dump($item); in php to see how they array structure is.. currently I do not know what the response object is, but for example you can access the keys as such: echo $item->Customer->CustName;
If it is an array response, not an object, then: $item['Customer']['CustName'];

PHP : Notice: Undefined property: stdClass::

I am fetching json data from a table called properties. Column name is attr and it has size,bedrooms and prop-type in it.
$q= mysqli_query($connect,"SELECT * FROM properties");
$savemyval = array();
while($row= mysqli_fetch_assoc($q)){
$data = json_decode($row['attr']);
//var_dump($data);
if($proptpe == $data->proptype){
$savemyval[] = $row['id'];
}
}
Querying data like above if i var_dump this is what i get
object(stdClass)[3]
public 'bedrooms' => string '5' (length=1)
public 'proptype' => string 'residential' (length=11)
object(stdClass)[4]
public 'bedrooms' => string '4' (length=1)
public 'proptype' => string 'commercial' (length=10)
object(stdClass)[3]
public 'size' => string '16000' (length=5)
public 'prop-type' => string 'commercial' (length=10)
in var_dump i get proper data but when i try to get proprtype, if its more than 1 it gives me the error
PHP : Notice: Undefined property: stdClass::
if I use isset then there is no error but still it prints one result while dumping gives me more than 1 results
Because in your array you doesn't have proptype on second index
try like this
if(isset( $data['proptype']) && $proptpe == $data->proptype){
$savemyval[] = $row['id'];
}

"Trying to get property of non-object" in SOAP PHP - not sure why this error is occuring

Hope you guys can help me... Still new at PHP and I am struggling to display parts of this Object/Array set of Results.
I am getting the following result $results back from a SOAP webservice:
`object(stdClass)[9]
public 'Summary' =>
object(stdClass)[2]
public 'ID' => string '1096408402' (length=10)
public 'IKey' => string '1440010962' (length=10)
public 'Address' =>
object(stdClass)[4]
public 'Forename' => string 'TEST' (length=4)
public 'Surname' => string 'TESTER' (length=6)
public 'DOB' => string '0000-00-00' (length=10)
public 'Telephone' => string 'Unavailable' (length=11)
public 'Occupants' =>
array (size=3)
0 =>
object(stdClass)[12]
...
1 =>
object(stdClass)[13]
...
2 =>
object(stdClass)[14]
...
3 =>
object(stdClass)[15]
...
Now I am attempting to put the data into a table format.
I have been successful in creating the table using a foreach on the section marked Occupants. I do this by calling Occupants as follows:
$occupants = ($results->Address->Occupants); and the data is extracted and populated into my table using my code (not relevent for this question).
My problem now is that when I try and do the same for Summary or Address it doesnt work: I get the error "Trying to get property of non-object"
I have tried $summary = $results->Summary and $summary = $results['Summary'] and neither works.
What I then want to do is run
<?php $summary = ($results->Summary);foreach($summary as $person):?>
and then I insert it into my table as follows:
<td><?=$person->ID?></td>
So any idea why I get this error? I dont think it is in the foreach aspect...?
Normally, you should get the "Summary" object with:
$summary = $results->Summary
in this case $summary is an object with 2 properties: "ID" and "IKey".
If you iterate over $summary with foreach, the value of $person would have the value of $summary->ID in the first loop iteration and the value of $summary->IKey in the second loop iteration. Both $summary->ID and $summary->IKey are strings and therefore non-objects, so I think that is why you get the error.
I suppose that you want do do this:
$summary = $results->Summary;
foreach ($summary as $value)
echo "<td>$value</td>";
This should output (for the given example):
<td>1096408402</td><td>1440010962</td>
For more information about Object Iteration, I recommend: http://php.net/manual/en/language.oop5.iterations.php

Categories