PHP Notice:Array to string conversion - php

I want to show all data from $result into my table but there's some error.
I'm trying to access a php array. But it is throwing me Array to string conversion error.
The notice is "Array to string conversion"
my controller :
public function actionStockitem() {
$datepost = date('Y-m-d');
$d1 = isset($data['d1']) ? $data['d1'] : $datepost;
$sql = " SELECT s1.name as name
FROM
(SELECT i.item_id,i.name,i.unitcost,
(SUM(s1.qty)) as stock1,
((SUM(s1.qty))* i.unitcost) as cost1
FROM (SELECT item_id,name,unitcost FROM mitem ) as i
JOIN mstocklist s1 ON s1.item_id=i.item_id
JOIN mstock s2 ON s2.id=s1.stock_id
WHERE s2.receive_date <='$d1'
GROUP BY i.item_id
ORDER BY i.name ASC ) s1
LEFT OUTER JOIN
(SELECT i.item_id,i.name,i.unitcost,
(SUM(s1.qty)) as stock2,
((SUM(s1.qty))* i.unitcost) as cost2
FROM (SELECT item_id,name,unitcost FROM mitem ) as i
JOIN msublist s1 ON s1.item_id=i.item_id
JOIN msub s2 ON s2.id=s1.sub_id
WHERE s2.receive_date <='$d1'
GROUP BY i.item_id
ORDER BY i.name ASC ) s2 ON s2.item_id=s1.item_id
WHERE ((s1.stock1)-IFNULL(s2.stock2,0))<>0
ORDER BY s1.name,cost1 ASC ";
$command = Yii::$app->db->createCommand($sql);
$reader = $command->query();
$inames = $reader->readAll();
$temp = array();
$iname = $inames;
$temp['name'] = $iname;
$result[] = $temp;
return $this->render('stockitem', [
'inames' => $inames,
'sql' => $sql,
'result' => $result,
]);
}
and this is the View :
<tbody>
<tr>
<td>
<?php
$i = 1;
foreach ($result as $data) {
?>
</td>
</tr>
<tr>
<td align="center"><?php echo $i; ?></td>
<td align="left" class="style3"><?php echo $data['name']; ?></td> //error in this line
<td align="center" class="style3"><?php echo ''; ?></td>
<td align="center" class="style3"><?php echo ''; ?></td>
<td align="center" class="style3"><?php echo ''; ?></td>
<td align="center" class="style3"><?php echo ''; ?></td>
<td align="center" class="style3"><?php echo ''; ?></td>
<td align="center" class="style3"><?php echo ''; ?></td>
</tr>
</tbody>
<?php
$i++;
}
?>
Please give me some advice

Your pushing data to inside the array needlessly . readAll() returns the result in single array .so just pass it to view . like this .
$inames = $reader->readAll();
// $temp = array();
//$iname = $inames;
// $temp['name'] = $iname;
// $result[] = $temp;
return $this->render('stockitem', [
'inames' => $inames,
'sql' => $sql,
'result' => $inames,
]);

Related

PHP While cicle keep loading and give error

