QueryFetchArrayAll from multiple tables? - php

I am pulling out data from my "facebook" table using this code that I then display in a table using the foreach() function:
$orders = $db->QueryFetchArrayAll("SELECT id,url,c_amount,amount,date,status FROM `facebook` WHERE `user`='".$data['id']."' ORDER BY `date` DESC LIMIT 30");
How would I go about pulling out data from multiple tables, for example from the "facebook" AND "twitter" table and then displaying it at the same time in my table?
Here is my full code for those that would need that:
<table class="table">
<thead>
<tr>
<td># (ID)</td>
<td>URL</td>
<td>Current Amount</td>
<td>Amount Wanted</td>
<td>Date</td>
<td>Status</td>
</tr>
</thead>
<tbody>
<?
$orders = $db->QueryFetchArrayAll("SELECT id,url,c_amount,amount,date,status FROM `facebook` WHERE `user`='".$data['id']."' ORDER BY `date` DESC LIMIT 30");
if(!$orders){ echo '<tr><td colspan="6" align="center"><b>Noting found!</b></td><tr>';}else{
foreach($orders as $order){
?>
<?
if($order['status'] == 0){
$status = '<label style="color: #999999;">Waiting for supplier</label>';
}
elseif ($order['status'] == 1) {
$status = '<label style="color: #f0ad4e;">In progress</label>';
}
elseif ($order['status'] == 2) {
$status = '<label style="color: #e25856;">Canceled/Refunded</label>';
}
elseif ($order['status'] == 3) {
$status = '<label style="color: #428bca;">Pending admin review</label>';
}
else{
$status = '<label style="color: #94b86e;">Completed</label>';
}
?>
<tr>
<td><?=$order['id']?></td>
<td><?=$order['url']?></td>
<td><?=$order['c_amount']?></td>
<td><?=$order['amount']?></td>
<td><?=date('Y-m-d h:i',$order['date'])?></td>
<td><?=$status?></td>
</tr><?}}?>
</tbody>
</table>

Use the UNION keyword.
Please note that both queries should have the same fields count and the same fields types.
Example :
$orders = $db->QueryFetchArrayAll(
"SELECT id,url,c_amount,amount,date,status FROM `facebook` WHERE `user`='"
. $data['id']
. "' UNION
SELECT field1, field2, field3, field4, field5 FROM `twitter` WHERE some_condition "
);
Hope it helps

