Select multiple array from mysql - php

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

Related

Select data from the database before or after a defined value

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";

Re-sort sql after results already generated

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'";

Copy data from one MySQL table to another when data intersect using PHP

I'm new to programming and would really appreciate your help. :) So, I have a USER table and a SALES table. On the SALES table I only have name and last name of the users. On the USER table I have name, last name, USER_ID, email and etc...
I need to copy the USER_ID from the USER table to the SALES table when NAME and LAST NAME are a match.
Here is the structure:
USER_TABLE_A
USER_ID_A
NAME_LASTNAME_A
SALES_TABLE_B
ROW_ID_B
NAME_B
LASTNAME_B
USER_ID_B (empty)
So far I got both tables to show data when they intersect but have no idea where to go from here. Could anyone please help?
$sql1 = mysql_query("SELECT name_B, lastname_B, user_id_B, row_id_B FROM sales_table_B WHERE name_B IS NOT NULL AND lastname_B IS NOT NULL", $db);
$sql2 = mysql_query("SELECT name_lastname_A, user_id_A FROM user_table_A WHERE name_lastname_A IS NOT NULL", $db);
$a1 = array();
while ($row = mysql_fetch_array($sql1)) {
$id = $row['row_id_B'];
$name1.$id = $row['name_B']." ".$row['lastname_B'];
array_push($a1, $name1.$id);
}
$a2 = array();
while ($row2 = mysql_fetch_array($sql2)) {
$id2 = $row2['user_id_A'];
$name2.$id2 = $row2['name_lastname_A'];
array_push($a2, $name2.$id2);
}
$result = array_intersect($a1,$a2);
print_r($result);
Thanks in Advance!
Under the assumption that NAME_LASTNAME_A column in USER_TABLE_A is a concatenation of NAME_B and LASTNAME_B columns of SALES_TABLE_B, following UPDATE query should update the ids:
update sales_table_b
set b.user_id_b = (
select user_id_a from user_table_a
where name_lastname_a = concat(b.name_b, ' ' , b.lastname_b)
limit 1
where exists(
select user_id_a from user_table_a
where name_lastname_a = concat(b.name_b, ' ' , b.lastname_b)
)
)
Please note that in case of multiple users having same first and last name, id of the first matching user will be considered.
Thank you so much Darshan!! Your answer was missing a ) after limit 1 but with the adjustment it worked beautifully! Here is the code that worked:
UPDATE sales_table_b
SET user_id_b = (SELECT user_table_a.user_id_a
FROM user_table_a
WHERE user_table_a.name_lastname_a = CONCAT(sales_table_b.name_b, ' ' , sales_table_b.lastname_b) LIMIT 1)
WHERE EXISTS (SELECT *
FROM user_table_a
WHERE user_table_a.name_lastname_a = CONCAT(sales_table_b.name_b, ' ' , sales_table_b.lastname_b))

Getting total in while statement with UNION query

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;
}

Using WHERE, AND, & OR in same MySQL query help