guys i have the following code, but when i execute it on my site, the site give me internal server error 500
$Data = $con->prepare("SELECT Example1,Example2,Example3,Example4 FROM SITES WHERE Email=:Email");
$Data->execute(array(
':Email' => $Email,
));
if ($Data->rowCount() > 0) {
$Rows = $Data->rowCount();
$CL = 1;
$Result = $Data->fetch(PDO::FETCH_ASSOC);
while ($CL <= $Rows) {
$Example1 = $Result['Example1'];
$Example2 = $Result['Example2'];
$Example3 = $Result['Example3'];
$Example4 = $Result['Example4'];
$CL = $CL++;
echo
'<tr class="tr">
<td class="td"><?=$Example1?></td>
<td class="td"><?=$Example2?></td>
<td class="td"><?=$Example3?></td>
<td class="td"><?=$Example4?></td>
<td class="td"></td>
</tr>';
}
}
I want that for every row where email=:email php will print an html row of an existing table.Thanks in advice, have a good day!
Try this {Let's us know if it works for you}
$Data = $con->prepare("SELECT Example1,Example2,Example3,Example4 FROM SITES WHERE Email=:Email");
$Data->execute(array(
':Email' => $Email,
));
if ($Data->rowCount() > 0) {
$Rows = $Data->rowCount();
$CL = 1;
$Result = $Data->fetch(PDO::FETCH_ASSOC);
while ($CL <= $Rows) {
$Example1 = $Result['Example1'];
$Example2 = $Result['Example2'];
$Example3 = $Result['Example3'];
$Example4 = $Result['Example4'];
//$CL = $CL++; This is bad;
$CL++;
echo
'<tr class="tr">'; <?
<td class="td"><?php echo $Example1 ;?></td>
<td class="td"><?php echo $Example2 ;?></td>
<td class="td"><?php echo $Example3 ;?></td>
<td class="td"><?php echo $Example4 ;?></td>
<td class="td"></td>
<?php
echo '</tr>';
}
}

How to retrieve data from database and display it in table

I am using WordPress and the global class $wpdb in order to retrieve data from MySQL database and display the results in a table.
I have 4 dropdown list that allow the user to select the required inputs then based on the selected inputs the system display all the related data for the user selection.
When I try to run the code it display error:
Notice: Array to string conversion
first part of code :
<?php
/*
Template Name: search info
*/
get_header();
?>
<?php
// code for submit button ation
global $wpdb,$_POST;
//variables that handle the retrieved data from mysql database
if(isset($_POST['site_name']))
{
$site_name=$_POST['site_name'];
}
else { $site_name=""; }
if(isset($_POST['owner_name']))
{
$owner_name=$_POST['owner_name'];
}
else { $owner_name=""; }
if(isset($_POST['Company_name']))
{
$company_name=$_POST['Company_name'];
}
else { $company_name=""; }
if(isset($_POST['Subcontractor_name']))
{
$Subcontractor_name=$_POST['Subcontractor_name'];
}
else { $Subcontractor_name="";}
$site_id = ['siteID'];
$equipment_type = ['equipmentTYPE'];
$lat=['latitude'];
$long=['longitude'];
$height = ['height'];
$owner_contact = ['ownerCONTACT'];
$sub_contact = ['subcontractorCONTACT'];
$sub_company = ['subcontractorCOMPANY'];
if(isset($_POST['query_submit']))
{
//query to retrieve all related info of the selected data from the dropdown list
$query_submit =$wpdb->get_results ("select
site_info.siteID,site_info.siteNAME ,site_info.equipmentTYPE,site_coordinates.latitude,site_coordinates.longitude,site_coordinates.height ,owner_info.ownerNAME,owner_info.ownerCONTACT,company_info.companyNAME,subcontractor_info.subcontractorCOMPANY,subcontractor_info.subcontractorNAME,subcontractor_info.subcontractorCONTACT from `site_info`
LEFT JOIN `owner_info`
on site_info.ownerID = owner_info.ownerID
LEFT JOIN `company_info`
on site_info.companyID = company_info.companyID
LEFT JOIN `subcontractor_info`
on site_info.subcontractorID = subcontractor_info.subcontractorID
LEFT JOIN `site_coordinates`
on site_info.siteID=site_coordinates.siteID
where
site_info.siteNAME = `$site_name`
AND
owner_info.ownerNAME = `$owner_name`
AND
company_info.companyNAME = `$company_name`
AND
subcontractor_info.subcontractorNAME = `$Subcontractor_name`
");
?>
<table width="30%" >
<tr>
<td>Site Name</td>
<td>Owner Name</td>
<td>Company Name</td>
<td>Subcontractor Name</td>
</tr>
<tr>
<td><?php echo $site_name ; ?></td>
<td><?php echo $owner_name ; ?></td>
<td><?php echo $company_name ; ?></td>
<td><?php echo $Subcontractor_name ; ?></td>
<td><?php echo $site_id ; ?></td>
<td><?php echo $equipment_type ; ?></td>
<td><?php echo $lat ; ?></td>
<td><?php echo $long ; ?></td>
<td><?php echo $height ; ?></td>
<td><?php echo $owner_contact ; ?></td>
<td><?php echo $sub_contact ; ?></td>
<td><?php echo $sub_company ; ?></td>
</tr>
</table>
<?php } ?>
The second part of code is for retrieve data from database and includes it in the dropdown list.
I will appreciate any help.
You can get rid of the "Array to string conversion" error quite easy.
In these lines, you are creating arrays:
$site_id = ['siteID'];
$equipment_type = ['equipmentTYPE'];
$lat=['latitude'];
...
$sub_company = ['subcontractorCOMPANY'];
...which you later are trying to echo. You simply can't echo arrays.
Just change the above to be strings instead:
$site_id = 'siteID';
$equipment_type = 'equipmentTYPE';
$lat = 'latitude';
...
$sub_company = 'subcontractorCOMPANY';
Note: As others already pointed out, your code is wide open to SQL Injections. You should really escape your data, before using it in any queries.
<table border="1">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Points</th>
</tr>
<?php
global $wpdb;
$result = $wpdb->get_results ( "SELECT * FROM myTable" );
foreach ( $result as $print ) {
?>
<tr>
<td><?php echo $print->firstname;?></td>
</tr>
<?php }

How to Not display empty rows?

My question is:
If you look at where it would display "
<td>1ST<?php echo $first ?></td>
"
How do I ensure that if the row associate to variable '$first' or all the others if they are empty nothing shows. Also that the '1st' doesn't show?
Have tried various things I am stumped on this!
<h2><?php echo $show_title ?></h2>
<h4>Show Date: <span class="glyphicon glyphicon-time"> </span><?php echo $show_date ?></h4>
<hr>
</a>
<hr>
<?php
// SO UPDATE THE QUERY TO ONLY PULL THAT SHOW'S DOGS
$query = "SELECT * FROM result
WHERE first IS NOT NULL";
$result = mysqli_query($connection, $query) or trigger_error
("Query Failed! SQL: $query - Error: ". mysqli_error
($connection), E_USER_ERROR);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$dog_name = $row['dog_name'];
$placement = $row['placement'];
$class_name = $row['class_name'];
$entries = $row['entries'];
$absentee = $row['absentee'];
$entries = $row['entries'];
$first = $row['first'];
$second = $row['second'];
$third = $row['third'];
$RES = $row['RES'];
$VHC = $row['VHC'];
$DCC = $row['DCC'];
$RDCC = $row['RDCC'];
$BCC = $row['BCC'];
$RBCC = $row['RBCC'];
$BOB = $row['BOB'];
$BP = $row['BP'];
$BJ = $row['BJ'];
?>
<table class="table" border="0"></div>
<tr>
<td><strong><?php echo $class_name ?></strong> - <h6>Entries: <?php echo $entries ?> Absentees: <?php echo $absentee ?></h6></td>
<td></td>
</tr>
<tr>
<td>DCC</td>
<td><?php echo $DCC ?></td>
</tr>
<tr>
<td>RDCC</td>
<td><?php echo $RDCC ?></td>
</tr>
<tr>
<td>BCC</td>
<td><?php echo $BCC ?></td>
</tr>
<tr>
<td>RBCC</td>
<td><?php echo $RBCC ?></td>
</tr>
<tr>
<td>BOB</td>
<td><?php echo $BOB ?></td>
</tr>
<tr>
<td>BP</td>
<td><?php echo $BP ?></td>
</tr>
<tr>
<td>BJ</td>
<td><?php echo $BJ ?></td>
</tr>
<tr>
<td>1ST</td>
<td><?php echo $first ?></td>
</tr>
<tr>
<td>2ND</td>
<td><?php echo $second ?></td>
</tr>
<tr>
<td>3RD</td>
<td><?php echo $third ?></td>
</tr>
<tr>
<td>RES</td>
<td><?php echo $RES ?></td>
</tr>
<tr>
<td>VHC</td>
<td><?php echo $VHC ?></td>
</tr>
</table>
You're doing well, just apply a filtering function to each row you recieve:
// SO UPDATE THE QUERY TO ONLY PULL THAT SHOW'S DOGS
$query = "SELECT * FROM result
WHERE first IS NOT NULL";
$result = mysqli_query($connection, $query);
if (!$result) {
trigger_error("Query Failed! SQL: $query - Error: ". mysqli_error($connection), E_USER_ERROR);
} else {
// Fetch results into array
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
// If results array is not empty
if ($data) {
echo '<table class="table" border="0"></div>
<tr>
<td>
<strong><?php echo $class_name ?></strong> - <h6>Entries: <?php echo $entries ?> Absentees: <?php echo $absentee ?></h6>
</td>
<td></td>
</tr>';
// Now let's walk through every record
array_walk($data, function($dogRecord) {
// Here we apply array_filter to each dog record, so that empty values (i.e. those evaluating to false) are filtered out
$dogRecord = array_filter($dogRecord);
// Now loop throw $dogRecord to build table
$collation = [
'DCC' => 'DCC',
'RDCC' => 'RDCC',
'BCC' => 'BCC',
'RBCC' => 'RBCC',
'BOB' => 'BOB',
'BP' => 'BOB',
'BJ' => 'BOB',
'1ST' => 'first',
'2ND' => 'second',
'3RD' => 'third',
'RES' => 'RES',
'VHC' => 'RES'
];
foreach ($dogRecord as $property => $value) {
echo '<tr>
<td>'.$collation[$property].'</td>
<td>'.$value.'</td>
</tr>';
}
});
echo '</table>';
}
}
Note that instead of simple foreach loop I'm using array_walk function. This is because since you extract variables for each record, you want undeclared (i.e. unoccupied) varables every time.
What about this:
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
// Show the table-row
}
}
The following code will iterate through each row in the result (while loop) and each key => value within each row (foreach loop); it will then check if a value is not null or the key is not equal to 'first' (if statement) and echo the results in the table element. I'm not sure I fully understood your question but I hope this helps in some small way.
<table>
<?php
if($result){
while($row = mysqli_fetch_assoc($result))
foreach($row as $key => $value){
if($value != null && $key != 'first'){
echo '<tr>';
echo '<td>' . $key . '</td>';
echo '<td>' . $value . '</td>';
echo '</tr>';
}
}
}
?>
</table>

