Choosing the correct SQL query based off user input - php

Lets say the user only entered in an artist to search by, how do I get PHP to recognize that the user is only looking for an artist and should therefore setup a query only for the artist. The way I have currently done it works, but it is very ineffective when the user wants a variety of search options.
$artist = $_POST["artistSearch"];
$topic= $_POST["topicSearch"];
$date = $_POST["dateSearch"];
$title = $_POST["titleSearch"];
$artistLength = strlen($artist);
$topicLength = strlen($topic);
$dateLength = strlen($date);
$titleLength = strlen($title);
if ($artistLength>2 && $topicLength<2 && $dateLength<2 && $titleLength<2) {
$sql=("Select * FROM music WHERE artist = '$artist' ORDER BY date");
}
if ($artistLength>2 && $topicLength>2 && $dateLength<2 && $titleLength<2) {
$sql=("Select * FROM music WHERE artist = '$artist' AND topic = '$topic' ORDER BY date");
}
if ($artistLength>2 && $topicLength>2 && $dateLength>2 && $titleLength<2) {
$sql=("Select * FROM music WHERE artist = '$artist' AND topic = '$topic' AND date = '$date' ORDER BY date");
}
if ($artistLength>2 && $topicLength>2 && $dateLength>2 && $titleLength>2) {
$sql=("Select * FROM music WHERE artist = '$artist' AND topic = '$topic' AND date = '$date' AND title = '$title' ORDER BY date");
}
$result = mysqli_query($con,$sql);

Simple, you build up the query string in stages. Ignoring your sql injection attack vulnerability, and assuming that all options should be ANDed together, you can do something like:
$options = array();
if ($artist) {
$options[] = "artist = '$artist'";
}
if ($topic) {
$options[] = "topic = '$topic'";
}
etc...
$where_clause = implode(' AND ', $options);
$sql = "SELECT ... WHERE $where_clause";

Related

How can I search multiple inputs from a form in php?