You would want to use a union
$orders = $db->QueryFetchArrayAll("SELECT id,url,
c_amount,amount,date,status FROM `facebook`
WHERE `user`='".$data['id']."'
join ORDER BY `date` DESC LIMIT 30
UNION
SELECT id,url,
c_amount,amount,date,status FROM `twitter`
WHERE `user`='".$data['id']."'
join ORDER BY `date` DESC LIMIT 30");

Related

Im always getting Call to a member function fetchAll() on boolean in

I'm always getting Call to a member function fetchAll() on boolean in, I'm using Microsoft Access I'm new at PDO so I don't know if I do it right
My Error:
Fatal error
: Uncaught Error: Call to a member function fetch() on boolean in C:\xampp\htdocs\newtimein_timeout\filter.php:46 Stack trace: #0 {main} thrown in
C:\xampp\htdocs\newtimein_timeout\filter.php
on line
46
<?php
$dbName = 'C:\xampp\htdocs\newtimein_timeout\att2000.mdb';
if (!file_exists($dbName)) {
die("Could not find database file.");
}
$connect = new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb)}; Server=localhost;
Port=3306; DBQ=$dbName; Uid=; Pwd=;");
$output = '';
$query = "select a.USERID, a.CHECKTIME, a.CHECKTYPE, b.Name,
b.Badgenumber,date_format(a.CHECKTIME, '%Y-%m-%d') as Date,
(CASE
WHEN date_format(c.CHECKTIME, '%h:%i:%s') IS NULL THEN '--:--:--'
ELSE date_format(c.CHECKTIME, '%h:%i:%s')
END) as start_time,
(CASE
WHEN date_format(d.CHECKTIME, '%h:%i:%s') IS NULL THEN '--:--:--'
ELSE date_format(d.CHECKTIME, '%h:%i:%s')
END) as break_out,
(CASE
WHEN date_format(e.CHECKTIME, '%h:%i:%s') IS NULL THEN '--:--:--'
ELSE date_format(e.CHECKTIME, '%h:%i:%s')
END) as break_in,
(CASE
WHEN date_format(f.CHECKTIME, '%h:%i:%s') IS NULL THEN '--:--:--'
ELSE date_format(f.CHECKTIME, '%h:%i:%s')
END) as end_time
from checkinout a
left join (select USERID, CHECKTIME from checkinout where CHECKTYPE='I') c
ON a.USERID=c.USERID AND date_format(a.CHECKTIME, '%Y-%m-%d')=date_format(c.CHECKTIME, '%Y-%m-%d')
left join (select USERID, CHECKTIME from checkinout where CHECKTYPE='0') d
ON a.USERID=d.USERID AND date_format(a.CHECKTIME, '%Y-%m-%d')=date_format(d.CHECKTIME, '%Y-%m-%d')
left join (select USERID, CHECKTIME from checkinout where CHECKTYPE='1') e
ON a.USERID=e.USERID AND date_format(a.CHECKTIME, '%Y-%m-%d')=date_format(e.CHECKTIME, '%Y-%m-%d')
left join (select USERID, CHECKTIME from checkinout where CHECKTYPE='O') f
ON a.USERID=f.USERID AND date_format(a.CHECKTIME, '%Y-%m-%d')=date_format(f.CHECKTIME, '%Y-%m-%d')
left join userinfo b
ON a.USERID=b.USERID
WHERE a.USERID > 0";
if(!empty($_POST["name"])){
$query .= " AND b.Name like '%".$_POST["name"]."%' ";
}
if(!empty($_POST["from_date"]) && (!empty($_POST["to_date"])) ) {
$query .= " AND date_format(a.CHECKTIME, '%Y-%m-%d') BETWEEN '".$_POST["from_date"]."' AND '".$_POST["to_date"]."' ";
}
$query .= " GROUP BY Date";
$result = $connect->query($query);
if ($row = $result->fetchAll()){
echo '<div style="font-size:18px;" class="col-sm-12"><b>ID NUMBER:</b> ' . $row['Name'] . '</div>';
echo '<div style="font-size:18px;" class="col-sm-12"><b>EMPLOYEE NAME:</b> ' . $row['Badgenumber'] . '</div>';
}
$output .= '
<table class="table table-striped table-bordered">
<thead class="thead-dark">
<tr>
<th style="width:220px">Date</th>
<th>Time In</th>
<th>Break Out</th>
<th>Break In</th>
<th>Time Out</th>
</tr>
</thead>
';
if($result->fetchColumn() > 0)
{
while($row = $result->fetchAll())
{
$date=date_create($row['CHECKTIME']);
$dDate = date_format($date,"M d, Y (D)");
$output .= '
<tr>
<td>'. $dDate .'</td>
<td>'. $start_time .'</td>
<td>'. $break_out .'</td>
<td>'. $break_in .'</td>
<td>'. $end_time .'</td>
</tr>
';
}
}
else
{
$output .= '
<tr>
<td colspan="5">No Data Found</td>
</tr>
';
}
$output .= '</table>';
echo $output;
?>

Student Attendance Report within a PIVOT Table

