Get variable in sql statment and use in php - php

The function below generates a table like the image below.
The location_id is being accessed but I would like to use this ID again at the bottom of the table in a link. See the LOCATION_ID at the bottom of the function.
Im not sure how to do this.
function countAppointment2() {
require 'config.php';
$data = array();
$date_list= array();
$sql_date_list ="SELECT start_date from appointment GROUP BY start_date";
$result_date_list = mysqli_query($conn, $sql_date_list);
$sql_loc_list = "SELECT `name` FROM `location` GROUP BY `name`";
$result_loc_list = mysqli_query($conn, $sql_loc_list);
$k=0;
while ($row =mysqli_fetch_assoc($result_loc_list)){
$data +=[$row['name']=>array()];
if($k==0){
while($row2 =mysqli_fetch_assoc($result_date_list)){
array_push($date_list,$row2['start_date']);
$data[$row['name']]+=[$row2['start_date']=>0];
}
$k++;
}else{
foreach($date_list as $date){
$data[$row['name']]+=[$date=>0];
}
}
}
$sql_getdata = "SELECT t2.name as loc_name, t1.start_date,t1.location_id, COUNT(t1.location_id) AS count FROM appointment t1 JOIN location t2 ON t1.location_id = t2.id GROUP BY t1.location_id,t1.start_date";
$result = mysqli_query($conn, $sql_getdata);
while($row =mysqli_fetch_assoc($result)){
$data[$row['loc_name']][$row['start_date']]=$row['count'];
}
$table="<table class='table table-bordered'>";
$table.="<thead><tr>";
$table.="<th>Dealership Location</th>";
foreach ($date_list as $date) {
$edate = date("d/m/Y", strtotime($date));
$table.="<th>".$edate."</th>";
}
$table.="</tr></thead>";
foreach ($data as $key=>$date) {
$table.="<tbody><tr>";
$table.="<td>".$key."</td>";
foreach($date as $key2=>$count){
$table.="<td>".$count."</td>";
}
$table.="</tr>";
}
$table.="</tbody></table>";
echo $table;
}

Change
$data[$row['loc_name']][$row['start_date']]=$row['count'];
to
$data[$row['loc_name']][$row['start_date']] = [
'count' => $row['count'],
'location_id' => $row['location_id']
];
Then replace the code in the loop to:
$table.="<td>".$count['count']."</td>";
Essentially changing it from a single value to an array.

Related

Display table count in html

I trying to create the backend for a booking system and need to show all booked appointments on each date for each location. My appointments table looks like this:
id, booked_date, location_id, customer_id
and I would like to display this in a html table like this:
Date 1
Date 2
Location 1 Name
Number of booked appointments
Number of booked appointments
Location 2 Name
Number of booked appointments
Number of booked appointments
I have a separate table of Locations that has full details like and and address.
I also have a table of event dates (id, start_date)
Im struggling to comprehend what I need to do here!
EDIT:
I just need some help putting everything together into the example table above.
Database tables : appointments, locations, event_dates
I have this query and the function below - SELECT t1.location_id, t1.start_datetime, t2.name, COUNT(*) AS count FROM appointment t1 INNER JOIN location t2 ON t1.location_id = t2.id GROUP BY t1.location_id, t1.start_datetime
function countAppointment() {
require 'config.php';
$sql = "SELECT t1.location_id, t1.start_datetime, t2.name, COUNT(*) AS count
FROM appointment t1
INNER JOIN location t2
ON t1.location_id = t2.id
GROUP BY t1.location_id, t1.start_datetime";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$a1 = $row['start_datetime'];
$a2 = $row['location_id'];
$a3 = $row['name'];
$a4 = $row['count'];
//echo "$a1 <br> $a2 <br> $a3 <br> $a4 <br><br>";
echo "<tr><th scope='row'>$a3</th>";
echo "<td><a href='#'>$a4</a></td>";
echo "<td>9</td><td>27</td><td>14</td></tr>";
}
} else {
return "0";
}
$conn->close();
}
try this code
<?php
$con = new mysqli("localhost","root","","test");
// Check connection
if ($con -> connect_errno) {
echo "Failed to connect to MySQL: " . $con -> connect_error;
exit();
}
$data = array();
$date_list= array();
$sql_date_list ="SELECT start_datetime from appointment GROUP BY start_datetime";
$result_date_list = mysqli_query($con, $sql_date_list);
$sql_loc_list = "SELECT `name` FROM `location` GROUP BY `name`";
$result_loc_list = mysqli_query($con, $sql_loc_list);
$k=0;
while ($row =mysqli_fetch_assoc($result_loc_list)){
$data +=[$row['name']=>array()];
if($k==0){
while($row2 =mysqli_fetch_assoc($result_date_list)){
array_push($date_list,$row2['start_datetime']);
$data[$row['name']]+=[$row2['start_datetime']=>0];
}
$k++;
}else{
foreach($date_list as $date){
$data[$row['name']]+=[$date=>0];
}
}
}
$sql_getdata = "SELECT t2.name as loc_name, t1.start_datetime, COUNT(t1.location_id) AS count FROM appointment t1 JOIN location t2 ON t1.location_id = t2.id GROUP BY t1.location_id,t1.start_datetime";
$result = mysqli_query($con, $sql_getdata);
while($row =mysqli_fetch_assoc($result)){
$data[$row['loc_name']][$row['start_datetime']]=$row['count'];
}
$table="<table border='1'>";
$table.="<tr>";
$table.="<th>location</th>";
foreach ($date_list as $date) {
$table.="<th>".$date."</th>";
}
$table.="</tr>";
foreach ($data as $key=>$date) {
$table.="<tr>";
$table.="<td>".$key."</td>";
foreach($date as $key2=>$count){
$table.="<td>".$count."</td>";
}
$table.="</tr>";
}
$table.="<table>";
echo $table;
?>
output