Will this query work? Is it most efficient?
SELECT * FROM `posts`
WHERE MATCH (`title`, `body`)
AGAINST ('search terms' IN BOOLEAN MODE)
AND `price` BETWEEN '100' AND '1000'
AND (`postinto` = 'cat1' OR `postinto` = 'cat2')
AND (`location` = 'loc1' OR `location` = 'loc2')
ORDER BY `id` DESC
LIMIT 0, 100;
Note: values for postinto and location will be contained in a PHP arrays, so if this will work I plan on looping their the arrays to generate the query terms. Is there a way to pass the entire array to MySQL? Also, these two conditions have a possibility of being quite long (a dozen values). Is there a better way?
specifically my question is about this:
AND (`postinto` = 'cat1' OR `postinto` = 'cat2')
AND (`location` = 'loc1' OR `location` = 'loc2')
an example of possible values would be "community|groups", "buy-sell-trade|electronics" where before the | is a category and after | is a sub category. If I am searching an entire category I would want to change that part of the query to:
AND (`postinto` LIKE 'category|%' OR `postinto` = 'this'
I have the proper indexes for the fulltext search, my question is about the OR clause. Is there a maximum number of times you can use OR in one query? Is this syntax even correct?
Thanks
Actually there is. The IN statement can help you here.
Your query would then become like this:
SELECT * FROM `posts`
WHERE MATCH (`title`, `body`)
AGAINST ('search terms' IN BOOLEAN MODE)
AND `price` BETWEEN '100' AND '1000'
AND `postinto` IN ('cat1', 'cat2')
AND `location` IN ('loc1', 'loc2')
ORDER BY `id` DESC
LIMIT 0, 100;
You can use AND and OR in a WHERE as often as you want, but to keep your sanity you need to obey a few simple rules.
1) Do not mix them, constructing a query with WHERE AND OR AND OR will probably work but the results will be unpredictable and the result set may contain multiple instances of the same record! (You are effectively turning the OR construct into an EITHER!
2) I would recommend always putting all of the OR statements before any AND statements. It will be easier for you to understand and for anybody else to maintain.
3) It is probably not a necessity but I always if possible enclose the OR statements in brackets.
I Maintain a Sports database and run some queries that can have multiple options in the select.
Hopefully the following examples will simplify the explanation.
// Make the query to retrieve the set of Singles Games.
$query = "SELECT * from Games WHERE Season = '$season'
AND GameNo < 8
OR Player1 = '$playerName' ORDER by MatchNo ASC";
$result = #mysql_query($query); // Run the query.
$num = mysql_num_rows($result);
This will run, it is syntactically correct but the results will be unpredictable!
If in these circumstances you wish to put the OR after the AND then you need to 'AND' the OR.
// Make the query to retrieve the set of Singles Games.(This is correct)
$query = "SELECT * from Games WHERE (Player1 = '$playerName'
OR Player3 = '$playerName') AND Season = '$season'
AND GameNo < 8 ORDER by MatchNo ASC";
$result = #mysql_query($query); // Run the query.
$num = mysql_num_rows($result);
This will run and produce a list of Singles games in which a player has participated.
The following is the same statement with the OR after the AND. Notice you need to AND
the OR to the end of the statement.
// Make the query to retrieve the set of Singles Games.(This is also correct)
$query = "SELECT * from Games WHERE Season = '$season'
AND GameNo < 8 AND (Player1 = '$playerName'
OR Player3 = '$playerName') ORDER by MatchNo ASC";
$result = #mysql_query($query); // Run the query.
$num = mysql_num_rows($result);
This will run and produce a list of Singles games in which a player has participated.
Finally a couple of examples, why I prefer the OR first
$query = "SELECT * from Games WHERE (Player1 = '$playerName'
OR Player2 = '$playerName' OR Player3 = '$playerName'
OR Player4 = '$playerName') AND Season = '$season'
AND GameNo > 7 ORDER by MatchNo ASC";
$result = #mysql_query($query); // Run the query.
$num = mysql_num_rows($result);
This will produce a result set containing all the League doubles that a player has participated in. Either as home player1 or 2, or away player 3 or 4.
To produce a query with multiple separate OR statements. Then place an AND between the OR
statements.
$query = "SELECT * from CupGames WHERE (Player1 = '$playerName'
OR Player2 = '$playerName' OR Player3 = '$playerName'
OR Player4 = '$playerName' OR Player5 = '$playerName'
OR Player6 = '$playerName') AND (CupID = 'CS' OR CupID = 'ND')
AND Season = '$season' AND GameNo < 4 ORDER by CupRound ASC";
$result04 = #mysql_query($query); // Run the query.
$num = mysql_num_rows($result04);
This will produce a result set containing all the Cup Triples that a player has participated in. Either as home player1,2 or 3, or away player 4, 5 or 6. In either of
the two selected cups. CS(Coronation Shield) or ND(Norman Day Cup) for the selected season.
If you wish to keep your hair I suggest following these rules.
(I have retired from IT and have a full head of hair!)
Best of Luck!

Categories