I am trying to record the attendance of my students that attend my courses. Courses are different lengths and times and I just need to record if a student is (P)resent (L)ate (A)sent. I record the attendance in 1 table and display the records in a pivot table based on the date attended. I am a newby and just can't workout this code to include all the details I need to show. id, bid, fullname, nickname, company_idno, (P)(L)(A).
Please could someone look at my code and tell me how to add this information to the pivot table.
This is what I want to show
This is where I store the information
This is table1
This is table2
At the moment I achieved the look I want but use 2 tables and use CSS to fix the widths of table 1 and place table 2 next to it.
I realize this is terrible practice and of course, I get odd results across different platforms, especially iOS which put a 47px gap between the 2 tables which I can't seem to remove also.
I want just want table 2 to show all the information. I can only show 3 fields, id, date, pla. How to add fullname, nickname and company_idno ??
Table 1
<table id="tblplanames" >
<td id="tdplabc">sid</td>
<td id="tdplabc">bid</td>
<td id="tdplacid" style="text-align: center">Cid</td>
<td id="tdplafn" style="text-align: center">Fullname</td>
<td id="tdplann" style="text-align: center">Nickname</td>
<?php
$sql13="SELECT * FROM students WHERE classno='$id' ORDER BY bluecard_no ASC ";
$sql_row13=mysqli_query($link,$sql13);
while($sql_res13=mysqli_fetch_assoc($sql_row13)) {
$stsid=$sql_res13["id"];
$stidno=$sql_res13["company_idno"];
$stbluecard_no=$sql_res13["bluecard_no"];
$stfullname=$sql_res13["fullname"];
$stnickname=$sql_res13["nickname"];
?>
<tr>
<td id="tdplabc"><a href=edit_student.php?id=<?php echo $stsid ?>><?php echo $stsid; ?></td>
<td id="tdplabc"><a href=edit_student.php?id=<?php echo $stsid ?>><?php echo $stbluecard_no; ?></td>
<td id="tdplacid"><a href=edit_student.php?id=<?php echo $stsid ?>><?php echo $stidno; ?></td>
<td id="tdplafn"><a href=edit_student.php?id=<?php echo $stsid ?>><?php echo $stfullname; ?></td>
<td id="tdplann"><a href=edit_student.php?id=<?php echo $stsid ?>><?php echo $stnickname; ?></td>
</tr>
<?php
}
?>
</table>
Table 2
<?php
$id = $_GET['id'];
$sql = "SELECT DISTINCT date
FROM attendance
WHERE classno = $id
ORDER BY DATE";
$res = $link->query($sql); // mysqli query
while ($row = $res->fetch_row()) {
$dates[] = $row[0];
}
/***********************************
* Table headings *
************************************/
$emptyRow = array_fill_keys($dates,'');
// format dates
foreach ($dates as $k=>$v) {
$dates[$k] = date('d-M', strtotime($v));
}
$heads = "<table id='tblpla'>\n";
$heads .= "<tr><td>sid</td><td>" . join('</td><td>', $dates) . "</td></tr>\n";
/***********************************
* Main data *
************************************/
$sql = "SELECT date, sid, pla, bluecard_no
FROM attendance
WHERE classno = $id
ORDER BY bluecard_no";
$res = $link->query($sql);
$sid='';
$tdata = '';
while (list($d, $sn, $s, $bcn) = $res->fetch_row()) {
if ($sid != $sn) {
if ($sid) {
$tdata .= "<tr><td>$sid</td><td>" . join('</td><td>', $rowdata). "</td></tr>\n";
}
$rowdata = $emptyRow;
$sid = $sn;
}
$rowdata[$d] = $s;
}
$tdata .= "<tr><td>$sid</td><td>" . join('</td><td>', $rowdata). "</td></tr>\n";
$tdata .= "</table\n";
echo $heads;
echo $tdata;
?>
SELECT c.olumns
, y.ou
, a.ctually
, w.ant
FROM students s
JOIN attendance a
ON a.classno = s.classno
WHERE s.classno = :id
ORDER
BY s.bluecard_no ASC
, a.date";
public function get_members_for_attendence()
{
$date = $this->input->post('choose_date');
$sql = 'SELECT a.date, c.member_name,c.member_join_date,c.member_payment_date,c.member_exp_date,c.member_payment_date,c.member_contact, c.member_reg_id,
CASE
WHEN a.status = "absent" THEN "Absent"
WHEN a.status = "present" THEN "Present"
ELSE "Not Taken"
END as attendence_status
FROM member_reg AS c
LEFT JOIN attendence AS a ON a.member_reg_id = c.member_reg_id AND a.date = "'.$date.'"';
$query = $this->db->query($sql);
return $query->result();
}
For CodeIgniter 3
it worked for me

Create HTML table based on Database Values