while-Loop in foreach-Loop with mysqli_query leads to unexpected result

I have a pice of code to get data from a mysql database. I need to build containers for all stations with the same station_group which I do via a foreach loop. Inside the foreach-loop, there is a while loop to fill the station group containers with all the stations that have the parents station_group. The code works fine if I have debbugging echo lines in the code (so some kind of delay), but having them commented out, the code delivers wrong order of containers and stations. I gues its because of the asynchronous function fetch_assoc so I might put in a callback function, but I just don't get it runnig. Therefore I would appriciate any help... =)
BR
<?php
//build unique Station group array
$sql_unique = "SELECT DISTINCT station_group FROM station ORDER BY station_group ASC";
$unique_station_groups = mysqli_query($dbConn, $sql_unique);
//get all station data
$sql = "SELECT * FROM station ORDER BY station_group, station_id ASC";
$result= mysqli_query($dbConn, $sql);
//Loop for station_group
foreach ($unique_station_groups as $station_group_value){
echo '<div class="css-station-group>';
while ($row = mysqli_fetch_assoc($result)) {
//echo "<script>console.log(".json_encode($station_group_value).")</script>";
//echo "<script>console.log(".json_encode($row).")</script>";
$station_id = $row['station_id'];
$station_name = $row['station_name'];
$station_layout = $row['station_layout'];
$station_group = $row['station_group'];
if ($station_group_value['station_group']==$station_group) {
echo '<div class="station-container css_station-layout-'.$station_layout.
'" id='.$station_id.
'>'.$station_name.
'<br></div>';
}
}
echo '</div>';
mysqli_data_seek($result,0); //reset array, so next Loop will find values again
}
?>
You don't need two queries to do this.
Store the previous station_group and check the current_group and previous group to differentiate the stations.
Changed your code a bit
<?php
//build unique Station group array
// $sql_unique = "SELECT DISTINCT station_group FROM station ORDER BY station_group ASC";
// $unique_station_groups = mysqli_query($dbConn, $sql_unique);
//get all station data
$sql = "SELECT * FROM station ORDER BY station_group ASC";
$result= mysqli_query($dbConn, $sql);
$rows = [];
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
//Loop for station_group
// foreach ($unique_station_groups as $station_group_value) {
$current_station_group = null;
echo '<div class="css-station-group">';
foreach ($rows as $row) {
//echo "<script>console.log(".json_encode($station_group_value).")</script>";
//echo "<script>console.log(".json_encode($row).")</script>";
$station_id = $row['station_id'];
$station_name = $row['station_name'];
$station_layout = $row['station_layout'];
$station_group = $row['station_group'];
if ($station_group != $current_station_group) {
echo '<div class="station-container css_station-layout-'.$station_layout.
'" id='.$station_id.
'>'.$station_name.
'<br></div>';
$current_station_group = $row['station_group'];
}
}
echo '</div>';
?>
It looks like it might be easier to simply dump the results in an array then loop through the array.
<?php
//build unique Station group array
$sql_unique = "SELECT DISTINCT station_group FROM station ORDER BY station_group ASC";
$unique_station_groups = mysqli_query($dbConn, $sql_unique);
//get all station data
$sql = "SELECT * FROM station ORDER BY station_group, station_id ASC";
$result= mysqli_query($dbConn, $sql);
$rows = [];
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
//Loop for station_group
foreach ($unique_station_groups as $station_group_value){
echo '<div class="css-station-group>';
foreach ($rows as $row) {
//echo "<script>console.log(".json_encode($station_group_value).")</script>";
//echo "<script>console.log(".json_encode($row).")</script>";
$station_id = $row['station_id'];
$station_name = $row['station_name'];
$station_layout = $row['station_layout'];
$station_group = $row['station_group'];
if ($station_group_value['station_group']==$station_group) {
echo '<div class="station-container css_station-layout-'.$station_layout.
'" id='.$station_id.
'>'.$station_name.
'<br></div>';
}
}
echo '</div>';
}
?>

