php foreach outside the function - php

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>

Related

Can I have two where clauses in my SQL Query so I can add $_SESSION?

I have a sql query and I want it to also only show the information for the logged in user. I was thinking is it possible for me to add another where clause to the query to add in: username = '".$_SESSION['login_user']."'
Here is my query:
$sql= "
SELECT
user.username,books.bid,name,authors,edition,
status,approve,issue,issue_book.return
FROM user
inner join issue_book ON user.username=issue_book.username
inner join books ON issue_book.bid=books.bid
WHERE issue_book.approve ='$exp'
ORDER BY `issue_book`.`return` DESC";
Anyone know how I would write this to achieve what I want above?
Here is my entire code:
<!-- Updated navbar for logged in user -->
<?php
if($_SESSION['login_user'])
{
include "navbar_user.php";
}
?>
<h2 style = "text-align: center; padding: 2%;">Your Expired Books </h2>
<?php
if(isset($_SESSION['login_user']))
{
$exp = 'EXPIRED';
$session_value = $_SESSION['login_user'];
$sql= "SELECT user.username,books.bid,name,authors,edition,status,approve,issue,issue_book.return FROM user inner join issue_book
ON user.username=issue_book.username inner join books ON issue_book.bid=books.bid WHERE issue_book.approve ='$exp' AND username = ".$_SESSION['login_user']."
ORDER BY `issue_book`.`return` DESC";
$res = mysqli_query($db,$sql);
if(mysqli_num_rows($res)==0)
{
echo "You have no expired books.";
}
else
{
?>
<table class = 'table table-bordered'>
<tr style='background-color: #abb79b; color: white;'>
<th>Username</th>
<th>BID</th>
<th>Book Name</th>
<th>Authors Name</th>
<th>Edition</th>
<th>Status</th>
<th>Return Date</th>
</tr>
<?php
while ($row = mysqli_fetch_assoc($res)) {
?>
<tr style = 'background-color: white;'>
<td><?php echo $row['username'] ?></td>
<td><?php echo $row['bid'] ?></td>
<td><?php echo $row['name'] ?></td>
<td><?php echo $row['authors'] ?></td>
<td><?php echo $row['edition'] ?></td>
<td><?php echo $row['status'] ?></td>
<td><?php echo $row['return'] ?></td>
</tr>
<?php
}
}
}
else
{
echo "</br></br></br>";
echo "<h2><b>";
echo "Please login first.";
echo "</b></h2>";
}
?>
</table>
use and(&&) operator
It may allow to add as many condition as use want

not able to get the data and display on web using php

$totDays = cal_days_in_month(CAL_GREGORIAN,$_REQUEST['month'],$_REQUEST['year']);
$attData = $commonObj->getAttendanceData($_REQUEST['month'],$_REQUEST['year']);
`
Student Name
<?php foreach($attData as $attk=>$attv){
$punchin = $commonObj->getTimeOfDate($attData[$attk]['punchin']);
$punchout = $commonObj->getTimeOfDate($attData[$attk]['punchout']);
$nam=$attv['name'];
?>
<tr>
<th class="danger">
<?php echo $nam;?>
</th>
<?php for($i=1;$i<=$totDays;$i++){?>
<?php if($commonObj->getDayOfDate($attData[$attk]['punch_time']) == $i){
echo "<td class='success' id='att_$i'>".$punchin.'-'.$punchout;?>
<table class="table table-responsive"style="display: none; position:relative;min-width:100px;max-width:200px; margin-top: -40px;" id="<?php echo "det_att_".$i;?>">
<tr>
<td>Time:</td>
<td><?php echo "p"?>
</td></tr>
<tr>
<td>UID:</td>
<td><?php echo $attData[$attk]['rfid_uid'];?></td>
</tr>
</table>
<?php
}else {echo "<td class='info'>#na";}?>
</td>
<?php }?>
</tr>
<?php }?>
</tr>
</table>`
this is the code for displaying on the web for viewing attendance ..
and here is the code for database part for getting attendance...
public function getAttendanceData($month,$year){
if(!is_numeric($month) || $month>12 || $month<1){
$this->setErrorMsg("Please Select valid month!");
header("location:viewAttendance.php");
exit;
}
$retData = array();
$fullDate = $year."-".$month;
//print_r($_SESSION);
if($_SESSION['user_type']==1){
$sql = "
SELECT t1.*
, t2.rfid_uid
, punch_time as punchin
, t2.name
FROM tbl_attendance as t1
right
join tbl_users as t2
on t1.rfid_uid = t2.rfid_uid
WHERE YEAR(punch_time) = $year
AND MONTH(punch_time) = $month
and t2.rfid_uid ='".$_SESSION['rfid_uid']."'
";
$retData = $this->getData($sql);
}else if($_SESSION['user_type'] == 2){
$sql = "SELECT t1.*,t2.rfid_uid,punch_time as punchin,t2.name FROM tbl_attendance as t1 right join tbl_users as t2 on t1.rfid_uid=t2.rfid_uid WHERE YEAR(punch_time) = $year AND MONTH(punch_time) = $month group by t2.rfid_uid";
$retData = $this->getData($sql);
}
return $retData;
}
web viewing imagedatabase table for attendanceuser
the attendance is recorded in the database but is not shown on the web..please help

