i try show data using PDO. But i get Error "Trying to get property of non-object".
i have a simple script.
public function tampilUserId($user_id)
{
$sql = "SELECT $this->user.*, $this->provinsi.*
FROM $this->user
INNER JOIN $this->provinsi
ON $this->user.provinsi_id=$this->provinsi.provinsi_id
WHERE user_id=:user_id";
$stmt = db::prepare($sql);
$stmt->bindParam(':user_id', $user_id);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_OBJ);
}
And this
echo $results->email_user;
print_r($result);
result
Notice: Trying to get property of non-object in C:\xampp\htdocs\laporan_app\user_views\profile.php on line 35
stdClass Object ( [user_id] => 45 [nama_dpn_user] => [nama_blkng_user] => [username_user] => adi [password_user] => $2y$10$p/8gF5BcQSooQUKRlEAiPuOSy4o1RMeXA5Ul8GTZNYZi/4wcOP3Ja [email_user] => adi#gmail.com [level_user] => mahasiswa [img_user] => [_dir_img_user] => [_size_img_user] => [provinsi_id] => [universitas_id] => )
And i try this script
echo $results['email_user'];
print_r($results);
result
Notice: Undefined index: email_user in C:\xampp\htdocs\laporan_app\user_views\profile.php on line 35
stdClass Object ( [user_id] => 45 [nama_dpn_user] => [nama_blkng_user] => [username_user] => adi [password_user] => $2y$10$p/8gF5BcQSooQUKRlEAiPuOSy4o1RMeXA5Ul8GTZNYZi/4wcOP3Ja [email_user] => adi#gmail.com [level_user] => mahasiswa [img_user] => [_dir_img_user] => [_size_img_user] => [provinsi_id] => [universitas_id] => )
Please help me, thanks before.
Merdeka! :D
In case your SQL query not contain any error its mean data was successfully pulled from database. So in your tampilUserId($user_id) function, its returning set of array from $stmt->fetchAll(PDO::FETCH_OBJ). Like below:
/* Sample from Sakila database */
array (size=603)
0 =>
object(stdClass)[11]
public 'address_id' => string '1' (length=1)
public 'address' => string '47 MySakila Drive' (length=17)
public 'address2' => null
public 'district' => string 'Alberta' (length=7)
public 'city_id' => string '300' (length=3)
public 'postal_code' => string '' (length=0)
public 'phone' => string '' (length=0)
public 'last_update' => string '2014-09-25 22:30:27' (length=19)
1 =>
object(stdClass)[12]
public 'address_id' => string '2' (length=1)
public 'address' => string '28 MySQL Boulevard' (length=18)
public 'address2' => null
public 'district' => string 'QLD' (length=3)
public 'city_id' => string '576' (length=3)
public 'postal_code' => string '' (length=0)
public 'phone' => string '' (length=0)
public 'last_update' => string '2014-09-25 22:30:09' (length=19)
more elements...
All you need to do is looping your function returned value first whereever you call it. Short example from your case:
//I dont know you put it under class or not.
$data = $YourClass->tampilUserId($user_id);
foreach ($data as $item) {
echo $item->email_user);
}
Note:
You can manually echoing your data without looping and its bad practice because you dont know the length of the array. So this is just gusessing. Taken from your case it would be.
$data = $YourClass->tampilUserId($user_id);
$data[0]->email_user; //If an object
$data[0]['email_user']; //If an array
Update:
There is suspicious thing on your query. The variable $this->user is not look like column name to me(unsure) If yes, so you have small mistake on your query. Secondly, as you said the result is null its mean something wrong or data you search not exist. I put this sample running inner join query.
Example:
Lets said i had 2 table. 1st is address and 2nd is city
|address table|
|city table|
So your sql query for joining table(from image above) should be:
SELECT adr.address_id, adr.address, adr.district, adr.city_id, c.city_id,
c.city FROM address AS adr INNER JOIN city AS c ON adr.city_id = c.city_id
WHERE c.city_id = 300 #using city id
Output:
Bring it to PHP
<?php
$pdo= new PDO('mysql:dbname=sakila;host=localhost:3306', 'user', password');
$city_id = 300; // manual set
$sql = 'SELECT adr.address_id, adr.address, adr.district, adr.city_id,
c.city_id, c.city FROM address AS adr INNER JOIN city AS c ON
adr.city_id = c.city_id WHERE c.city_id = :city_id';
$stmt = $_this->db->prepare($sql);
$stmt->bindParam(':city_id', $city_id);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
?>
var_dump($data) giving a result:
Great, as it come as (object(stdClass)) so we can loop it through the array & then accessing it using -> sign.
<?php
$i = 1;
foreach ($data as $d) {
echo '<dl>';
echo '<dt>Adress '.$i++.':</dt>';
echo '<li>Address id: '.$d->address_id.'</li>';
echo '<li>Address: '.$d->address.'</li>';
echo '<li>District: '.$d->district.'</li>';
echo '<li>City id: '.$d->city_id.'</li>';
echo '<li>City name: '.$d->city.'</li>';
echo '</dl>';
}
?>
Result in browser:
Hope this will resolve your problem.
Related
So I have been doing my research and no method seems to parse my file correctly. I have tried these two codes, my data is being inserted into sql however it is inserted 3 times with the first insertion being fine while the other 2 are blank. Here is my JSON file and code:
JSON:
[
{
"Comments": {
"Manufacturer": "--E",
"Model": "----- ----- ----",
"BIOSFamily": "---",
"BIOSDate": --/--/---8",
"SerialNumber": "---------"
}
},
{
"#ComputerSystem.v1-----------ystem": {
"/redfish/v1/Systems/1/": {
"AssetTag": " ",
"Bios": {
"#odata.id": "/redfish/v1/systems/1/bios/"
},
"BiosVersion": "U----------------)",
"Boot": {
"BootSourceOverrideMode": "-----y",
"BootSourceOverrideTarget": "None",
"BootSourceOverrideEnabled": "Disabled",
"BootSo-----------arget#Redfish.AllowableValues": [
"None",
"Cd",
"Hdd",
"Usb",
"Utilities",
"Diags",
"BiosSetup",
"Pxe",
"UefiShell"
]
Code:
<?php
$connect = mysqli_connect("reserve1",
"root", "","server_31");
$filename = "-----.json";
$data = file_get_contents($filename);
$array = json_decode($data, true);
foreach($array as $row)
{
$sql = "INSERT INTO servers (Model,
Manufacturer, BIOSFamily,
BIOSDate,
SerialNumber) VALUES
('".$row["Comments"]["Model"]."' ,
'".$row["Comments"]
["Manufacturer"]."',
'".$row["Comments"]
["BIOSFamily"]."','".$row["Comments"]
["BIOSDate"]."','".$row["Comments"]
["SerialNumber"]."')";
mysqli_query($connect, $sql);
}
echo "Data in";
?>
ERROR:" Notice: Undefined index: Comments "
other forloops i have tried are:
foreach($data as $Comments)
{
$sql =" INSERT INTO
'servers'('Manufacturer','Model',
'BIOSFamily','BIOSDate',
'SerialNumber'), VALUES('{$Comments-
>Manufacturer}', '{$Comments-
>Model}',
'{$Comments->BiosFamily}',
'{$Comments->BiosDate}',
'{$Comments-
>SerialNumber}')";
}
ERROR:" Notice: Trying to get property of non-object in"
To reiterate: the first method does get my info onto sql but does so 3 times with the last 2 entries being blank. The second method does not insert anything into my table.
EDIT:
so i tried vardump, using the file itself all i got was NULL, copy and pasting the contents and labeling it $json= ' content ' in the script i get..
C:\Users\Administrator\Desktop\Reserve1\newtry\NEWJSONP.php:16:
array (size=1)
0 =>
object(stdClass)[1]
public 'Comments' =>
object(stdClass)[2]
public 'Manufacturer' => string 'HPE' (length=3)
public 'Model' => string '-------------' (length=20)
public 'BIOSFamily' => string '---' (length=3)
public 'BIOSDate' => string '--/--/----' (length=10)
public 'SerialNumber' => string '-------' (length=10)
C:\Users\Administrator\Desktop\Reserve1\newtry\NEWJSONP.php:17:
array (size=1)
0 =>
array (size=1)
'Comments' =>
array (size=5)
'Manufacturer' => string '---' (length=3)
'Model' => string '------ ----------' (length=20)
'BIOSFamily' => string '---' (length=3)
'BIOSDate' => string '--/--/----' (length=10)
'SerialNumber' => string '-------' (length=10)
Simply index in your foreach loop the first item since $array object maintains Comments only in first position. See 0 index from var_dump output:
array (
0 =>
array (
'Comments' =>
array (
'Manufacturer' => '--E',
'Model' => '----- ----- ----',
'BIOSFamily' => '---',
'BIOSDate' => ' --/--/-- - 8 ',
'SerialNumber' => '---------',
),
),
1 =>
array (
'#ComputerSystem.v1-----------ystem' =>
...
Therefore, iterate through the Comments array and use parameterization for readability:
$connect = new mysqli($servername, $username, $password, $dbname);
// PREPARED STATEMENT
$sql = "INSERT INTO servers (Model, Manufacturer, BIOSFamily, BIOSDate, SerialNumber)
VALUES(?, ?, ?, ?, ?)";
// INDEX FIRST ITEM AT 0
foreach($array[0] as $row) {
$stmt = $connect->prepare($sql);
// BIND PARAMETERS (NO COMMENTS INDEX)
$stmt->bind_param("sssss", $row["Model"],
$row["Manufacturer"],
$row["BIOSFamily"],
$row["BIOSDate"],
$row["SerialNumber"]);
// EXECUTE STATEMENT
$result = $stmt->execute();
}
In Codeigniter I am tryign to join two tables with one to many relation. I want to get one result from my table housetype and all of its values/members from other table housetype_member:
$this->db->select('*');
$this->db->join('housetype_member', 'housetype_member.housetype_id = housetype.PkId', 'left');
$result = $this->db->get_where('housetype', array('PkId' => $id));
return $result->result();
So far I get such result:
array (size=2)
0 =>
object(stdClass)[28]
public 'PkID' => string '4' (length=1)
public 'Name' => string 'Classic' (length=7)
public 'image' => string '1449063250.jpg' (length=14)
1 =>
object(stdClass)[30]
public 'PkID' => string '4' (length=1)
public 'Name' => string 'Classic' (length=7)
public 'image' => string '1449063288.gif' (length=14)
First two object values (PkID, Name) are from the first table and the last one (image) is from the second left table. Everything is good but I get array with two elements, when I only need one housetype object.
Is there a way to write above code so that my returned object would look like this:
object(stdClass)[28]
public 'PkID' => string '4' (length=1)
public 'Name' => string 'Classic' (length=7)
public 'image' =>
array (size=2)
0 => string '1449063250.jpg' (length=14)
1 => string '1449063288.gif' (length=14)
I need one result from first table and to it I want to join all of its members from the second table.
Can it be done with Codeigniters active record?
As far as your second table has multi records with that primary key, it is better if you don't use joins at all.
You can simply get that with two selects.
$this->db->select('PkID, name');
$this->db->where('PkId', $id);
$houseTypes = $this->db->get('housetype')->result();
foreach($houseTypes as $houseType){
$this->db->select('image');
$this->db->where('housetype_id', $houseType->PKId);
$houseType->image = $this->db->get('housetype_member')->result();
}
return $houseTypes;
I want to get Doctrine to return a hydrated array with the values being the id for the key, then all values inside an array of results (i.e. if there are multiple items with same ID, then return ID with multiple results in array).
This is the current function I do:
public static function getMedia($em, $entity, $id = NULL)
{
$dql = 'SELECT m.id, m.url, m.nb, m.lang
FROM iMT\Entity\Media m INDEX BY m.id JOIN iMT\Entity\\' . $entity . ' r WITH m.id = r.id';
if($id) {
$dql .= " WHERE r.id = ?1";
}
$q = $em->createQuery($dql);
if($id) {
$q->setParameter(1, $id);
}
return $q->getResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);
}
Which returns:
array (size=44)
479600 =>
array (size=4)
'id' => int 479600
'url' => string 'pois/479600/Nonna.JPG' (length=48)
'nb' => null
'lang' => string 'fr' (length=2)
479615 =>
array (size=4)
'id' => int 479615
'url' => string 'pois/479615/Tramways.jpg' (length=51)
'nb' => null
'lang' => string 'fr' (length=2)
479580 =>
array (size=4)
'id' => int 479580
'url' => string 'pois/479580/ATLAS.jpg' (length=48)
'nb' => null
'lang' => string 'fr' (length=2)
479581 =>
array (size=4)
'id' => int 479581
'url' => string 'pois/479581/P'tit_sushi.jpg' (length=54)
'nb' => null
'lang' => string 'fr' (length=2)
However, I need the output to be:
array (size=44)
479600 =>
array (size=2)
array (size=4)
'id' => int 479600
'url' => string 'pois/479600/Nonna.JPG' (length=48)
'nb' => null
'lang' => string 'fr' (length=2)
array (size=4)
'id' => int 479600
'url' => string 'pois/479600/OtherPic.JPG' (length=48)
'nb' => null
'lang' => string 'fr' (length=2)
Would I need to create my own AbstractQuery::HYDRATE_ARRAY or is there something available that does what I need?
I'm using the result by checking if it contains a key that matches the ID of the current item (e.g. if(isset($data[$item])) // where $item = 479600 then output images), maybe there's a better way to check for the results?
EDIT
I've updated my function to return:
$result = $q->getResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);
$data = array();
$count = count($result);
for($i = 0; $i < $count; $i++) {
if(!isset($data[$result[$i]['id']])) {
$data[$result[$i]['id']] = array(
$result[$i]
);
} else {
$data[$result[$i]['id']][] = $result[$i];
}
}
return $data;
Which returns something more to what I want:
array (size=44)
479600 =>
array (size=1)
0 =>
array (size=4)
'id' => int 479600
'url' => string 'pois/479600/Nonna.JPG' (length=48)
'nb' => null
'lang' => string 'fr' (length=2)
479577 =>
array (size=2)
0 =>
array (size=4)
'id' => int 479577
'url' => string 'pois/479577/AOMC.JPG' (length=47)
'nb' => null
'lang' => string 'fr' (length=2)
1 =>
array (size=4)
'id' => int 479577
'url' => string 'pois/479577/Buffet AOMC.jpg' (length=54)
'nb' => null
'lang' => string 'fr' (length=2)
Can this be improved? Is there any Doctrine functions that can help, or should I leave my for() loop?
The problem with using INDEX BY together with a JOIN is that the result that doctrine gives you might not contain all data that's fetched from the database.
In your case the database might return multiple rows containing the same value for m.id (because of the JOIN). But each subsequent row containing the same value for m.id will overwrite the previous one (because of the INDEX BY m.id).
Doctrine does not come with a hydrator that can solve this problem out of the box. You shall indeed need to implement your own. Read more about creating custom hydration modes.
Alternative
Another solution would be to not use INDEX BY in this case.
You could write a repository method that translates the result given by Doctrine to the array you want to have. Other parts of your application can then call that repository method.
This is probably easier than creating a custom hydration mode.
Update
The translation can look like this:
$data = array();
foreach ($q->getArrayResult() as $row) {
if (!isset($data[$row['id']])) {
$data[$row['id']] = array();
}
$data[$row['id']][] = $row;
}
return $data;
I'am at loss here. Not sure why I'm getting "stdClass". Shouldn't I be getting name from 1st column?
$sql = "SELECT cn, iso2, iso3, fid, sort FROM ct";
$stmt = $dbh->query($sql);
$result = $stmt->fetch( PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE );
var_dump($result);
//expected - first: cn.col holds country names
object(Brazil)[3]
public 'iso2' => string 'BR' (length=2)
public 'iso3' => string 'BRA' (length=3)
public 'fid' => string '1' (length=1)
public 'sort' => string '0' (length=1)
//received
object(stdClass)[3]
public 'iso2' => string 'BR' (length=2)
public 'iso3' => string 'BRA' (length=3)
public 'fid' => string '1' (length=1)
public 'sort' => string '0' (length=1)var_dump
The issue is most likely that the class is not defined (or in scope). I did some testing using local data.
$conn = new PDO("mysql:host=localhost;dbname=test", 'user', 'pass');
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$stmt = $conn->prepare("SELECT name,email FROM `test_table`");
$stmt->execute();
$result = $stmt->fetch( PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE );
print_r($result) // returns stdClass Object ( [email] => 'test#test.com' )
By adding this above the PDO code
Class levi{
}
I was able to get it to return:
levi Object ( [email] => 'test#test.com')
I have a var dump of my sql query which return the following
I wanna to count in the array below that how many rows of myID = 5 are there. How would I do that. I am using php. Thanks in advance
array
0 =>
object(stdClass)[17]
public 'myID' => string '5' (length=1)
public 'data' => string '123' (length=3)
1 =>
object(stdClass)[18]
public 'myID' => string '5' (length=1)
public 'data' => string '123' (length=3)
2 =>
object(stdClass)[19]
public 'relativeTypeID' => string '2' (length=1)
public 'data' => string '256' (length=3)
3 =>
object(stdClass)[20]
public 'myID' => string '4' (length=1)
public 'data' => string '786' (length=3)
object(stdClass)[21]
public 'myID' => string '4' (length=1)
public 'data' => string '786' (length=3)
Do you always have the same value of data for the same myID? In other words, is data functionally dependant on myID?
If so, you can get the database to do this for you:
SELECT myID, data, COUNT(*) AS cnt
FROM (your query here)
GROUP BY myID, data
This would give you results like the following:
myID data cnt
'5' '123' 3
'2' '256' 1
'4' '786' 2
Or, you can use a foreach statement, like:
$count = 0;
foreach($arr as $item)
{
// Given that your item is an stdClass Object you access its property with "->"
// if an array $item["myID"] instead
if ( $item->myID == '4' )
{
$count ++;
}
}