Is there a way to resort a mySQL sql after the results are already generated.
I have a sql that gets the results I want to display basically but the way I want to sort them depends on the result themselves. Have provided some pseudo code for clarity.
$sql = "SELECT * FROM post_info WHERE poster = 'login_user' OR replier = 'login_user'";
if ('login_user' == $row['poster']) { //sort by one column }
else { //sort by a different column }
You can sort conditionally from within the query with a CASE statement.
ORDER BY (CASE
WHEN poster = 'login_user' THEN col1
ELSE col2
END)
$sql = "SELECT *, if(poster='login_user', 1, 0) as idx FROM post_info WHERE poster = 'login_user' OR replier = 'login_user' order by idx desc";
or
$sql = "SELECT * FROM post_info WHERE poster = 'login_user' UNION SELECT * FROM post_info WHERE replier = 'login_user'";
Related
orderfood
orderfood_id food_id total_amount
foodcancel
foodcancel_id food_id status
$query = $this->db->query("SELECT * FROM order_food of LEFT JOIN `foodcancel` fc ON of.food_id = fc.food_id WHERE of.orderfood_id = '" . (int)$orderfood_id . "'");
$order_foods = $query->rows;
above is my query, what i wanted is that if there food_id inside foodcancel table , exclude it from rows, possbile to do it ?
For exclude the existing values you could try checking null for corresponding matching value
SELECT *
FROM order_food of
LEFT JOIN foodcancel fc ON of.food_id = fc.food_id
and of.food_id = your_value
WHERE fc.orderfood_id is null
anyway you should not php var in your sql code because in this way you are are risk for sqlinjection for avoid this you should take a look at prepared statement and binding param
It's very possible to do. In my logic. first, you must get all food_id on food_cancel table. Then save it into variabel and use it when you show orderFood table with adding NOT IN condition.
I've write code for you,
<?php
// Get Food Id From Cancel
$orderCancel = mysqli_query($mysqli, "SELECT * FROM `foodcancel`");
$cancelId = "";
while ($cancel = mysqli_fetch_array($orderCancel)) {
$cancelId .= $cancel["food_id"].",";
};
$cancelId = substr($cancelId, 0, -1);
// Put Food Id on Cancel Table into NOT IN Condition Database
$orderFood = mysqli_query($mysqli, "SELECT * FROM `orderfood` WHERE food_id NOT IN ($cancelId)");
while ($order = mysqli_fetch_assoc($orderFood)) {
$food[] = $order;
};
echo json_encode($food);
?>
I am having problems achieving the query to select data from a table in the db after a defined value has been met.
My code to do this is:
$fi = 'first_segment'
$im = popo.jpg
$sqls = "SELECT * FROM $fi,news_pictures
WHERE $fi.pi_id = news_pictures.pi_id
AND news_pictures.i_name = '$im'
GROUP BY news_pictures.id DESC";
I wasn't able to achieve the result with that query.
Basically, I want the query to confirm if news_pictures.i_name = '$im' and if true, return starts from the value of $im followed by other data in the table depending on news_pictures.id DESC.
The sample data and output:
Table news_pictures:
id i_name
-- ------
1 coco.jpg
2 lolo.jpg
3 popo.jpg
4 dodo.jpg
Since $im = popo.jpg, I want my query to display all values starting from popo.jpg with id DESC, i.e. popo.jpg, lolo.jpg, coco.jpg.
I got to solve the question with the help of a friend.
$fsqls = "SELECT * FROM $fi,news_pictures WHERE $fi.pi_id = news_pictures.pi_id AND news_pictures.i_name = '$im' GROUP BY news_pictures.id";
$rres = mysqli_query($connection, $fsqls) or print(mysqli_error($connection));
while($row = mysqli_fetch_assoc($rres))
{
$rnm = $row["id"];
}
$sqls = "SELECT * FROM news_pictures WHERE news_pictures.id <= $rnm ORDER BY news_pictures.id DESC";
I am trying to calculate how much a user has earned so it reflects on the users home page so they know how much their referrals have earned.
This is the code I have.
$get_ref_stats = $db->query("SELECT * FROM `members` WHERE `referral` = '".$user_info['username']."'");
$total_cash = 0;
while($ref_stats = $get_ref_stats->fetch_assoc()){
$get_ref_cash = $db->query("SELECT * FROM `completed` WHERE `user` = '".$ref_stats['username']."' UNION SELECT * FROM `completed_repeat` WHERE `user` = '".$ref_stats['username']."'");
$countr_cash = $get_ref_cash->fetch_assoc();
$total_cash += $countr_cash['cash'];
$countr_c_rate = $setting_info['ref_rate'] * 0.01;
$total_cash = $total_cash * $countr_c_rate;
}
It worked fine when I just had
$get_ref_cash = $db->query("SELECT * FROM `completed` WHERE `user` = '".$ref_stats['username']."'");
but as soon as I added in the UNION it no longer calculated correctly.
For example, there is 1 entry in completed and 1 entry in completed_repeat both of these entries have a cash entry of 0.75. The variable for $countr_c_rate is 0.10 so $total_cash should equal 0.15 but instead it displays as 0.075 with and without the UNION it acts as if it is not counting from the other table as well.
I hope this makes sense as I wasn't sure how to explain the issue, but I am very unsure what I have done wrong here.
In your second query instead of UNION you should use UNION ALL since UNION eliminates duplicates in the resultset. That is why you get 0.075 instead of 0.15.
Now, instead of hitting your database multiple times from client code you better calculate your cash total in one query.
It might be inaccurate without seeing your table structures and sample data but this query might look like this
SELECT SUM(cash) cash_total
FROM
(
SELECT c.cash
FROM completed c JOIN members m
ON c.user = m.username
WHERE m.referral = ?
UNION ALL
SELECT r.cash
FROM completed_repeat r JOIN members m
ON r.user = m.username
WHERE m.referral = ?
) q
Without prepared statements your php code then might look like
$sql = "SELECT SUM(cash) cash_total
FROM
(
SELECT c.cash
FROM completed c JOIN members m
ON c.user = m.username
WHERE m.referral = '$user_info['username']'
UNION ALL
SELECT r.cash
FROM completed_repeat r JOIN members m
ON r.user = m.username
WHERE m.referral = '$user_info['username']'
) q";
$result = $db->query($sql);
if(!$result) {
die($db->error()); // TODO: better error handling
}
if ($row = $result->fetch_assoc()) {
$total_cash = $row['cash_total'] * $setting_info['ref_rate'];
}
On a side note: make use of prepared statements in mysqli instead of building queries with concatenation. It's vulnerable for sql-injections.
With $countr_cash = $get_ref_cash->fetch_assoc(); you only fetch the first row of your result. However, if you use UNION, you get in your case two rows.
Therefore, you need to iterate over all rows in order to get all values.
Ok, So there is only one row in members table. You are iterating only once on the members table. Then you are trying to get rows using UNION clause which will result in two rows and not one. Then you are just getting the cash column of the first row and adding it to the $total_cash variable.
What you need to do is iterate over the results obtained by executing the UNION query and add the $total_cash variable. That would give you the required result.
$get_ref_stats = $db->query("SELECT * FROM `members` WHERE `referral` = '".$user_info['username']."'");
$total_cash = 0;
while($ref_stats = $get_ref_stats->fetch_assoc()){
$get_ref_cash = $db->query("SELECT * FROM `completed` WHERE `user` = '".$ref_stats['username']."' UNION SELECT * FROM `completed_repeat` WHERE `user` = '".$ref_stats['username']."'");
while($countr_cash = $get_ref_cash->fetch_assoc()){
$total_cash += $countr_cash['cash'];
}
$countr_c_rate = $setting_info['ref_rate'] * 0.01;
$total_cash = $total_cash * $countr_c_rate;
}
I'm trying to make a search for a property website i'm working on for a friend.
In the Database the property types are named by id numbers, ie: house = 30, flat = 8, terraced =1, and so forth..
How can i retrieve ALL properties from the database when some are detached houses with value of 2 and houses are value of 30 etc :)
It has got me stuck..lol
Here's what i have so far which isn't working...
$bedrooms = $_GET['bedrooms'];
$pricefrom = $_GET['pricefrom'];
$priceto = $_GET['priceto'];
$proptype = $_GET['proptype'];
if($proptype == 'house'){
$search_propsubid = array('1,2,3,4,5,6,21,22,23,24,26,27,30');
}elseif($proptype == 'flat'){
$search_propsubid = array('7,8,9,10,11,28,29,44');
}elseif($proptype == 'bungalow'){
$search_propsubid = array('');
}
$sql = mysql_query("SELECT * FROM `properties` WHERE `PROP_SUB_ID`='$search_propsubid' AND `BEDROOMS`='$bedrooms' AND `TRANS_TYPE_ID`='1' HAVING `PRICE` BETWEEN '$pricefrom' AND '$priceto' ORDER BY `UPDATE_DATE` DESC");
Thank you for your time i hope someone can point me in the right direction..
Regards
Steve
You can try to implode array:
$search_propsubid = array('1,2,3,4,5,6,21,22,23,24,26,27,30');
$comma_separated = implode(",", $search_propsubid);
$sql = mysql_query("SELECT * FROM `properties` WHERE `PROP_SUB_ID` in ($comma_separated) ...
Comme back with news if this don't works for you.
You can use the MySql IN() comparison operator to select all that match the list of values:
$sql = mysql_query("
SELECT *
FROM `properties`
WHERE `PROP_SUB_ID` IN (" .implode(",", $search_propsubid). ")
AND `BEDROOMS`='$bedrooms'
AND `TRANS_TYPE_ID`='1'
HAVING `PRICE` BETWEEN '$pricefrom' AND '$priceto'
ORDER BY `UPDATE_DATE` DESC
");
Assuming $proptype == 'flat', the output will be:
SELECT *
FROM `properties`
WHERE `PROP_SUB_ID` IN (7,8,9,10,11,28,29,44)
...
I have two tables for the users; a login table and the user profile table.
I want to compare a value from 'userprofiletable' to another value from another table called posts. If the value is equal, it shows a list.
I have the following code. The problem is that it is not comparing the value in the posts table with the value of the session from user profile table.
Could someone help me please?
<?php
$limit = '5';
$dbreq = 'SELECT * FROM `posts` ORDER BY `pos` DESC';
$dbdata = mysql_query($dbreq);
while($dbval = mysql_fetch_array($dbdata))
{
if (($dbval['city'] == $_SESSION['student_city'])) { //checks for last 4 accomodation
if ($limit >= '1') {
echo '<tr><td>'.$dbval['title'].'</td></tr>';
$limit = $limit -'1';
}
}
}
?>
I also want to get the value of userprofiletable and post it in the posts table. For example, when somebody make a new post.
Your post is a bit unclear, but I think this is what you want:
<?php
$userid = 11542;//Sample uid. You will have to figure this out and set it.
$limit = 5;
$dbreq = "SELECT * FROM `posts` WHERE `userid`=".$userid." ORDER BY `pos` DESC LIMIT=".$limit.";";
$dbdata = mysql_query($dbreq);
while($dbval = mysql_fetch_array($dbdata))
{
if (($dbval['city'] == $_SESSION['student_city'])) { //checks for last 4 accomodation
echo '<tr><td>'.$dbval['title'].'</td></tr>';
}
}
?>
The question is not clear, but there could be two answers:
To reproduce your code, you can do in ONE sql query:
$dbreq = 'SELECT *
FROM `posts`
WHERE city="'.mysql_real_escape_string($_SESSION['student_city']).'"
ORDER BY `pos` DESC
LIMIT 4';
If, however, there are two tables, then you need "LEFT JOIN" linking the posts table to the userprofile table
$dbreq = 'SELECT p.*, u.*
FROM posts p
LEFT JOIN userprofiletable up ON p.UserID=up.UserID
WHERE up.city="'.mysql_real_escape_string($_SESSION['student_city']).'"
ORDER BY p.pos DESC
LIMIT 4';
(UserID in the table above is the name of the field in the posts table and userprofiletable that links the two.)