PHP Notice:Array to string conversion

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,
]);

grouping class names together in my CMS php

I am done with a CMS school system which i created from scratch for practice in php. My question is for example I have Accounting 101, Computer Science 101, however there must multiple times for Accounting 101. For example: Ticket 1035, 1036 are both Accounting 101 and they should appear in the same table, but in my code it shows them in different classes. Here is my code.
if(isset($_GET['id']))
{
$category = $_GET['id'];
$sql = "SELECT * FROM classes WHERE category_id = " . $category;
$query2 = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_object($query2))
{
?>
<center><h3><?php echo $row->class_name . '-' . $row->units; ?> </h3></center>
<table border ="0" wdith="100%">
<tr>
<td>
<strong>Description: </strong>
<?php echo $row->class_description; ?>
</tr>
</td>
</table>
<br/>
<table border="1" width="44%">
<tr>
<td width="60"><b>Ticket</b> </td>
<td width="123"><b>Days</b></td>
<td width="120"><b>Hours</b></td>
<td width="64"><b>Room</b></td>
<td><b>Instructor</b></td>
</tr>
<tr>
<td width="60"> <?php echo $row->ticket; ?> </td>
<td width="123"><?php echo $row->days; ?></td>
<td width="120"><?php echo $row->start_hours . $row->time_format . '-' . $row->end_hours . $row->time_format2 ; ?> </td>
<td width="64"> <?php echo $row->room_number; ?></td>
<td><?php echo $row->instructor_name; ?></td>
</tr>
}//end while
}//end if
Its showing Accounting 101 with different tickets in different tables, but it should be all in 1 table. Thanks.
You need a double loop if you're trying to get records inside of records. For example:
while ($row1 = mysql_fetch_object($query1))
{
echo $row1->ParentName;
$query2 = 'select * from `mytable` where `myForeignKey` = ' . $row1->ParentId;
while ($row2 = mysql_fetch_object($query2))
{
echo $row2->ChildName;
}
}
You could also do a left join. Let me know if you need a sample of that.
Edit:
The left join would be done like this:
$sql = "select * from `classes` as a where category_id = '{$category}' left join `tickets` as b on a.id = b.class_id"
Ref. http://www.w3schools.com/sql/sql_join_left.asp

Null results for a specific column - php/mysql

My query returns the correct data when executed on the db, but when run live the company_title comes back null. All other fields work.
$row['company_name'] is the code i can't get to work:
$query = "select * from invoices i, company_lookup cl, students s where i.company_id = cl.company_id and i.student_id = s.student_id;";
$results = $DB->query($query);
$invoices = mysql_query("select * from invoices");
?>
<table border="1" id="hl" name="hl">
<tr>
<th>Month/Year</th>
<th>Full Amount</th>
<th>Company</th>
</tr>
<?php while ($row = mysql_fetch_array($invoices)) {
$invoice_date = $row['invoice_date'];
?>
<tr onMouseOver="showInvoicePayments(<? echo $row['invoice_id'] ?>);this.bgColor = '#C0C0C0'" onMouseOut ="this.bgColor = '#FFFFFF'" bgcolor="#FFFFFF">
<td><? echo date('F Y',strtotime($invoice_date)) ?></td>
<td><? echo '$' . $row['full_amount'] ?></td>
<td><? echo $row['company_name'] ?></td>
</tr>
<?
}
?>
try adding COALESCE in some of your fields.
like this one:
SELECT ..., COALESCE(company_title, ''),
COALESCE(company_name, '')
...
Instead of null value, it will return an empty string.

Categories