Cast MySQL table to float array using PHP PDO - php

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???

Related

Adding MySQL result in php array has duplicate values

To explain the scenario:
I have this table in MySQL DB
+-------------------------------------------------------------------------+
| message_id | client_id | admin_id | message | date_posted | read_status |
+-------------------------------------------------------------------------+
I am selecting all the messages and grouping them in a 2D Array for the same client so that the result migh look like
$messages = array(
"4" => array ("338", "4", "1", "message1", "20170904 120803", "0"),
"5" => array ("339", "5", "1", "message2", "20170904 120807","0")
);
The result I'm getting is similar but each value in the array is duplicated
array (size=12)
'message_id' => string '22' (length=2)
0 => string '22' (length=2)
'client_id' => string '14' (length=2)
1 => string '14' (length=2)
'admin_id' => string '1' (length=1)
2 => string '1' (length=1)
'message' => string 'hii I'm new to this' (length=19)
3 => string 'hii I'm new to this' (length=19)
'date_posted' => string '2017-04-22 17:17:13' (length=19)
4 => string '2017-04-22 17:17:13' (length=19)
'read_status' => string '0' (length=1)
5 => string '0' (length=1)
This is my query
$grouped_messages = array();
foreach ($connect->query("SELECT DISTINCT * FROM request ORDER BY client_id") as $row) {
var_dump($row);
$client_id = $row['client_id'];
if (!isset($grouped_messages[$client_id])) {
$grouped_messages[$client_id] = array();
}
$grouped_messages[$client_id][] = $row;
}
foreach ($grouped_messages as $client_id => $client_messages) {
echo '<div>';
echo '<p>Messages for client #' . $client_id . '</p>';
foreach ($client_messages as $message) {
foreach($message as $column) {
echo $column;
}
}
echo '</div>';
}
Any Ideas on why that is happening?
PS The same client can have multiple messages meaning multiple rows in this table that's what the code it puts all those messages from the same client into the associative array!
Fetching both numeric and text keys is a default behaviour of PDO fetch.
You can change it, in your case this should be done by setting attribute PDO::ATTR_DEFAULT_FETCH_MODE to PDO::FETCH_ASSOC:
$connect->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
Or you can do it when you instantiate new PDO object.
More modes here.

PDO_sqlsrv: wrong character encoding on field identifiers

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?

Doctrine DQL subqueries give a zero result

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;

Model uses MySQL view and some fields are not at the same level/hiearchy

I've configured a model to use a view. When querying this view in my controller, the recordset returned has two fields that are not at the same level/hiearchy than the rest.
In this case, see ast (asset_id and asset_configuration_id).
Querying the view manually in dbForge, I get a flat recordset. I cannot figure out why this is happening.
Model:
<?php
App::uses('AppModel', 'Model');
class AssetConfigurationDeploymentStatus extends AppModel {
public $useTable = "asset_configuration_deployment_statuses";
}
?>
Query for view asset_configuration_deployment_statuses:
SELECT `ac`.`id` AS `asset_configuration_id`
, `ast`.`id` AS `asset_id`
, `ac`.`domain_id` AS `domain_id`
, `ac`.`server_id` AS `server_id`
, `e`.`acronym` AS `environment`
, `e`.`id` AS `environment_id`
, `d`.`name` AS `domain`
, `lds`.`deployed_by` AS `last_deployed_by`
, `lds`.`deployed_date` AS `last_deployed_date`
, `lds`.`revision` AS `last_deployed_revision`
, `lds`.`is_failed` AS `last_deployed_is_failed`
, `lss`.`deployed_by` AS `last_successful_deployed_by`
, `lss`.`deployed_date` AS `last_successful_deployed_date`
, `lss`.`revision` AS `last_successful_deployed_revision`
, `lss`.`is_failed` AS `last_successful_deployed_is_failed`
, `eds`.`count_failed_deployments` AS `count_failed_deployments`
, `er`.`last_successful_environment_revision` AS `last_successful_environment_revision`
, `ast`.`asset_group_id` AS `asset_group_id`
FROM
(((((((((`assets` `ast`
JOIN `asset_configurations` `ac`
ON ((`ast`.`id` = `ac`.`asset_id`)))
JOIN `last_deployment_statuses` `lds`
ON ((`ac`.`id` = `lds`.`asset_configuration_id`)))
JOIN `last_successful_deployment_statuses` `lss`
ON ((`ac`.`id` = `lss`.`asset_configuration_id`)))
JOIN `last_environment_deployment_statuses` `eds`
ON ((`ac`.`id` = `eds`.`asset_configuration_id`)))
JOIN `domains` `d`
ON ((`ac`.`domain_id` = `d`.`id`)))
JOIN `servers` `s`
ON ((`ac`.`server_id` = `s`.`id`)))
JOIN `environments_servers` `es`
ON ((`s`.`id` = `es`.`server_id`)))
JOIN `environments` `e`
ON ((`es`.`environment_id` = `e`.`id`)))
JOIN `last_successful_environment_deployment_revision` `er`
ON (((`ac`.`asset_id` = `er`.`asset_id`) AND (`e`.`id` = `er`.`environment_id`))))
Controller code:
...
$this->loadModel("AssetConfigurationDeploymentStatus");
$all_deploy_items = $this->AssetConfigurationDeploymentStatus->find('all', array(
'order'=>array('AssetConfigurationDeploymentStatus.environment_id','AssetConfigurationDeploymentStatus.domain'),
'conditions' => array('AssetConfigurationDeploymentStatus.asset_id' => $id)
)
);
foreach($all_deploy_items as $conf){
var_dump($conf);
exit;
...
}
...
Output of dump:
array (size=2)
'AssetConfigurationDeploymentStatus' =>
array (size=16)
'asset_configuration_id' => string '172' (length=3)
'domain_id' => string '21' (length=2)
'server_id' => string '10' (length=2)
'environment' => string 'DEV' (length=3)
'environment_id' => string '4' (length=1)
'domain' => string 'my.domain.here' (length=28)
'last_deployed_by' => string 'user' (length=7)
'last_deployed_date' => string '2014-06-23 12:05:24' (length=19)
'last_deployed_revision' => string '644' (length=3)
'last_deployed_is_failed' => boolean false
'last_successful_deployed_by' => string 'user' (length=7)
'last_successful_deployed_date' => string '2014-06-23 12:05:24' (length=19)
'last_successful_deployed_revision' => string '644' (length=3)
'last_successful_deployed_is_failed' => boolean false
'count_failed_deployments' => string '0' (length=1)
'last_successful_environment_revision' => string '1930' (length=4)
'ast' =>
array (size=2)
'asset_id' => string '47' (length=2)
'asset_group_id' => string '28' (length=2)

PDO::FETCH_CLASSTYPE - unexpected result

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')

Categories