I got
for($i = $start_date;$start_date <= $end_date;$i->modify('+1 day')) {
$i->format('Y-m-d').'<br />';
$dates = $i->format('Y-m-d');
echo $query = "
SELECT md.dish_id
, md.daydate
, d.id
, d.dish_name
, d.weight
, d.price
FROM dishes d
LEFT
JOIN menu_details md
ON d.id = md.dish_id
WHERE md.daydate = '$dates'
";
$result = mysql_query($query);
}
while($row = mysql_fetch_array($result)) {
echo 'Date: '.$row['daydate'].'Name: '.$row['dish_name'].'<br />';
}
how can i row 'dish_name' for every date on a new row.In the database there are more then 1 row with same date=
You should try to avoid running queries in loops...
Try:
$query = "SELECT md.dish_id, md.daydate, d.id, d.dish_name, d.weight, d.price
FROM dishes d
LEFT JOIN menu_details md ON (d.id = md.dish_id)
WHERE md.daydate BETWEEN '$start_date' AND '$end_date'
GROUP BY md.daydate ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
echo 'Date: '.$row['daydate'].'Name: '.$row['dish_name'].'<br />';
}
What is the group by for? I think it may cause you to lose some of the results...
Related
include 'conn.php';
$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
$sort = isset($_POST['sort']) ? strval($_POST['sort']) : 'saleid';
$order = isset($_POST['order']) ? strval($_POST['order']) : 'desc';
$orderno = isset($_POST['orderno']) ? mysql_real_escape_string($_POST['orderno']) : '';
$offset = ($page-1)*$rows;
$result = array();
$where = "orderno like '$orderno%'";
$rs = mysql_query("select count(*) from tblsales where " . $where);
$row = mysql_fetch_row($rs);
$result["total"] = $row[0];
$rs = mysql_query("select *, sum(price+shipping+paypalfee+storefee) as totalcost from tblsales group by orderno where " . $where . " order by $sort $order limit $offset,$rows");
$items = array();
while($row = mysql_fetch_object($rs)){
array_push($items, $row);
}
$result["rows"] = $items;
echo json_encode($result);
Could you please change this query so that it returns all records in table while using WHERE clause so that I could search a particular record if needed. At the moment it does not return anything:
select *, sum(price+shipping+paypalfee+storefee) as totalcost
from tblsales
group by orderno
where " . $where . "
order by $sort $order
limit $offset,$rows
Try this
select *,sum(totalcost)
FROM (select *, price+shipping+paypalfee+storefee as totalcost from tblsales) x
group by orderno
where " . $where . "
order by $sort $order
limit $offset,$rows
I have a query set up to return comments given from one user to another.
Now we want to allow the ability to rate these comments.
I've added a new table that has 3 fields: comment_id, user_id, and score.
How can I grab an array of {user_id,score} for any comment fetched?
Will I need to loop through the comments after they are fetched and run a second query? This approach could result in adding several extra queries.
Can it be done with a single query?
Here's the function I have now:
function getAllComments($args) {
if(empty($_SESSION['user']['id'])) return false;
$limit = 5;
if(isset($args['limit'])) $limit = $args['limit'];
$page = 1;
if(isset($args['page'])) $page = $args['page'];
$data = array();
$offset = ($page-1)*$limit;
$sql = "SELECT c.*,CONCAT(u1.firstName,' ',u1.lastName) AS owner,u1.title AS ownerTitle,CONCAT_WS(' ',u2.firstName,u2.lastName) AS senderName,u2.title AS senderTitle,a.name AS actionName,a.behavior
FROM comment AS c
JOIN user AS u1 ON c.recipient = u1.id
JOIN user AS u2 ON c.sender = u2.id
JOIN action AS a ON c.action = a.id
WHERE c.type=1";
if(isset($args['location'])) $sql .= " AND u1.location=?";
$sql .= " ORDER BY date DESC";
$sql .= " LIMIT ?";
$sql .= " OFFSET ?";
try {
$db = DB::getInstance();
$stmt = $db->dbh->prepare($sql);
$n = 1;
//THESE MUST STAY IN THE SAME ORDER TO MATCH THE ? PLACEHOLDERS
if(isset($args['location'])) $stmt->bindValue(($n++), $args['location'], PDO::PARAM_INT);
$stmt->bindValue(($n++), $limit, PDO::PARAM_INT);
$stmt->bindValue(($n++), $offset, PDO::PARAM_INT);
$result = $stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$rows = array();
if($result !== false) {
while($row = $stmt->fetch()) {
$rows[] = $row;
}
$data['comments'] = $rows;
return $data;
}else {
logit('Query Failed');
return false;
}
}catch(PDOException $e) {
logit($e->getMessage());
return false;
}
}
If you for example wanted all {comment_id, user_id, score} associated with the comments of user 5, your query would involve an INNER JOIN and look something like:
SELECT s.comment_id, s.user_id, s.score FROM CommentScore s
INNER JOIN Comment c
ON c.comment_id = s.comment_id
WHERE c.user_id = 5
I have the following code and was wondering how I could simplify it into one MYSQL statement
$sql = "SELECT sesionID
FROM `juegos_sesiones`
WHERE `usuarioID` = ".$_SESSION['MM_UserID'];
$query = mysql_query($sql, $cnx) or die(mysql_error());
//$row_rsPaises = mysql_fetch_assoc($rsPaises);
$exercises = mysql_num_rows($query);
echo $exercises;
//find total points
while( $row = mysql_fetch_array($query)){
$sql2 = 'SELECT correct_answers FROM `juegos_sesiones_detalle` WHERE `sesionID` = '.$row['sesionID'];
$query2 = mysql_query($sql2, $cnx) or die(mysql_error());
$details2 = mysql_fetch_assoc($query2);
$counter = $counter + $details2['correct_answers'];
}
echo '<br />'.$counter;
SELECT sum(correct_answers) as total_correct_answers
FROM `juegos_sesiones_detalle` d
INNER JOIN `juegos_sesiones` s on s.`sesionID` = d.`sesionID`
WHERE `usuarioID` = $_SESSION['MM_UserID']
You can read about joins here
You can write single query by using INNER JOIN as:
SELECT correct_answers
FROM juegos_sesiones_detalle a
INNER JOIN juegos_sesiones b
ON a.sesionID = b.usuarioID;
Try this :
$sql = "SELECT correct_answers FROM `juegos_sesiones_detalle` jsd
JOIN `juegos_sesiones` js
ON jsd.sesionID = js.`sesionID`
WHERE js.usuarioID = ".$_SESSION['MM_UserID'];
select t1.CardID,t2.Description,t5.BioData
from db2.tblemployeeinfob t1
left join (db2.tbldepartments t2,db1.tblbiometrics t5)
on
(t1.Department = t2.DepartmentID and
t1.CardID=t5.CardID
)
Return Result is 1420 | (NULL) | (NULL)
Expected Result is 1420 | DB2_Description_Value | DB1_BioData_value
if i remove cross database join, like remove db1 then query will work fine to join remaining two tables from same database.
if i do cross database join between db1 and db2, even table t2 from same database db2 is returning NULL.
Where is problem with my Query, so i can get value from both databases.
You shouldn't be using a cross join here. You want two separate left joins:
SELECT t1.CardID, t2.Description, t5.BioData
FROM db2.tblemployeeinfob AS t1
LEFT JOIN db2.tbldepartments AS t2 ON t1.Department = t2.DepartmentID
LEFT JOIN db1.tblbiometrics AS t5 ON t1.CardID = t5.CardID
<?php
include('../dbcon.php');
include('../session.php');
if (isset($_POST['delete_user'])){
$id=$_POST['selector'];
$class_id = $_POST['teacher_class_id'];
$get_id=$_POST['get_id'];
$N = count($id);
for($i=0; $i < $N; $i++)
{
$result = mysql_query("select * from files where file_id = '$id[$i]' ")or die(mysql_error());
while($row = mysql_fetch_array($result)){
$fname = $row['fname'];
$floc = $row['floc'];
$fdesc = $row['fdesc'];
$uploaded_by = $row['uploaded_by'];
mysql_query("insert into files (floc,fdatein,fdesc,class_id,fname,uploaded_by) value('$floc',NOW(),'$fdesc','$class_id','$fname','$uploaded_by')")or die(mysql_error());
}
}
?>
<script>
window.location = 'downloadable.php<?php echo '?id='.$get_id; ?>';
</script>
<?php
}
if (isset($_POST['copy'])){
$id=$_POST['selector'];
$N = count($id);
for($i=0; $i < $N; $i++)
{
$result = mysql_query("select * from files where file_id = '$id[$i]' ")or die(mysql_error());
while($row = mysql_fetch_array($result)){
$fname = $row['fname'];
$floc = $row['floc'];
$fdesc = $row['fdesc'];
mysql_query("insert into teacher_backpack (floc,fdatein,fdesc,teacher_id,fname) value('$floc',NOW(),'$fdesc','$session_id','$fname')")or die(mysql_error());
}
}
?>
<script>
window.location = 'backpack.php';
</script>
<?php
}
?>
<?php
if (isset($_POST['share'])){
$id=$_POST['selector'];
$teacher_id = $_POST['teacher_id1'];
echo $teacher_id ;
$N = count($id);
for($i=0; $i < $N; $i++)
{
$result = mysql_query("select * from files where file_id = '$id[$i]' ")or die(mysql_error());
while($row = mysql_fetch_array($result)){
$fname = $row['fname'];
$floc = $row['floc'];
$fdesc = $row['fdesc'];
mysql_query("insert into teacher_shared (floc,fdatein,fdesc,teacher_id,fname,shared_teacher_id) value('$floc',NOW(),'$fdesc','$session_id','$fname','$teacher_id')")or die(mysql_error());
}
}
?>
<script>
window.location = 'tambah_share_file.php';
</script>
<?php
}
?>
I've almost done with my query, but there is still one last issue to resolve. My query looks like this:
//execute the SQL query and return records
$result = mysql_query("SELECT SUM(ps_order_detail.product_weight) * IF( COUNT(ps_order_detail.id_order_detail) > 50, 1.2, 1 )
as total_provision, COUNT(ps_order_detail.id_order_detail) as antal_ordrar, ps_customer.firstname
FROM ps_order_detail
JOIN ps_orders ON ps_order_detail.id_order = ps_orders.id_order
JOIN ps_order_history ON ps_orders.id_order = ps_order_history.id_order
JOIN ps_customer ON ps_orders.id_customer = ps_customer.id_customer
WHERE MONTH(ps_order_history.date_add) = MONTH(CURDATE()) AND (ps_order_history.id_order_state) = '4' OR (ps_order_history.id_order_state) = '13'
GROUP BY ps_orders.id_customer
ORDER BY SUM(ps_order_detail.product_weight) DESC
");
echo "<br>";
echo ("<img src=chart.php>");
echo "<br>";
echo ("<img src=chart_prov.php>");
//fetch tha data from the database
while ($row = mysql_fetch_array($result))
{
echo '<font size="3">';
echo " Namn: ".$row{'firstname'}. "";
echo " Provision: ".$row{'total_provision'}. "";
echo " Abonnemang: ".$row{'antal_ordrar'}. "";
echo '<br>';
echo '</font size>';
}
This part:
AND (ps_order_history.id_order_state) = '4' OR (ps_order_history.id_order_state) = '13'
causes the result to be displayed if the state of orders is either 4 or 13. The problem is that in the backend I can put it in those states many times, so if I'm not careful when updating orders, it will add the results more than one time.
Is it a way to limit that funktion to just handle latest update (have date_add in same table) or limit by 1?
Try to use
SELECT SUM(ps_order_detail.product_weight) * IF( COUNT(ps_order_detail.id_order_detail) > 50, 1.2, 1 )
as total_provision, COUNT(ps_order_detail.id_order_detail) as antal_ordrar, ps_customer.firstname
FROM ps_order_detail
JOIN ps_orders ON ps_order_detail.id_order = ps_orders.id_order
JOIN ps_order_history ON ps_orders.id_order = ps_order_history.id_order
JOIN ps_customer ON ps_orders.id_customer = ps_customer.id_customer
WHERE ps_order_history.id = (select ps_order_history.id from ps_order_history where ps_orders.id_order = ps_order_history.id_order and MONTH(ps_order_history.date_add) = MONTH(CURDATE()) AND (ps_order_history.id_order_state) = '4' OR (ps_order_history.id_order_state) = '13' order by ps_order_history.date_add desc limit 1)
GROUP BY ps_orders.id_customer
ORDER BY SUM(ps_order_detail.product_weight) DESC
Maybe it helps.