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')
Related
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.
Ok i inherited a pretty bad DB Situation the Views and Tables are in use and can't or can only with a lot of work be changed.
I am trying to get a Php/Html based Tool to work with the DB.
Here is my Info:
try {
$conn = new PDO("sqlsrv:server=$serverName;Database = $database", $uid, $pwd);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::SQLSRV_ATTR_ENCODING, PDO::SQLSRV_ENCODING_UTF8);
} catch (PDOException $e) {
die("Error connecting to SQL Server " . $e);
}
This is my PDO connection and
select * from munition.dbo.V_Admin_Zündhütchen order by Kaliber desc
this my query.
V_Admin_Zündhütchen is a View.
When i fetch the return and dump it like this:
$row = $sql->fetch(PDO::FETCH_ASSOC)
var_dump($row);
I get this:
array (size=5)
'ID' => string '2' (length=1)
'Kaliber' => string '7,62 mm' (length=7)
'Hersteller' => string 'Vihtavuori' (length=10)
'Z�ndtyp' => string 'Boxer' (length=5)
'Bezeichnung' => string '1511' (length=4)
the � is supposed to be a ü
The byte sequence of what is shown as Z�ndtyp is 5A FC 6E 64 74 79 70
The Data itself is fine only the Columnames are affected:
array (size=5)
'ID' => string '24' (length=2)
'Kaliber' => string '12/70' (length=5)
'Hersteller' => string 'Rottweil' (length=8)
'Z�ndtyp' => string 'Boxer' (length=5)
'Bezeichnung' => string 'Schrotzünder' (length=13)
So why does it not resolve properly?
This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 2 years ago.
I am trying to get single value from DB with single query. i mean that i already featched all values in one query from that i need to get only one column value.
$connection = mysqli_connect($servername, $username, $password, $dbname);
$query = mysqli_query( $connection,"select * from register where password='$log_in_password' AND username='$log_in_username'");
var_dump($query);
$table = mysqli_fetch_all($query,MYSQLI_ASSOC);
var_dump($table);
assume columns are
' userid useremail username password Name '
from php
var_dump($query) gives this..
object(mysqli_result)[2]
public 'current_field' => null
public 'field_count' => null
public 'lengths' => null
public 'num_rows' => null
public 'type' => null
var_dump($table) gives this
array (size=1)
0 =>
array (size=5)
'userid' => string '7' (length=1)
'useremail' => string 'demo#gmail.com' (length=16)
'username' => string 'demousername' (length=7)
'password' => string 'demopassword' (length=5)
'Name' => string 'demoname' (length=6)
so help me out with fetching only one column value's record (example insSelect * to select userid)
Your variable $table is an array, so if you want only the userid, you just have to use
$table[0]['userid']
If you want to query only the userid change you query like this :
$query = mysqli_query( $connection,"select userid from register where password='$log_in_password' AND username='$log_in_username'");
$table = mysqli_fetch_all($query,MYSQLI_ASSOC);
And the result of $table will be :
array (size=1)
0 =>
array (size=1)
'userid' => string '7' (length=1)
$table will also be an array, and to acces userid you have to use again
$table[0]['userid']
Try this
$connection = mysqli_connect($servername, $username, $password, $dbname);
$query = mysqli_query($connection, "select * from register where password='$log_in_password' AND username='$log_in_username'");
$table = null;
while ($row = mysqli_fetch_array($query)) {
$table = $row;
}
print_r($table);
I want to get a multidimentional php array from MySQL database where I want to cast a field to float.
I'm using PHP 5.3 and MySQL 5
and this is my code:
*** My PDO class:
class DB {
private static $instance = NULL;
public static function getInstance() {
if (!self::$instance) {
try {
self::$instance = new PDO("mysql:host=" . SERVER . ";dbname=" . DtB, USR, PASS);
self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
self::$instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, 0);
self::$instance->query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'");
} catch (PDOException $e) {
echo 'Échec lors de la connexion : ' . $e->getMessage();
}
}
return self::$instance;
}
private function __clone() {
/* interdiction de cloner l'instance */
}
}
And I use it like this:
$datas1 = $db->query('
SELECT
r.nom AS nomReg,
COUNT(e.regions) AS nbr
FROM regions r
LEFT OUTER JOIN event e ON r.nom=e.regions
GROUP BY r.nom
')->fetchAll(PDO::FETCH_ASSOC);
and :
$dataTypes=$db->query("
SELECT tt.nomtype_tache AS name,
CAST(((COUNT(t.nomtype_tache) / (
SELECT count(t.idtype_tache) AS y
FROM type_tache tt
LEFT OUTER JOIN tache t
ON tt.idtype_tache = t.idtype_tache
)
) * 100) AS DECIMAL(5,1)) AS y
FROM type_tache tt
LEFT OUTER JOIN tache t ON tt.idtype_tache = t.idtype_tache
GROUP BY name
")->fetchAll(PDO::FETCH_ASSOC);
and this the var_dump of these variables:
$datas1:
array (size=4)
0 =>
array (size=2)
'nomReg' => string 'ARIANA' (length=6)
'nbr' => int 1
1 =>
array (size=2)
'nomReg' => string 'BEJA' (length=4)
'nbr' => int 0
2 =>
array (size=2)
'nomReg' => string 'BEN AROUS' (length=9)
'nbr' => int 1
3 =>
array (size=2)
'nomReg' => string 'BIZERTE' (length=7)
'nbr' => int 0
$dataTypes:
array (size=3)
0 =>
array (size=2)
'name' => string 'type1' (length=5)
'y' => string '0.0' (length=3)
1 =>
array (size=2)
'name' => string 'type2' (length=5)
'y' => string '0.0' (length=3)
2 =>
array (size=2)
'name' => string 'type3' (length=5)
'y' => string '13.3' (length=4)
I don't no what is the problem that don't make the 'y' field to be float???
I have three related entities : Group, GroupDefault, GroupDefaultTranslation on a Mysql server.
The Group entity stores the groups of a user.
The GroupDefault entity define the default groups for any user.
The GroupDefaultTranslation entity stores the translation for the default groups.
The relationships between the entities are types:
- ManyToOne between Group and GroupDefault
- OneToManu ent GroupsDefault and GroupDefaultTranslation
My goal is to display the list of groups of a user with the corresponding translation in his language parameter.
Here is my QueryBuilder with DQL query generated :
public function findByOwnerWithLanguage($languageCode, $ownerId)
{
$qb = $this->createQueryBuilder('g')
->select('g.name')
->addSelect('gdt.content AS name')
->join('g.parent', 'gd')
->join('gd.translations', 'gdt')
->where('g.owner = :owner');
//création de l'expression AND
$orModule = $qb->expr()->andX();
$orModule->add($qb->expr()->eq('g.parent', '0'));
$orModule->add($qb->expr()->eq('gdt.locale', ':language'));
$orModule->add($qb->expr()->eq('g.owner', ':owner'));
//Ajout de l'expression à la requête
$qb->orWhere($orModule)
->setParameter('language', $languageCode, \PDO::PARAM_STR)
->setParameter('owner', $ownerId)
->orderBy('g.isMyLightbox', 'DESC')
->getQuery()
->getResult();
return $qb;
// DQL Query :
// SELECT g.name, gdt.content AS name
// FROM Horyou\Bundle\CoreBundle\Entity\Group g
// INNER JOIN g.parent gd
// INNER JOIN gd.translations gdt
// WHERE g.owner = :owner
// OR (g.parent = 0 AND gdt.locale = :language AND g.owner = :owner)
// ORDER BY g.isMyLightbox DESC
}
And here is the output of the object var_dump :
object(stdClass)[1368]
public '__CLASS__' => string 'Doctrine\ORM\QueryBuilder' (length=25)
public '_em' =>
object(stdClass)[1362]
public '__CLASS__' => string 'Doctrine\ORM\EntityManager' (length=26)
public 'config' => string 'Doctrine\ORM\Configuration' (length=26)
public 'conn' => string 'Doctrine\DBAL\Connection' (length=24)
public 'metadataFactory' => string 'Doctrine\ORM\Mapping\ClassMetadataFactory' (length=41)
public 'unitOfWork' => string 'Doctrine\ORM\UnitOfWork' (length=23)
public 'eventManager' => string 'Symfony\Bridge\Doctrine\ContainerAwareEventManager' (length=50)
public 'proxyFactory' => string 'Doctrine\ORM\Proxy\ProxyFactory' (length=31)
public 'repositoryFactory' => string 'Doctrine\ORM\Repository\DefaultRepositoryFactory' (length=48)
public 'expressionBuilder' => string 'Doctrine\ORM\Query\Expr' (length=23)
public 'closed' => boolean false
public 'filterCollection' => string 'Doctrine\ORM\Query\FilterCollection' (length=35)
public '_dqlParts' =>
array (size=9)
'distinct' => boolean false
'select' => string 'Array(2)' (length=8)
'from' => string 'Array(1)' (length=8)
'join' => string 'Array(1)' (length=8)
'set' => string 'Array(0)' (length=8)
'where' => string 'Doctrine\ORM\Query\Expr\Orx' (length=27)
'groupBy' => string 'Array(0)' (length=8)
'having' => null
'orderBy' => string 'Array(1)' (length=8)
public '_type' => int 0
public '_state' => int 1
public '_dql' => string 'SELECT g.name, gdt.content AS name FROM Horyou\Bundle\CoreBundle\Entity\Group g INNER JOIN g.parent gd INNER JOIN gd.translations gdt WHERE g.owner = :owner OR (g.parent = 0 AND gdt.locale = :language AND g.owner = :owner) ORDER BY g.isMyLightbox DESC' (length=251)
public 'parameters' =>
array (size=2)
0 => string 'Doctrine\ORM\Query\Parameter' (length=28)
1 => string 'Doctrine\ORM\Query\Parameter' (length=28)
public '_firstResult' => null
public '_maxResults' => null
public 'joinRootAliases' =>
array (size=2)
'gd' => string 'g' (length=1)
'gdt' => string 'g' (length=1)
My problem is that the result is zero.
Does anyone see what is the error in my QueryBuilder?
Actually it's not a result - it's just a dump of a query builder object. I think you have to do something like this:
...
$qb->orWhere($orModule)
->setParameter('language', $languageCode, \PDO::PARAM_STR)
->setParameter('owner', $ownerId)
->orderBy('g.isMyLightbox', 'DESC');
$result = $qb->getQuery()->getResult();
return $result;