I have a PHP program that allows users to search through an SQL table depending on the input or combination of inputs. I can do single search combination, but can't figure out a way to search by any criteria. What I got so far is terrible because I'm trying to search by every input possibility (and it's not working). This is what I got so far.
<?php
include_once("config.php");
if(isset($_POST['submit'])){
$name = mysqli_real_escape_string($mysqli, $_POST['name']);
$day = mysqli_real_escape_string($mysqli, $_POST['day']);
$month = mysqli_real_escape_string($mysqli, $_POST['month']);
$year = mysqli_real_escape_string($mysqli, $_POST['year']);
// 1 2 3 4
if( !empty($name) && !empty($day) && !empty($month) && !empty($year) ) {
$sql = mysqli_query($mysqli, "SELECT *
FROM transfer
WHERE name like '%$name%'
and day LIKE '%$day%'
AND month LIKE '%$month%'
AND year LIKE '%$year%'");
} else if (!empty($name) && !empty($day) && !empty($month) ) {
$sql = mysqli_query($mysqli, "SELECT *
FROM transfer
WHERE name like '%$name%'
and day LIKE '%$day%'
AND month LIKE '%$month%'");
} else if (!empty($day) && !empty($month) && !empty($year) ) {
$sql = mysqli_query($mysqli, "SELECT *
FROM transfer
WHERE day LIKE '%$day%'
AND month LIKE '%$month%'
AND year LIKE '%$year%'");
} else if (!empty($name && !empty($day) ) {
$sql = mysqli_query($mysqli, "SELECT * FROM transfer
WHERE name like '%$name%' and
day LIKE '%$day%'");
}
//1 3
else if (!empty($name) && !empty($month) )
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE name like '%$name%' and month LIKE '%$month%'");
}
//1 4
else if (!empty($name) && !empty($year) )
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE name like '%$name%' and year LIKE '%$year%'");
}
//2 3
else if (!empty($day) && !empty($month) )
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE day like '%$day%' and month LIKE '%$month%'");
}
//2 3
else if (!empty($day) && !empty($month) )
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE day like '%$day%' and month LIKE '%$month%'");
}
//2 4
else if (!empty($day) && !empty($year))
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE day like '%$day%' and year LIKE '%$year%'");
}
//3 4
else if (!empty($month) && !empty($year))
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE month like '%$month%' and year LIKE '%$year%'");
}
//1
else if (!empty($name))
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE name like '%$name%'");
}
//2
else if (!empty($day))
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE day like '%$day%'");
}
//3
else if (!empty($month))
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE month like '%$month%'");
}
//4
else if(!empty($year))
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE year like '%$year%'");
}
else
{
echo "<p>you must insert an input</p>";
}
//while loop used to retrieve data from the SQL database
while ($res = mysqli_fetch_array($sql))
{
echo "<tr>";
echo "<td>".$res['name']."</td>";
echo "<td>".$res['confirmation']."</td>";
echo "<td>".$res['code']."</td>";
echo "<td>".$res['hora']." ".$res['horario']."</td>";
echo "<td>".$res['day']."/".$res['month']."/".$res['year']."</td>";
echo "<td>".$res['extra']."</td>";
echo "</tr>";
}
}
?>
</table>
(Note: It has been said to use prepared statements, which is right - but I don't want to give a copy & paste answer anyway, so here is just an example on how you can achieve your result - use prepared statements anyway. It works the same, except you are creating your query with placeholders and provide the variables that are not empty)
You can create your query in a more "dynamic" way. This is a little tricky, and becomes very "challenging" if joins are required - but what you actually want is to end up with a single query, containing all your constraints.
The first thing, you should define: Are your Searchfields "and" or "or" fields?
if it's "and" it is quite simple to achieve - something like this:
$query = "SELECT * FROM transfer";
$andParts = array();
if(!empty($name))
$andParts[] = "name = '$name'";
if(!empty($day))
$andParts[] = "day = $day";
if (!empty($month))
$andParts[] = "month = $month";
if (!empty($year))
$andParts[] = "year = $year";
if (!empty($andParts))
$query .= " WHERE ".implode(" AND " , $andParts);
$sql->Query($query);
if theres also "or" involved, you'll need another array $orParts, where you first join all the "ors", and finally glue that array together to the final "ands".
If conditions could match columns from "joined" tables, you need to keep track of that, so that you know, from with tables you need to "select".
If you have very complex query for each "searchfield" (i.e. every searchfields result is a result of multiple joins etc...) you can query just the id's for each searchfield, then intersect the results and retrieve the ids matching all criterias:
$result1 = $sql->Query("SELECT id FROM transfer left join .... ");
// array(1,2,3,5,7,10,15,19,27)
$result2 = $sql->Query("SELECT id FROM transfer right join .... ");
// array(2,3,10,15,19,27,43,123)
$result3 = $sql->Query("SELECT id FROM transfer inner join .... ");
// array(2,10,15,27,43,711)
$ids = array_intersect($result1, $result2, $result3);
// array(2,10,15,27)
$finalResult = $sql->Query("SELECT * FROM transfer WHERE id in (".implode(",", $ids).");");

php mysql search row with multiple arrays in cells

ok, so stay with me here ...
i have a site with a table of about 80,000 rows; i am trying to search this table with one MySQL query. The problem is that each of the fields in the row i'm searching has / might have an array (ex: year = 2017,2016,2015, etc), and some of them may not have anything at all. i have tried doing a loop through to and build my "WHERE" clause as i pull the results, but that isn't working either.
any thoughts? any and all help will be greatly appreciated.
CODE:
INSERT INTO the table - this is one of the 13 different rows
if(!empty($_POST['pd_year']) && is_array($_POST['pd_year'])) {
$pd_year = implode(",", $_POST['pd_year']);
$insert_year = mysqli_query($con, "UPDATE prod_desigs_search_test SET pds_year = '$pd_year' WHERE s_id = '$search'");
} elseif(empty($_POST['pd_year'])) {
$insert_year = mysqli_query($con, "UPDATE prod_desigs_search_test SET pds_year = ' ' WHERE s_id = '$search'");
}
SELECT THE design and check if it is an array or not:
$get_search = mysqli_query($con, "SELECT * FROM prod_desigs_search_test WHERE s_id = '$s_id'");
while($new_search = mysqli_fetch_array($get_search)) {
$pd_year_ex = $new_search['pds_year'];
if(!empty($pd_year_ex) && is_array($pd_year_ex)) {
$pd_year = explode(",", $pd_year_ex, 0);
$year = $pd_year[0];
} elseif(!empty($pd_year_ex) && !is_array($pd_year_ex)) {
$year = $pd_year_ex;
}
$search = mysqli_query($con, "SELECT * FROM prod_designs WHERE pd_year = '$year'");
while($row_search = mysqli_fetch_array($search)) {
EDIT
I have tried to build out the "WHERE" in the query dependent on the is_array check like this:
$where = "WHERE ";
if(!empty($pd_year_ex) && is_array($pd_year_ex)) {
$pd_y = $pd_year[0];
foreach ($pd_y as $year) {
$where .= "pd_year LIKE '%".$year."%'";
}
} elseif(!empty($pd_year_ex) && !is_array($pd_year_ex)) {
$where .= "pd_year LIKE '%".$pd_year_ex."%'";
} elseif(empty($pd_year_ex)) {
$where .= "";
}
and this doesn't seem to be working either. i am just trying to understand how to do a search like this:
$search = mysqli_query($con, "SELECT * FROM designs WHERE pd_year LIKE '%2017,2016,2015%'")(etc)
I know it won't go with the above, but how do i search a table for something like this?

Alphabetically ordered list from mysqli join query

I am trying to print out an alphabetically ordered list of usernames after using a mysqli join query to select userid's from a friends table.
Friends table consists of
id - userid_one - userid_two - friendship_date - friendship_type
Users table has a pretty standard layout, and the only field I really need from it is the username (to display) and the userid to link the two tables
what i want to achieve is the below
A
Andy
Anna
B
Bobby
Brian
The code i am using is below.
$ir['userid'] //the current users id
$getfriends = mysqli_query($con,"SELECT * FROM friends INNER JOIN users ON (friends.userid_one = users.userid OR friends.userid_two = users.userid) WHERE (userid_one = '{$ir['userid']}' OR userid_two = '{$ir['userid']}') ORDER BY username") or die("query error");
$last="";
if(mysqli_num_rows($getfriends) == 0)
{
print"<li>You have no friends....sorry</li>";
}
else
{
while($gotf=mysqli_fetch_array($getfriends))
{
if($gotf['userid_one'] == $ir['userid']){$friend = $gotf['userid_two'];}else{$friend = $gotf['userid_one'];}
$printed_array = explode(",",$printed);
if(!in_array($friend,$printed_array))
{
$username_of_user = get_username_no_link($friend);
$current_letter = $username_of_user[0];
if ($last != $current_letter) {
print"<li class='Label'>{$current_letter}</li>";
$username_of_user = get_username_nd_avatar($friend);
print"<li>".$username_of_user."</li>";
$last = $current_letter;
$printed = $printed.",".$friend;
}
elseif($last == $current_letter){
$username_of_user = get_username_nd_avatar($friend);
print"<li>".$username_of_user."</li>";
$last = $current_letter;
$printed = $printed.",".$friend;
}
}
}
}
I have not got much experience of using JOIN in mysqli queries and my issue is that I am not getting the list sorted alphabetically as the below example shows.
A
Andy
T
Thomas
S
Sandra
Sally
UPDATE--
the order in which the usernames display, now seems to change randomly after reloading the page, which is further confusing the matter!
question now answered after some playing around. Ended up putting the usernames into an array, then sorting the array alphabetically by value, as well as adding a $printed_array array to add each friend to after they were printed to prevent them being printed out twice.
$usersnames = array();
while($gotf=mysqli_fetch_array($getfriends))
{
if($printed != ""){$comma = ",";}
if($gotf['userid_one'] == $ir['userid']){$friend = $gotf['userid_two'];}else{$friend = $gotf['userid_one'];}
$printed_array = explode(",",$printed);
if(!in_array($friend,$printed_array))
{
$username_of_user = get_username_no_link($friend);
$usersnames[] = $username_of_user;
$printed = $printed.$comma.$friend;
}
}
sort($usersnames);
foreach($usersnames as $name)
{
$getuserid = mysqli_query($con,"SELECT userid,avatar FROM users WHERE username = '$name' LIMIT 1");
$gotuserid = mysqli_fetch_array($getuserid);
//var_dump($gotuserid);
$displaypic = "<img style='height:30px;vertical-align:middle;margin:5px;' src='".$gotuserid['avatar']."'>";
$current_letter = $name[0];
if ($last != $current_letter)
{
print"<li class='Label'>{$current_letter}</li>";
print"<li><a href='profile/".$name."'>".$displaypic.$name."</a></li>";
$last = $current_letter;
}
elseif($last == $current_letter)
{
print"<li><a href='profile/".$name."'>".$displaypic.$name."</a></li>";
$last = $current_letter;
}
}

Order MySQL inbox by newest conversation first?

I've a MySQL/PHP code for a private messaging system that I built. It works great although I'm fairly new to it all so struggling to get the message threads to display by newest first. Is there any chance you could offer advice? The current code is as follows:
$result = '';
$nowTime = time();
$getmessages = mysql_query("SELECT * FROM messages WHERE msg_to = '$session_memberid' GROUP BY msg_from ORDER BY ID DESC");
while($iamessages = mysql_fetch_array($getmessages))
{
$msg_id = $iamessages['ID'];
$msg_from = $iamessages['msg_from'];
$msg_conversation = $iamessages['conversation'];
$getmsgdata = mysql_query("SELECT * FROM messages WHERE msg_to = '$session_memberid' AND msg_from = '$msg_from' ORDER BY ID DESC LIMIT 1");
while($imsd = mysql_fetch_array($getmsgdata))
{
$msg_message = $imsd['msg_message'];
$msg_time = $imsd['time'];
$msg_read = $imsd['msg_read'];
}
$msg_conversation = suitcrypt($msg_conversation);
if ( $msg_read == 'no' ) { $msgclass = "messagepostunread"; } else { $msgclass = "messagepost"; }
$getfromdata = mysql_query("SELECT FullName, Username, status FROM members WHERE ID = '$msg_from'");
while($ifd = mysql_fetch_array($getfromdata))
{
$msg_from_name = $ifd['FullName'];
$msg_from_username = $ifd['Username'];
$msg_from_status = $ifd['status'];
}
$getfromdata1 = mysql_query("SELECT Link FROM images WHERE MemberID = '$msg_from' AND is_primary = 'yes'");
while($ifd1 = mysql_fetch_array($getfromdata1)) {
$msg_from_img = $ifd1['Link'];
}
$timepass = timing($msg_time);
if ( $timepass == 'data' ) {
$timepass = date("dS M", $msg_time);
}
if ( ( $msg_from_status == 'full' ) || ( $msg_from_status == 'active' ) ) {
$result .= "
<div class=\"$msgclass\" onclick=\"showconversation('$msg_conversation');\">
<img src=\"m/members_image/$msg_from/thumb-$msg_from_img\" class=\"feedpic\" width=\"55\" height=\"55\" /><div class=\"messageposttext\">$msg_from_name:<div class=\"inboxfeedreply\">Reply ยท $timepass</div><br />$msg_message</div>
</div>
<div class=\"splittermessages\"></div>
";
}
Within each table entry in the messages table there is a 'time' stamp. Here's an example of the time entries: 1367680391. What's the best way to order the threads by newest reply first?
First off I think you should group by $msg_conversation and find the last date on each conversation. With the code below you have the conversatons ordered by the last message each conversation/thread had.
$result = '';
$nowTime = time();
$getmessages = mysql_query("SELECT conversation, max(date) FROM messages WHERE msg_to = '$session_memberid' GROUP BY conversation ORDER BY max(date)");
while($iamessages = mysql_fetch_array($getmessages))
{
$msg_conversation = $iamessages['conversation'];
...
Further on you can get the messages for each conversation by date descending.
I got someone to help and the answer was to update the query to the following:
$getmessages = mysql_query("SELECT * FROM messages WHERE msg_to = '$session_memberid' GROUP BY msg_from ORDER BY MAX(time) DESC");

How can execute a MySQL query with multiple WHERE-clauses?

how would you do a mysql query where a user can choose from multiple options. Fox example I have a form that user can use to search for houses. Now I have a select box where you can chosse whether you want a house, a flat or whatever. Then I have a second box where you can choose for example the city you want the house or flat to be in. And maybe another one with the maximum price.
Now how would you do the mysql query? My problem is, I would do it like that:
if($_POST["house_type"] != 0) {
$select = mysql_query("SELECT * FROM whatever WHERE type = '".$_POST["house_type"]."'");
}
But now I only have the case that someone has chosen a house type but not any other option. So do I have to do an "if" for every possible combination of selected elements?
To emphasize my problem:
if(!isset($_POST["house_type"])) {
if($_POST["something"] == 0) {
$search_select = #mysql_query("SELECT * FROM housedata WHERE something = $_POST["whatever"]);
}
elseif($_POST["something"] != 0) {
$search_select = #mysql_query("SELECT * FROM housedata something = $_POST["whatever"] AND somethingelse = 'whatever');
}
}
elseif(!isset($_POST["house_type"])) {
if($_POST["something"] == 0) {
$search_select = #mysql_query("SELECT * FROM housedata WHERE something = $_POST["whatever"]);
}
elseif($_POST["something"] != 0) {
$search_select = #mysql_query("SELECT * FROM housedata something = $_POST["whatever"] AND somethingelse = 'whatever');
}
}
Now imagine I had like 10 or 20 different select boxes, input fields and checkboxes and I would have to do a mysql query depending on what of these boxes and fiels and checkboxes is filled. This would be a code that is extremely complicated, slow and horrible. So is there a possibility to make a mysql query like:
SELECT * FROM whatever WHERE house_data = '".$whatever."' AND (if(isset($_POST["something"])) { whatever = '".$whatever2."' } AND ...;
You get what I mean? Its a bit complicated to explain but actually its a very important question and probably easy to answer.
Thank you for your help!
phpheini
Generate the WHERE clause prior to running the SQL.
A short example:
$whereClause = "";
if ($_POST['opt1']) {
$opt1 = mysql_real_escape_string($_POST['opt1']);
$whereClause .= "AND opt1='$opt1'";
}
if ($_POST['opt2']) {
$opt2 = mysql_real_escape_string($_POST['opt2']);
$whereClause .= "AND opt2='$opt2'";
}
mysql_query("SELECT * FROM table WHERE 1 ".$whereClause);
To point you a little bit into the right direction, try something like this:
if(isset($_POST["something"]))
{
$where = " AND whatever = '".$whatever2."'";
}
else $where = '';
mysql_query("SELECT * FROM whatever WHERE house_data = '".$whatever."'".$where);
$where = array();
if($_POST["something"]) {
$where[] = " something =".$_POST["something"];
}
if($_POST["something2"]) {
$where[] = " something2=".$_POST["something2"];
}
.
.
.
//build where string
$where_ = !(empty($where) ? " WHERE ".implode(" AND ",$where) : "";
//build sql
$sql = "SELECT * ... ".$where;
write some simple query builder
$where = array();
if($_POST["something"]) {
$where[] = sprintf(" something='%s'",$_POST["something"]);
//sprintf - prevent SQL injection
}
if($_POST["something2"]) {
$where[] = sprintf(" something2='%s'",$_POST["something2"]);
}
//build where string
$where_str = " WHERE ".implode(" AND ",$where);
//build sql
$sql = "SELECT * ... $where_str";
You need to build your search string separately but the format is simply
SELECT * FROM your_table WHERE number = {$number} AND sentence = '{$sentence}';
Since you are creating the search term based on PHP logic do this:
$search = "SELECT * FROM your_table WHERE ";
if(isset($whatever)) $search .= "something = '{$whatever}'";
if(isset($whateverelse)) $search .= " AND somethingelse = '{$whateverelse}'";
$search_select = mysql_query($search);

Categories