Mysql Query with SUM and WHERE does not work - mysql

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

Related

Why can't this code run in CodeIgniter?

Query code:
$query = $this->db->query(
'SELECT course.*, AVG(course_review.`rating`) AS `avg_rating`
FROM course
LEFT JOIN course_review ON `course`.`id` = `course_review`.`course_id`
WHERE `course`.`course_category`= ' . $id . '
AND `course`.`approved`= 3
AND `course`.`delete_course` != 1
AND `course`.`unpublish_course` != 1
GROUP BY `course`.`id`
ORDER BY avg_rating DESC');
return $query->result()
Thanks
You can try this Query for your problem :
Query:-
$query = $this->db->query('SELECT
course.id,
AVG(course_review.rating) AS avg_rating
FROM course
LEFT JOIN course_review
ON course.id = course_review.course_id
WHERE course.course_category = ' . $id . '
AND course.approved = 3
AND course.delete_course != 1
AND course.unpublish_course != 1
GROUP BY course.id
ORDER BY avg_rating DESC');
return $query->result();

mysql additional condition after INNER JOIN, ON

I have this query right now
global $wpdb;
$interval = "1 WEEK";
$now = current_time('mysql');
$top4=$wpdb->get_results('SELECT ID, post_title, post_name from `'.$wpdb->prefix.'popularpostssummary`
INNER JOIN `'.$wpdb->prefix.'posts` ON `postid`=`ID`
ORDER BY `pageviews` DESC
LIMIT 4;', ARRAY_A);
And I want to add the following conditions, what's the proper way of adding them in the code?
WHERE post_type = post
AND last_viewed > DATE_SUB('{$now}', INTERVAL {$interval})
post_type is under '.$wpdb->prefix.'posts
while last_viewed is under '.$wpdb->prefix.'popularpostssummary
global $wpdb;
$interval = "1 WEEK";
$now = current_time('mysql');
$sql =
'SELECT p.ID, p.post_title, p.post_name
FROM `' . $wpdb->prefix . 'popularpostssummary` AS pps
INNER JOIN `' . $wpdb->prefix . 'posts` AS p ON pps.`postid`= p.`ID`
WHERE p.post_type = "post"
AND pps.last_viewed > DATE_SUB("' . $now . '", INTERVAL ' . $interval . ')
ORDER BY pps.`pageviews` DESC
LIMIT 4;';
echo $sql; exit;
$top4 = $wpdb->get_results( $sql, ARRAY_A );

PHP - How to group from multiple sql queries

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...

Add many-to-many select into existing query

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

How to get PDO to select from more than one table

Here is my code:
$sql= ("SELECT R.cr_id,R.time,R.reply,U.user_id,U.user_name FROM tb_user U, conversation_reply R WHERE R.user_id_fk=U.user_id and R.c_id_fk='$c_id' ORDER BY R.cr_id ASC LIMIT 20");
$stmt = $conn->prepare($sql);
$stmt->execute();
$row=$stmt->fetchAll();
foreach ($row as $laww) {
echo $laww['$user_name'].":". $laww['reply']. "<br>";
}
}////END
I get only the result from $laww['reply'] but not $laww['$user_name']
Can anyone helpe me ?