PHP chart diagram to display skipped entry

I'm trying to create a graph like this http://jsfiddle.net/9mmrbjt7/1/
I have a script created that will add the data to the graph. The date and the value is stored in db and it works just fine.
The php script counts the number of dates and uses it as a value and assign it to the date.
The problem is if someone miss one day it skips the value which I understand.
So how can I assign value zero to skipped day?
2014-07-23
2014-07-23 = 2,
2014-07-24 -> wasn't submitted so the 0 should be added to the graph with the date.
2014-07-25
2014-07-25
2014-07-25= 3,
php script
$user_curr_id = $_SESSION['user_id'];
$sql = mysqli_query($con,"SELECT * FROM rosary WHERE user_ids = $user_curr_id ORDER BY datum ASC");
$array1 = array();
while($row = mysqli_fetch_array($sql)){
$array1[] = '"' . $row['datum'] . '"';
}
$tags = implode(', ', array_unique(array_map('trim',explode(',',implode(',',$array1)))));
$sql = mysqli_query($con,"SELECT datum, COUNT(datum) cnt
FROM rosary
WHERE user_ids = $user_curr_id
GROUP BY datum;");
$result = array();
while ($row = mysqli_fetch_array($sql)) {
$result[] = $row['cnt']; // add the content of field cnt
}
in js script
labels : ["Start",<?php echo $tags; ?>] -> list the dates from db
data : [0,<?php echo implode(',', $result); ?>]-> list values from db
php:
$sql = mysqli_query($con,"SELECT datum, COUNT(datum) as cnt
FROM rosary
GROUP BY datum
ORDER BY datum ASC;");
$result = array();
$start = null;
$end = null;
while ($row = mysqli_fetch_array($sql)) {
$result['"'.$row['datum'].'"'] = $row['cnt'];
if(is_null($start)) $start = $row['datum'];
$end = $row['datum'];
}
$res_array = array();
if(!is_null($start)){
$i = strtotime($start);
while($i <= strtotime($end)){
$res_array['"'.date('Y-m-d',$i).'"'] = 0;
$i = strtotime("+1 day",$i);
}
}
foreach($result as $date => $val){
$res_array[$date] = $val;
}
in js script
labels : ["Start",<?php echo implode(',',array_keys($res_array)) ?>],
data : [0,<?php echo implode(',', array_values($res_array)); ?>],

select fields and group them in a category in php and mysql

i have a table with staff_id and subjects, i want to display all staffs according to their subjects.
my table
result i want
Physics
-001
-004
-006
Chemistry
-002
-009
Biology
-003
-008
Mathematics
-005
My code
$q = mysql_query("Select staff_id from my_table");
while($row = mysql_fetch_array($q)){
echo $subject .'</br>';
echo $staff_id.'</br>';
}
but this doesn't give the result i want.
any help?
What you need is ORDER BY.
Change your query to:
SELECT STAFF_ID, SUBJECT FROM my_table ORDER BY SUBJECT, STAFF_ID
So you get the records in the right order to work with them.
Something like this?
$q = mysql_query("SELECT `staff_id`, `subject` FROM `my_table`;");
$data = array();
while($row = mysql_fetch_array($q)){
$data[$row['subject']][] = '-'.$row['staff_id'];
}
print_r($data);
Or to echo out the rows
foreach($data as $heading => $rows){
echo $heading.'<br>';
foreach($rows as $row){
echo $row.'<br>';
}
}
You can write your code like this below:
$q = mysql_query("SELECT * FROM my_table ORDER BY SUBJECT, STAFF_ID");
while($row = mysql_fetch_array($q)){
//Do staff
}
The following code should help. You should split each subject into a separate array within your query. Once your query is complete, you should iterate through the subject array, and then within each staff id.
$subjects = array();
$q = mysql_query("Select staff_id from my_table");
while($row = mysql_fetch_array($q)){
if ($subjects[$row['SUBJECT']] == nil) {
$subjects[$row['SUBJECT']] = array();
}
array_push($subjects[$row['SUBJECT']], $row['STAFF_ID']);
}
foreach ($subjects as $key=>$value) {
echo $key . '<br>;
foreach ($vaue as &$staff) {
echo $staff . '<br>';
}
}
$result=mysql_query("SELECT * from table GROUP BY subject");
while($ext=mysql_fetch_object($result)) {
$query=mysql_query(" SELECT * from table WHERE subject='".$ext->subject."'");
echo $ext->subject;
while($res=mysql_fetch_object($query)) {
echo $res->staff_id;
}
}

some problems with in_array function

Hi I am trying to use in_array, I think my syntax is correct,
but it says "Wrong datatype for second argument"
My code is
$result = mysqli_query($con, "SELECT * FROM Products WHERE Quantity_On_Hand < Min_Stock");
$filter = mysqli_query($con, "SELECT ProductID FROM Orders");
while($row = mysqli_fetch_array($result))
{
if (in_array($row['ProductID'], $filter))
{
}
}
My idea is to find out if the ProductID from Products Table is in the Order Table.
Could someone helps me, Thanks :-)
$filter isn't an array; it's a mysqli_result object:
$filter = mysqli_query($con, "SELECT ProductID FROM Orders");
I think you want to iterate over that, add each ProductID to a new array, and then pass that array to the in_array function like so:
$filter = mysqli_query($con, "SELECT ProductID FROM Orders");
$product_ids = array();
while ($row = $filter->fetch_assoc())
{
$product_ids[] = $row['ProductID'];
}
$result = mysqli_query($con, "SELECT * FROM Products WHERE Quantity_On_Hand < Min_Stock");
while($row = mysqli_fetch_array($result))
{
if (in_array($row['ProductID'], $product_ids))
{
}
}
Your code is failing because $filter is a MySQLi result resource, not an array. Really, this is better accomplished with a simple inner join between the two tables. If a ProductID does not exist in Orders, the INNER JOIN will exclude it from the result set in the first place.
$sql = "
SELECT Products.*
FROM
Products
INNER JOIN Orders ON Products.ProductID = Orders.ProductID
WHERE Quantity_on_Hand < Min_stock";
$result = mysqli_query($con, $sql);
if ($result) {
$results = array();
while ($row = mysqli_fetch_array($result)) {
$results[] = $row;
}
}
// Now $results is a 2D array of all your Products
If instead you want to retrieve all the Products, and simply have an indication of whether it has an active order, use a LEFT JOIN and test if Orders.ProductID is null in the SELECT list:
$sql = "
SELECT
Products.* ,
/* No orders will print 'no-orders' in a pseudo column called has_orders */
CASE WHEN Orders.ProductID IS NULL THEN 'no-orders' ELSE 'has-orders' AS has_orders
FROM
Products
LEFT JOIN Orders ON Products.ProductID = Orders.ProductID
WHERE Quantity_on_Hand < Min_stock";
$result = mysqli_query($con, $sql);
if ($result) {
$results = array();
while ($row = mysqli_fetch_array($result)) {
$results[] = $row;
}
}
// Now $results is a 2D array of all your Products
// And the column $row['has_orders'] will tell you if it has any...
In this case, you may test in a loop over your rowset whether it has orders:
foreach ($results as $r) {
if ($r['has_orders'] == 'has-orders') {
// this has orders
}
else {
// it doesn't...
}
}

Categories