Echo return values from rows from db - php

Does it make difference to get the value of result set when using alias names and join in the SQL generated using zend framwork.
Regarding to the sql resulted from the selected answer in this question I want to print all result in .phtml file.
I make like this
<?php
foreach($this->rows as $row){
echo $row->visit_id . ' ' . $row->rep_id . ' '.$row->target;
?>
When I print the size of $this->rows it returns the correct number of rows, but it doesn't print any thing?!
Edit
here's what I get when I print $rows
Zend_Db_Statement_Pdo Object ( [_fetchMode:protected] => 2 [_stmt:protected] => PDOStatement Object ( [queryString] => SELECT `r`.`rep_id`, `r`.`visit_id`, `v`.`target`, `v`.`visit_id` FROM `visit_report_tb` AS `r` INNER JOIN `inspection_visits_tb` AS `v` ON v.visit_id=r.visit_id WHERE (r.visit_id = 1) ) [_adapter:protected] => Zend_Db_Adapter_Pdo_Mysql Object ( [_pdoType:protected] => mysql [_numericDataTypes:protected] => Array ( [0] => 0 [1] => 1 [2] => 2 [INT] => 0 [INTEGER] => 0 [MEDIUMINT] => 0 [SMALLINT] => 0 [TINYINT] => 0 [BIGINT] => 1 [SERIAL] => 1 [DEC] => 2 [DECIMAL] => 2 [DOUBLE] => 2 [DOUBLE PRECISION] => 2 [FIXED] => 2 [FLOAT] => 2 ) [_defaultStmtClass:protected] => Zend_Db_Statement_Pdo [_config:protected] => Array ( [dbname] => inspection [username] => root [password] => 123456 [charset] => [persistent] => [options] => Array ( [caseFolding] => 0 [autoQuoteIdentifiers] => 1 [fetchMode] => 2 ) [driver_options] => Array ( ) ) [_fetchMode:protected] => 2 [_profiler:protected] => Zend_Db_Profiler Object ( [_queryProfiles:protected] => Array ( ) [_enabled:protected] => [_filterElapsedSecs:protected] => [_filterTypes:protected] => ) [_defaultProfilerClass:protected] => Zend_Db_Profiler [_connection:protected] => PDO Object ( ) [_caseFolding:protected] => 0 [_autoQuoteIdentifiers:protected] => 1 [_allowSerialization:protected] => 1 [_autoReconnectOnUnserialize:protected] => ) [_attribute:protected] => Array ( ) [_bindColumn:protected] => Array ( ) [_bindParam:protected] => Array ( ) [_sqlSplit:protected] => Array ( [0] => SELECT `r`.`rep_id`, `r`.`visit_id`, `v`.`target`, `v`.`visit_id` FROM `visit_report_tb` AS `r` INNER JOIN `inspection_visits_tb` AS `v` ON v.visit_id=r.visit_id WHERE (r.visit_id = 1) ) [_sqlParam:protected] => Array ( [0] => SELECT `r`.`rep_id`, `r`.`visit_id`, `v`.`target`, `v`.`visit_id` FROM `visit_report_tb` AS `r` INNER JOIN `inspection_visits_tb` AS `v` ON v.visit_id=r.visit_id WHERE (r.visit_id = 1) ) [_queryId:protected] => )

If you are using the query you accepted in the other question, your field names should be as you expect.
I usually just var_dump $row to see what's there is what I expect:
<?php
foreach($this->rows as $row){
//Zend_Debug::dump() provides formatted debug info, the second argument is a label
Zend_Debug::dump($row, 'Row')
?>
This should give you a pretty good idea of what each row contains with out all the baggage that $rows has.

Heh, and that's why I pointed You to ReferenceMap i Zend_Db_Tables. Check my answer to Your previous question.
https://stackoverflow.com/a/9905206/1278879
Using my code from Your previous question You could've done it like this:
foreach ($reportRowset as $reportRow) {
echo $reportRow->visit_id . ' ' . $reportRow->rep_id . ' '.$visitRow->target;
}
And that's piece of cake

The row is not an object, its an array and it can be get like this:
print $row['rep_id']

Related

How can i reformat array this array?

So i have this database table
From that table i want to achievie this (My Expected result)
I don't know the best way to handle this, so for now i create two query.
My first query
SELECT * FROM ( select convert(created_date,date) created_date,code,'' code2,count(code) total, 0 total2
from morning_briefing
where convert(created_date,date) = convert('" . $selected_date . "',date) and code IS NOT NULL
group by code order by created_date desc) a order by total desc
My second query
SELECT * FROM ( select convert(created_date,date) created_date,''code,code2,0 total,count(code2) total2
from morning_briefing
where convert(created_date,date) = convert('" . $selected_date . "',date)
and code2 IS NOT NULL
group by code2 order by created_date desc) a order by total2 desc
Below is result for my query
Array
(
[0] => stdClass Object
(
[created_date] => 2021-03-16
[code] => AA
[code2] =>
[total] => 2
[total2] => 0
)
[1] => stdClass Object
(
[created_date] => 2021-03-16
[code] => AB
[code2] =>
[total] => 1
[total2] => 0
)
[2] => stdClass Object
(
[created_date] => 2021-03-16
[code] => BB
[code2] =>
[total] => 1
[total2] => 0
)
)
then my second query result is this
Array
(
[0] => stdClass Object
(
[created_date] => 2021-03-16
[code] =>
[code2] => AB
[total] => 0
[total2] => 2
)
[1] => stdClass Object
(
[created_date] => 2021-03-16
[code] =>
[code2] => AA
[total] => 0
[total2] => 1
)
)
So, i want to merge both of the array , then i want to order total column desc, the second order is total2
Btw, i'm using mysql table. So how can i achieve my expected result (above), thanks in advance.
You can loop through your $results1 and $result2 and create a new array that contains data in your expected result format.
$total = max(count($result1), count($result2));
$formatted = [];
for($i = 0; $i < $total; $i++) {
$formatted[] = [
'code' => isset($result1[$i]) ? $result1[$i]->code : '-',
'total' => isset($result1[$i]) ? $result1[$i]->total : 0,
'code2' => isset($result2[$i]) ? $result2[$i]->code2: '-',
'total2' => isset($result2[$i]) ? $result2[$i]->total2 : 0
];
}

How to get the data Using Yii2 Query Builder

What i am trying
I have 2 table staff and salarydetails,i want to fetch staff name and there respective salary
$salaries = SalaryDetails::find()->select('salary_details.total_salary AS salary,staff.name AS name')
->leftJoin("staff",'salary_details.staff_id = staff.id');
if ($fcreated_date != null && $tcreated_date != null) {
$salaries->andFilterWhere(['>=','salary_details.salary_given_date', $fcreated_date]);
$salaries->andFilterWhere(['<=', 'salary_details.salary_given_date', $tcreated_date]);
}
when i try to print sql raw query by using
echo $salaries->createCommand()->getRawsql();
i got SELECT salary_details.total_salary AS salary, staff.name AS name FROM salary_details LEFT JOIN staff ON salary_details.staff_id = staff.id
and this query gives the data i wanted in phpMyadmin
But the array gives ie, print_r($salaries); gives
yii\db\ActiveQuery Object ( [sql] => [on] => [joinWith] => [select] => Array ( [0] => salary_details.total_salary AS salary [1] => staff.name AS name ) [selectOption] => [distinct] => [from] => [groupBy] => [join] => Array ( [0] => Array ( [0] => LEFT JOIN [1] => staff [2] => salary_details.staff_id = staff.id ) ) [having] => [union] => [params] => Array ( ) [_events:yii\base\Component:private] => Array ( ) [_behaviors:yii\base\Component:private] => Array ( ) [where] => [limit] => [offset] => [orderBy] => [indexBy] => [modelClass] => common\models\SalaryDetails [with] => [asArray] => [multiple] => [primaryModel] => [link] => [via] => [inverseOf] => )
Thanks,
As you can see in your print_r, $salaries is an ActiveQuery instance. Call the methods ->asArray()->all() on it to get the records.
$query = SalaryDetails::find()
->select('salary_details.total_salary AS salary,staff.name AS name')
->leftJoin("staff",'salary_details.staff_id = staff.id');
if ($fcreated_date != null && $tcreated_date != null) {
$query->andFilterWhere(['>=','salary_details.salary_given_date', $fcreated_date]);
$query->andFilterWhere(['<=', 'salary_details.salary_given_date', $tcreated_date]);
}
$salaries = $query->asArray()->all();
Note that without asArray the all would return an array of SalaryDetails records and you would loss the staff name.

Drupal - Unable to get result from db_query

I have written below code in drupal module.
echo '<pre>';
$data = db_query("SELECT uid, name, status, created, access FROM {users} u WHERE uid <> 0 LIMIT 50 OFFSET 0");
print_r($data);
die;
But it is not giving me users data it is giving me below output:
DatabaseStatementBase Object
(
[dbh] => DatabaseConnection_mysql Object
(
[needsCleanup:protected] =>
[target:protected] => default
[key:protected] => default
[logger:protected] =>
[transactionLayers:protected] => Array
(
)
[driverClasses:protected] => Array
(
[SelectQuery] => SelectQuery
)
[statementClass:protected] => DatabaseStatementBase
[transactionSupport:protected] => 1
[transactionalDDLSupport:protected] =>
[temporaryNameIndex:protected] => 0
[connectionOptions:protected] => Array
(
[database] => aaldev
[username] => root
[password] =>
[host] => localhost
[port] =>
[driver] => mysql
[prefix] => Array
(
[default] =>
)
)
[schema:protected] =>
[prefixes:protected] => Array
(
[default] =>
)
[prefixSearch:protected] => Array
(
[0] => {
[1] => }
)
[prefixReplace:protected] => Array
(
[0] =>
[1] =>
)
)
[queryString] => SELECT uid, name, status, created, access FROM users u WHERE uid <> 0 LIMIT 50 OFFSET 0
)
Please help me on this.
Assuming that your query is correct, and Drupal documentation, you have a fetchAll() method:
$data = db_query("SELECT uid, name, status, created, access FROM {users} u WHERE uid <> 0 LIMIT 50 OFFSET 0");
$data->fetchAll();
Retrieve all records into an indexed array of stdClass objects.

Data from array into html combobox

I have 2 arrays inside the class Continente..both public and i populate the arrays with records from mysql database.
class Continente{
public $continente = array();
public $tari= array();
}
And i have an object for wich i call the methods to put data into my arrays.
$cont = new Continente;
$cont->setContinente();
$cont->setTari();
Now the arrays look like this:
Array (
[0] => Array ( [Id] => 1 [Nume] => Europa )
[1] => Array ( [Id] => 2 [Nume] => Asia )
[2] => Array ( [Id] => 3 [Nume] => Africa ) )
and:
Array
( [0] => Array ( [Id] => 0 [Nume] => Romania [idContinent] => 1 [Populatie] => 2500 )
[1] => Array ( [Id] => 0 [Nume] => Bulgaria [idContinent] => 1 [Populatie] => 2200 )
[2] => Array ( [Id] => 0 [Nume] => Estonia [idContinent] => 1 [Populatie] => 1100 )
[3] => Array ( [Id] => 0 [Nume] => Japonia [idContinent] => 2 [Populatie] => 5000 )
[4] => Array ( [Id] => 0 [Nume] => China [idContinent] => 2 [Populatie] => 4599 )
[5] => Array ( [Id] => 0 [Nume] => India [idContinent] => 2 [Populatie] => 6000 )
[6] => Array ( [Id] => 0 [Nume] => Egipt [idContinent] => 3 [Populatie] => 444 ) )
now i need to make a combox with the 3 continents , and for each continent selected i need to print the first 3 countries sorted by the bigest number in 'Populatie' .
So i can select the contries for the continents... i have Id=idContinent .
Now i really don't know how to do this. Write a method for this in php? As i already have the arrays... or html?
This is what i tried:
<html>
<head></head>
<body>
<div>
<br>
<select>
<?php
foreach($cont->tari as $val ){
echo '<option value="'.$val.'">'.$val.'</option>';
}
?>
</select>
</div>
</body>
</html>
If you can do it, I think you can clean up your data structure quite a bit and it would make it easier to accomplish what you are trying to do. If you store your information like this:
$data = array( Europa => array (Romania => 2500,
Bulgaria => 2200,
Estonia => 1100 ),
Asia => array ( Japonia => 5000,
China => 4599,
India => 6000 )
...);
Then you may be able to eliminate the need for your "ID" keys and just use the array indices for your IDs.
Then you can just sort your subarrays by value using arsort(). Something like this:
foreach( $data as $cont => $pop_data ) {
arsort( $pop_data );
}
Then for creating your combo boxes, use similar code:
foreach( $data as $cont => $pop_data ) {
echo $cont . " Population Info:" . "<br>"; // or whatever
foreach( $pop_data as $country => $pop ) {
echo '<option value="'.$pop.'">'.$pop.'</option>';
}
}

Add key and variable to multidimensional Array based on conditions

I wonder if it's possible to add a key and value to an array, based on certain conditions.
This piece of script makes an api-call to retrieve sportresults from multiple teams based on a teamID number.
$length = $numberofTeams
for ($i = 0; $i < $length; $i++) {
$teamID = $objTeamID[$i]['Teamid'];
$teamResults = 'http://api.com/teamresults/' . $Teamid;
$dataResults = file_get_contents($teamResults);
$objResults[] = json_decode($dataResults, true);
}
The result is an array with this structure:
Array (
[0] => Array (
[errorcode] => 9995
[message] => No results
)
[1] => Array (
[errorcode] => 1000
[message] => Ok, Schedule follows
[List] => Array (
[0] => Array (
[MatchID] => 7683403
[Number] => 630
[Result] => 2 - 1
[Datum] => 2013-08-27
[Tijd] => 2000
[CompType] => B )
[1] => Array (
[MatchID] => 7683403
[Number] => 630
[Result] => 4 - 0 [Datum] => 2013-08-27
[Tijd] => 2000
[CompType] => B )
)
)
[2] => Array (
[errorcode] => 9995
[message] => No results )
)
Before saving it in an MySql database, for later use I need to add the teamID-variable to every result so it would become:
Array (
[0] => Array (
[errorcode] => 9995
[message] => No results
)
[1] => Array (
[errorcode] => 1000
[message] => Ok, Schedule follows
[List] => Array (
[0] => Array (
[teamID] => 'value from $teamID'
[MatchID] => 7683403
[Number] => 630
[Result] => 2 - 1
[Datum] => 2013-08-27
[Tijd] => 2000
[CompType] => B )
[1] => Array (
[teamID] => 'value from $teamID' [MatchID] => 7683403
[Number] => 630
[Result] => 4 - 0
[Datum] => 2013-08-27
[Tijd] => 2000
[CompType] => B )
)
)
[2] => Array (
[errorcode] => 9995
[message] => No results )
)
The length of the array varies and also the number of results vary. I have no influence on the result of the api-call itself, because it's been set up by big sport association.
I'm absolutely no programmer, so I'm out of my depth her, but this is a voluntary job for an amateur sportsclub so hiring a programmer is no option.
Rgds, Bonzyx
if(isset($objResults[1]['List'])){
foreach($objResults[1]['List'] as &$listItem){
$listItem['teamID'] = $teamID;
}
unset($listItem); //good practice to unset this reference to last array element
}
You could do the same with php's array_walk() function, but since you said you're not a programmer I think the foreach method is more clear to you.

Categories