php table add values if cell repeats

I have a wordpress loop retriving a table like this:
I want to check if the name repeats it self and if so do a sum of partial values to show the total.
On my screenshot the 1st and 3rd rows have the same "nome" so the global value should be 85, can any one tellme how to do this ?
my php :
<?php while( have_rows('wallet_repeater') ): the_row();
echo '<div class="promotoras_item_wallet"> ';
echo '<div class="promnames_wallet"> ';
// vars
$adicionados = get_sub_field('wallet_promotora');
foreach($adicionados as $post) :
$nome = simple_fields_values("pname1");
$im = simple_fields_values("ftotop");
$cp=$adicionados ;
$imatop = $im;
$data=get_sub_field('wallet_data');
$evento=get_sub_field('wallet_evento');
$obs=get_sub_field("wallet_obs");
$numeros_horas = get_sub_field("Wallet_n_horas");
$valor_horas = get_sub_field("wallet_valorh");
$evento = get_sub_field("wallet_evento");
$horarios = get_sub_field("wallet_horario");
$total_parcial = $valor_horas * $numeros_horas."€";
$ii = wp_get_attachment_image($imatop[0]);
?>
<table id="wallet_table1" width="900px" border="0" cellspacing="2" cellpadding="0">
<tbody>
<tr>
<tr onmouseover="this.style.backgroundColor='#ffff66';" onmouseout="this.style.backgroundColor='#d4e3e5';">
<td class="wallet_data_img" width="5"><div class="w_promotora_images"><?php echo wp_get_attachment_image($imatop[0]); ?></td>
<td class="wallet_data_data" width="20"><?php echo the_sub_field('wallet_data'); ?> </td>
<td class="wallet_data_nome" width="200"><?php echo $nome[0];$nomes[]=$nome[0];?></td>
<td class="wallet_data_evento" width="10"> <?php echo the_sub_field("wallet_evento"); ?></td>
<td class="wallet_data_horarios" width="10"><?php echo the_sub_field("wallet_horario"); ?></td>
<td class="wallet_data_obs" width="10"><?php echo the_sub_field("wallet_obs"); ?></td>
<td class="wallet_data_horas" width="10"><?php echo the_sub_field("Wallet_n_horas")."h"; ?></td>
<td class="wallet_data_valorh" width="5"><?php echo the_sub_field("wallet_valorh")."€"; ?></td>
<td class="wallet_data_props" width="5"><?php echo the_sub_field("wallet_props"); ?></td>
<td class="wallet_data_total" width="5">Parcial: <?php echo $total_parcial; ?> global:
</td> </tr></tbody></table>
<?php
Stuff the query data into an associative array and after that output it.
You can do it like that:
$qry = new WP_Query('post_type' => 'your_post_type', 'posts_per_page' => -1)
$arr = array();
while($qry->have_posts()) {
$qry->the_post()
$nam = //Get the name data;
$val = //Get the «global» data;
if($qry[$nam]) {
$qry[$nam]['global'] += $val;
}
else {
$qry[$nam] = array(
'foto' => //Photo data of the current post,
'name' => //Photo data of the current post,
//and so on
'global' => $val,
);
}
}
foreach($qry as $key => $data) {
//Output your table here
}