I have a database that has information on actors, roles, and movies.
On an HTML page I have the user input the first name and last name of an actor.
This form is then submitted to my PHP page where I look through my database, and provide the user with a 3 column html table with the following information: Movie Name the actor has worked in, Role the actor played, and year of movie.
All these information are in separate database tables. Examples of what each table looks like is below:
actor table contains:
'id', 'first_name', 'last_name', and 'gender' stored in the following way - (933,'Actor','Name','M')
role table contains:
'actor_id', 'movie_id', 'role stored in the following way - (16844,10920,'Role')
movies table contains:
'id', 'name', 'year', 'rank' stored in the following way - (306032,'Snatch.',2000,7.9)
I have to look through and correlate all the data into a table. This is what I have so far:
$sql ="SELECT id, first_name, last_name FROM actors";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result)) {
if ($row['first_name'] == $firstname && $row['last_name'] == $lastname) {
$actorID = $row['id'];
echo "$actorID<br>";
}
}//end while
$sql2 = "SELECT actor_id, movie_id, role FROM roles";
$result2 = mysql_query($sql2);
while ($row=mysql_fetch_array($result2)) {
if ($row['actor_id'] == $actorID) {
$movieID = $row['movie_id'];
$actRole = $row['role'];
echo "$movieID <br>";
echo "$actRole <br>";
}
} //end while
$sql3 = "SELECT id, name, year FROM movies";
$result3 = mysql_query($sql3);
while ($row=mysql_fetch_array($result3)) {
if ($row['id'] == $movieID) {
$movieName = $row['name'];
$movieYear = $row['year'];
echo "$movieName <br>";
echo "$movieYear <br>";
}
} //end while
echo '
<table>
<thead>
<tr>
<th> Movie Name </th>
<th> Actor Role </th>
<th> Release Date </th>
</tr>
</thead>
<tbody>
<td>'. $movieName .'</td>
<td>'. $actRole. '</td>
<td>'. $movieYear. '</td>
</tbody>
</table>';
?>
My solution works -- just a mediocre way of doing it
You don't have assign the variables $firstname and $lastname. Apart from that your if condition is wrong true every time.
if ($row['first_name'] = $firstname && $row['last_name'] = $lastname) {
Should be:
if ($row['first_name'] == $firstname && $row['last_name'] == $lastname) {
Also check what you want to do with the echo $row['first_name'][0];
Note that mysql_* functions are deprecated so you better use mysqli or PDO.
EDIT:
You can select all actors that have play in a movie using the following query. You can adjust to take only the information you need changing SELECT clause or using WHERE.
$sql = "
SELECT aa.id AS actor_id, aa.first_name, aa.last_name, cc.name, cc.year
FROM actor AS aa
INNER JOIN role AS bb
ON aa.id = bb.actor_id
INNER JOIN movies AS cc
ON cc.id = bb.movie_id";
EDIT 2: (from comments)
You can use the following code:
$conn = mysqli_connect("localhost", "db_username", "your_password", "your_database");
$query = "
SELECT aa.id AS actor_id, aa.first_name, aa.last_name, cc.name AS movie_name, cc.year AS release_year
FROM actor AS aa
INNER JOIN role AS bb
ON aa.id = bb.actor_id
INNER JOIN movies AS cc
ON cc.id = bb.movie_id";
$result = mysqli_query($conn, $query);
echo '
<table>
<thead>
<tr>
<th>Actor id</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Movie name</th>
<th>Release date</th>
</tr>
</thead>
<tbody>';
while($row = mysqli_fetch_array($result)) {
echo '<td>'.$row['actor_id'].'</td>';
echo '<td>'.$row['first_name'].'</td>';
echo '<td>'.$row['last_name'].'</td>';
echo '<td>'.$row['movie_name'].'</td>';
echo '<td>'.$row['release_year'].'</td>';
}
echo '
</tbody>
</table>';

PHP/MYSQL - "ORDER BY" Doesn't work

I have a table with a bunch of users who have a certain amount of points. I would like to arrange the users from highest points first to the lowest. However ORDER BY PTS DESC doesn't work.
<tr>
<th id="users_th1"><img src="<?php echo mysql_result($r_TEAMS, $i, 'LOGO'); ?>"/> <p><?php echo mysql_result($r_TEAMS, $i, 'NAME'); ?></p></th>
<th id="users_th2">Points Value</th>
</tr>
<?php
$q_users = 'Select * from POINTS LEFT JOIN USERS on USERS.UID = POINTS.UID where TID = '.mysql_result($r_TEAMS, $i, 'TID');
$r_users = mysql_query($q_users, $connection) or die(mysql_error());
$n_users = mysql_num_rows($r_users);
for($k = 0; $k <$n_users; $k++){
?>
<tr>
<td class="person"><?php echo mysql_result($r_users, $k, 'NAME'); ?></td>
<td><?php echo mysql_result($r_users, $k, 'POINTS.PTS'); ?></td>
</tr>
<?php
}
}
This is just guesswork, but I see you're doing a JOIN between the table USER and the table POINTS. Perhaps you have a field called PTS in both tables, so if you want to order the results by that field you should indicate to which table the one you're referring to belongs.
So, do it this way,
$q_users = "
SELECT *
FROM POINTS
LEFT JOIN USERS
ON USERS.UID = POINTS.UID
WHERE <table name>.TID = " . mysql_result($r_TEAMS, $i, 'TID') . "
ORDER BY <table name>.PTS DESC";
Did you try:
$q_users = 'Select * from POINTS LEFT JOIN USERS on USERS.UID = POINTS.UID where TID = '.mysql_result($r_TEAMS, $i, 'TID').' ORDER BY PTS DESC;';
You could also write if it won't sort or if it won't query.

display php / mysql column output as rows

I have the below syntax that is used to display a MySQL query in PHP:
function get_dayssincecapture($db)
{
$result = $db->query("SELECT DATEDIFF(now(), sarrive)as days,count(loadnumber) as loads from v2loads where adminstatus='captured' group by DATEDIFF(now(), sarrive) ");
return $result;
}
$dayssincecapture = get_dayssincecapture($db);
Display Syntax:
<table border=1>
<tr>
<? while($row = $dayssincecapture->fetch(PDO::FETCH_ASSOC)) { ?>
<td><? echo $row['days']; ?><br><? echo $row['loads']; ?></td>
<? } ?>
</tr>
</table>
this produces the below screen output
How do I alter by table syntax in order to get the days field as a row heading and the load field as the second row of my table?
so what I want will be:
Thanks as always,
Try with:
<?php
$dayssincecapture = get_dayssincecapture($db);
$data = array('days' => array(), 'loads' => array());
while($row = $dayssincecapture->fetch(PDO::FETCH_ASSOC)) {
$data['days'][] = $row['days'];
$data['loads'][] = $row['loads'];
}
?>
<table style="border: 1px solid #000">
<tr>
<td>Days</td>
<?php foreach ( $data['days'] as $day ) { ?>
<td><?php echo $day; ?></td>
<?php } ?>
</tr>
<tr>
<td>Loads</td>
<?php foreach ( $data['loads'] as $load ) { ?>
<td><?php echo $load; ?></td>
<?php } ?>
</tr>
</table>
If you wanted to perform this type of transformation in MySQL, then you will be pivoting the data. MySQL does not have a pivot function but you can replicate this using an aggregate function with a CASE statement:
select
count(case when DATEDIFF(now(), sarrive) = 1 then loadnumber end) as Day_1,
count(case when DATEDIFF(now(), sarrive) = 2 then loadnumber end) as Day_2,
count(case when DATEDIFF(now(), sarrive) = 3 then loadnumber end) as Day_3,
count(case when DATEDIFF(now(), sarrive) = 4 then loadnumber end) as Day_4,
count(case when DATEDIFF(now(), sarrive) = 5 then loadnumber end) as Day_5,
count(case when DATEDIFF(now(), sarrive) = 6 then loadnumber end) as Day_6,
count(case when DATEDIFF(now(), sarrive) = 7 then loadnumber end) as Day_7
from v2loads
where adminstatus='captured'
You can also write this code inside of a prepared statement to create this dynamically since the values will be unknown.
You can try:
<?php
while($row = $dayssincecapture->fetch(PDO::FETCH_ASSOC)) {
$days_row .= "<td>" . $row['days'] . "</td>";
$loads_row .= "<td>" . $row['loads'] . "</td>";
}
?>
<table>
<tr>
<td>Days</td>
<?php echo $days_row; ?>
</tr>
<tr>
<td>Loads</td>
<?php echo $loads_row; ?>
</tr>
</table>

Categories