How to show data category wise using MySQl - php

This is mySQL Fiddle I am trying to show data in DataTables using this query but if I want to show data accordingly with each brand wise and category wise. What should I change in this query?
$q = intval($_POST['Name']);
$time = strtotime($_POST['Date']);
$day = date('d',$time);
$month = date('m',$time);
$year = date('Y',$time);
$query = "
SELECT d.distributor_name
, s.order_date
, p.product_name
, s.nsp
, s.current_sales
, s.closing_balance
FROM sales s
LEFT
JOIN product p
ON p.product_id = s.product_id
LEFT
JOIN distributor d
ON s.d_id = d.d_ID
WHERE MONTH(s.order_date) = '" . $month . "'
AND YEAR(s.order_date) = '" . $year . "'
AND d.d_id = '" . $q . "';
";
$result = $connect->query($query);
$array = array();
while ($row = mysqli_fetch_assoc($result)) {
$array['data'][] = $row;
}
echo json_encode($array);
$connect->close();

Related

Print column value if one column name is same in all tables using left join

How to echo any column value by using LEFT JOIN method where one column name is common in all the tables used in select query? Below in my code. I want to get 'app_id' value along with all the columns, but 'app_id' doesn't print anything. app_id column is available in all 4 tables used in this query. It prints all the rows that i want to show but app_id does not return any value.
<?php
session_start();
include('../../connect.php');
$date = strtotime("+1 day", time());
$cdate = strtotime("-7 day", time());
$finaldate = date('Y-m-d', $date);
$scdate = date('Y-m-d', $cdate);
//$sql = "SELECT * FROM tblapps WHERE journeydate >= '".$finaldate."' AND appstatus = 'On-Hold' AND process = 'yes'";
$sql = "SELECT * from tblapps
LEFT JOIN tblapps2 ON tblapps.app_id = tblapps2.app_id
LEFT JOIN tblapps3 ON tblapps.app_id = tblapps3.app_id
LEFT JOIN payments ON tblapps.app_id = payments.app_id
WHERE
tblapps.journeydate >= '$finaldate' AND tblapps.appstatus = 'On-Hold' AND tblapps.process = 'yes'";
$result = $connect->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["app_id"]. " - Name: " . $row["firstname"]. " " . $row["journeydate"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>

PHP MYSQL full join between two table using dates

Hiii i have two diffrent tables
staff_rotas (id,staff_id, startDateTime, endDateTime, rota_minutes, status)
staff_login (id,staff_id, actual_startDateTime,actual_endDateTime,shift_minutes, status);
I want to fetch data from both table where date between e.g (21-11-2016 to 27-11-2016) and output something like this
Timesheet
I have tried following query pls check.
<?php
$staff_data = mysql_query("SELECT * FROM staff_rotas LEFT JOIN staff_login ON
(DATE(staff_rotas.startDateTime) = DATE(staff_login.actual_startDateTime))
WHERE staff_rotas.staff_id = '123' AND DATE_FORMAT(staff_rotas.startDateTime,'%Y-%m-%d')
BETWEEN '" . $date_from . "' AND '" . $date_to . "'
UNION
SELECT * FROM staff_rotas RIGHT JOIN staff_login ON (
DATE(staff_login.actual_startDateTime) = DATE(staff_rotas.startDateTime))
WHERE staff_login.staff_id = '123' AND
DATE_FORMAT(staff_login.actual_startDateTime,'%Y-%m-%d') BETWEEN '" . $date_from . "' AND '" . $date_to . "'
ORDER BY `startDateTime` DESC")
while($data = mysql_fetch_object($staff_data)){
/*html table to show data ......
...
...
*/
}
?>

PHP MySQL $_POST

I am trying to create a PHP form using MySQL database.
I have created a dropdown list with the names of samples (like Al, Au...) and a textbox for the values.
My problem that the units are in my database sometimes in ppm, sometimes in pph.
How can I set if the values are in pph, use the $value=$_POST["value"]/10000;
if the values are in ppm, use $value=$_POST["value"]?
Any idea?
My code:
<?php
if (isset($_POST["sample"]))
{
$sample = $_POST["sample"];
$unit = mysql_query("SELECT unit FROM analysis where sample='" . $sample . "'");
if ($unit == 'pph')
{
$value = $_POST["value"] / 10000;
$sql = "SELECT
a.sample,
concat (a.modif, (IF (unit='pph',10000*value,value))),
a.method,
a.mkey,
b.name,
b.from,
b.to,
b.type
FROM
anlysis a,
sample b
WHERE
a.mkey=b.mkey AND sample = '$sample' AND value > '$value'";
$result = mysql_query($sql);
}
else
{
$value = $_POST["value"];
$sql = "SELECT
a.sample,
concat ( a.modif, ( IF (unit = 'pph', 10000 * value, value) ) ),
a.method,
a.mkey,
b.name,
b.from,
b.to,
b.type
FROM
anlysis a,
sample b
WHERE
a.mkey = b.mkey AND sample = '$sample' AND value > '$value'";
$result = mysql_query($sql);
}
}
Thank you!
Here's what I'd suggest:
<?php
if (isset($_POST["sample"])) {
$sample = htmlspecialchars(trim($_POST["sample"])); //A little clean-up wont hurt...
$unit = mysql_query("SELECT unit FROM analysis where sample='" . $sample . "'");
if ($unit == 'pph'){
$postVal= htmlspecialchars(trim($_POST["value"]));
$value = $postVal / 10000;
$sql = "SELECT a.sample,
concat (a.modif, (IF (unit='pph',10000*value, value))),
a.method,
a.mkey,
b.name,
b.from,
b.to,
b.type
FROM
analysis AS a
LEFT JOIN sample AS b
ON a.mkey=b.mkey
WHERE
a.sample='" . $sample . "' AND a.value > '" . $value ."'";
$result = mysql_query($sql);
}
else
{
$postVal= htmlspecialchars(trim($_POST["value"]));
$value = $postVal;
$sql = "SELECT
a.sample,
concat ( a.modif, ( IF (unit = 'pph', 10000 * value, value) ) ),
a.method,
a.mkey,
b.name,
b.from,
b.to,
b.type
FROM
analysis AS a
LEFT JOIN sample AS b
ON a.mkey=b.mkey
WHERE
a.mkey = b.mkey AND sample = '" . $sample . "' AND value > '" . $value . "'";
$result = mysql_query($sql);
}
first
$analysis = mysql_fetch_object($query);
then you can access the value
if ($analysis->unit == 'pph')

variable as SELECT constraint

I am setting a variable that contains an array as a constraint to a SELECT sql statement. However the constraint seems only to apply to one piece of data in the array. Why is this?
Code below:
<?php
include 'connection.php';
$Date = $_POST['date'];
$Unavail = 0;
$Avail = 0;
$Availid = 0;
$low = 99999;
$query = "SELECT username FROM daysoff WHERE date = '$Date'";
$dayresult = mysql_query($query);
while($request = mysql_fetch_array($dayresult)) {
$Unavail = $request;
echo "<span>" . $Unavail['username'] . " is unavailable.</br>";
}
$query1 = "SELECT Username, name, work_stats FROM freelance WHERE Username != '$Unavail[username]'";
$dayresult1 = mysql_query($query1);
while($request1 = mysql_fetch_array($dayresult1)) {
echo "<span>" . $request1['name'] . " is available.</br>";
if ($request1['work_stats']<=$low) {
$low = $request1['work_stats'];
$Availid = $request1['name'];
}}
echo "<span>" . $Availid . " is available on " . $_POST['date'] . " and is on workstat level " . $low . ".</span></br>";
?>
The output shows two names in the first echo but then shows one of those names as available in the second echo (these echos are only in place as part of my testing),
Many Thanks
The first query can have multiple results.
SELECT username FROM daysoff WHERE date = '$Date'
Let's say if gives two rows: Dave and John.
You're only keeping the last record so it will seem like Dave is available.
You should probably do something like:
$query = "SELECT username FROM daysoff WHERE date = '$Date'";
$dayresult = mysql_query($query);
$unavailable_users = array();
while($request = mysql_fetch_array($dayresult)) {
$unavailable_users[] = $request["username"];
echo "<span>" . $Unavail['username'] . " is unavailable.</br>";
}
$query1 = "SELECT Username, name, work_stats FROM freelance
WHERE NOT Username IN ('" . implode("','", $unavailable_users) . "')";
// etc
Or in one go with a LEFT JOIN:
SELECT `Username`, `name`, `work_stats`
FROM `freelance`
LEFT JOIN `daysoff` ON `freelance`.`Username` = `daysoff`.`username`
AND `daysoff`.`date` = '$Date'
WHERE
`daysoff`.`username` IS NULL

php for each loop not functioning

I am attempting to clean up a database table that might be missing book titles or bio information. The user is supposed to be able to click a button and the program does the rest.
I have run the query in my database and it returns the information I am looking for, so i think my issue is with the for each loop.
Here is my code:
<?php
require_once ('../db.php');
require_once ('../amazon/amazon.php');
$conn = db_connect();
session_start();
$x = 0;
// find all of the books with no Titles or Bios
$result = $conn->query("
select
i.date_created,
users.username,
i.sku,
i.isbn13,
i.quantity,
source.source,
i.date_process,
location.location
from inventory i
left join book on i.isbn13 = book.isbn13
left join source on i.source_id = source.source_id
left join location on i.location_id = location.location_id
left join users on i.created_by = users.user_id
where sku > '10000000'
and quantity >= 1
and (book.title = ''
or book.title is null
or book.author = ''
or book.author is null)
and i.isbn13 >1");
$num_rows = $result->num_rows;
if($num_rows > 0)
{
while($row = $result->fetch_assoc()) {
$isbnArray[$x] = $row['isbn13'];
$qtyArray[$x] = $row['quantity'];
$x++;
} // end of while loop
$sum = array_sum($qtyArray);
for each ($isbnArray as $isbn)
{
//retrieve amazon data
$parsed_xml = amazon_xml($isbn);
$amazonResult = array();
$current = $parsed_xml->Items->Item;
if($parsed_xml->Items->Request->IsValid == 'True') {
$amazonResult = array(
'Title' => $current->ItemAttributes->Title,
'Author' => $current->ItemAttributes->Author,
'Edition' => $current->ItemAttributes->Edition,
'Weight' => ($current->ItemAttributes->PackageDimensions->Weight / 100),
'Publisher' => $current->ItemAttributes->Publisher,
'PublishDate' => $current->ItemAttributes->PublicationDate,
'Binding' => $current->ItemAttributes->Binding,
'SalesRank' => $current->SalesRank,
'ListPrice' => str_replace('$','',$current->ItemAttributes->ListPrice->FormattedPrice),
'ImageURL' => $current->LargeImage->URL,
'DetailURL' => $current->DetailPageURL
);
} // end of if statement
//update Title and Bio info in book table
$conn->query("
update book
set isbn13 = '$isbn',
author = '" . $amazonResult['Author'] . "',
title ='" . $amazonResult['Title'] . "',
edition = '" . $amazonResult['Edition'] . "',
weight = '" . $amazonResult['Weight'] . "',
publisher = '" . $amazonResult['Publisher'] . "',
binding = '" . $amazonResult['Binding'] . "',
listed_price = '" . $amazonResult['ListPrice'] . "',
pub_date = '" . $amazonResult['PublishDate'] . "'
WHERE isbn13 = '$isbn'");
} // end of for each loop
}
$message = array( 'message' => $sum.' Records were updated' );
$conn->close();
echo json_encode($message);
?>
To me everything looks right, but when I run it with firebug on, there is no message. Console.log(data) in my success function says empty string.
What am I doing wrong? Should I restructure my for each loop?
EDIT: I changed parts of the code to get an accurate count of how many records were updated. This is the $qtyArray[$x] = $row['quantity'] line. My console.log(data) shows that 2995 records were updated, but the #message does not appear on the screen, just the console.log(data). Hope this gives a little more insight.
Your error may lie in your while loop:
while($row = $result->fetch_assoc()) {
$isbnArray[$x] = $row['isbn13'];
$sum = array_sum($isbnArray);
} // end of while loop
$x is initialized to 0, and never changed, so you just overwrite the same entry in the array each time.
You have to change:
$isbnArray[$x] = $row['isbn13'];
to:
$isbnArray[] = $row['isbn13'];
You need to escape your " in your query
$result = $conn->query("
select
i.date_created,
users.username,
i.sku,
i.isbn13,
i.quantity,
source.source,
i.date_process,
location.location
from inventory i
left join book on i.isbn13 = book.isbn13
left join source on i.source_id = source.source_id
left join location on i.location_id = location.location_id
left join users on i.created_by = users.user_id
where sku > '10000000'
and quantity >= 1
and (book.title = \"\"
or book.title is null
or book.author = \"\"
or book.author is null)
and i.isbn13 >1");

Categories