php foreach outside the function

i'm learning php.
i have a function with mysql query select.
than i use it with foreach list..
but it work me only if the foreach is inside the function.
i don't know how to get it work outside the function..
what i'm doing wrong?
working code - https://phpbox.info/d3GCP
no working code:
function volaco ()
{
$query = $db->getQuery(true);
$query = "select a.id, count(i.id) as all_items, a.name, SUM(i.state = '1') published, SUM(i.state = '0') unpublished"
. " FROM item as i"
. " JOIN application a ON a.id = i.application_id"
. " group by i.application_id";
$db->setQuery($query);
$apps= $db->loadObjectList();
}
$apps = volaco();
?>
<table >
<?php if (count($apps)) : foreach ($apps as $app) : ?>
<tr >
<td width="40%"><?php echo $app->name; ?></td>
<td width="20%" style="text-align: center;"><?php echo $app->all_items;?></td>
<td width="20%" style="text-align: center;"><?php echo $app->published; ?></td>
<td width="20%" style="text-align: center;"><?php echo $app->unpublished; ?></td>
</tr>
<?php endforeach; else : ?>
<?php endif; ?>
</table>
thanks a lot
You function volaco() need return type
return $apps= $db->loadObjectList();
Read Returning values
Add a return to your volaco() function, $apps is out of the scope.
function volaco ()
{
$query = $db->getQuery(true);
$query = "select a.id, count(i.id) as all_items, a.name, SUM(i.state = '1') published, SUM(i.state = '0') unpublished"
. " FROM item as i"
. " JOIN application a ON a.id = i.application_id"
. " group by i.application_id";
$db->setQuery($query);
return $db->loadObjectList();
?>
Try this:
function volaco ()
{
$query = $db->getQuery(true);
$query = "select a.id, count(i.id) as all_items, a.name, SUM(i.state = '1') published, SUM(i.state = '0') unpublished"
. " FROM item as i"
. " JOIN application a ON a.id = i.application_id"
. " group by i.application_id";
$db->setQuery($query);
$apps= $db->loadObjectList();
return $apps;
}
$apps = volaco();
?>
<table >
<?php if (count($apps)) : foreach ($apps as $app) : ?>
<tr >
<td width="40%"><?php echo $app->name; ?></td>
<td width="20%" style="text-align: center;"><?php echo $app->all_items;?></td>
<td width="20%" style="text-align: center;"><?php echo $app->published; ?></td>
<td width="20%" style="text-align: center;"><?php echo $app->unpublished; ?></td>
</tr>
<?php endforeach; else : ?>
<?php endif; ?>
</table>

Categories