Search from multiple tables - php

This is a code which is working fine without any error giving result.
SELECT student.id, student.name, fee_slip.payamount, fee_slip.time, student.class
FROM student
LEFT JOIN fee_slip
ON student.id=fee_slip.student
where (fee_slip.student) is null
But now I want to make it more dynamic.
I have a code which is also working good but I am using it on a single table.
$query = "SELECT id, name, std_reg_number, class, section FROM student where id IS NOT NULL ";
if ($name != "") {
$query .= " AND `name` LIKE '" . $name . "%'"; // id is greater then
}
if ($status != "") {
$query .= " AND `status` LIKE '" . $status . "%'"; // id is greater then
}
if ($class != "") {
$query .= " AND class IN($class) ORDER BY class DESC"; // Selecting class
}
if ($section != "") {
$query .= " AND section IN($section)"; // selecting section
}
if ($sort != "") {
$query .= " ORDER BY $sort ASC"; // Selecting religion
}
$result = mysql_query($query);
Now I tried to use subquery
$query .= " SELECT fee_slip.student_id, fee_slip.std_reg_number, fee_slip.payamount, fee_slip.totalamount ";
But I didn't get results.
What should I do?

There is a big difference between the terms "subquery" and "multi-query". You seem to be mixing those concepts up.
Assuming the query you posted works the way you need it to, it seems you could just replace the $query value in the code with that, and it would work just as well as the query you have there now. (You might have to add the table names/aliases to the fields in the WHERE clauses though, to avoid ambiguity. Depends on your table structure.)
In any case, adding another SELECT after the query you have now isn't the way to go.
I would also, like others have before me, point out that the old MySQL API functions are outdated, and that your code is riddled with security issues. - Prepared Statements through either PDO or MySQLi should be used these days.

Related

PHP to create MySQL query from URL query

I have a relatively small search form that I want people to use to search my SQL database.
The only way I've done this before was with a billion nested if statements. Is there a better way to do this?
I am parsing my URL query string, so I have my variables of say:
$city
$bedrooms
$elementaryschool
If I were to just try to try:
$sql = "SELECT * FROM $table_name WHERE ";
if(isset($city)) {
$sql .= " `City` LIKE " . $city;
}
if(isset($bedrooms)) {
$sql .= " AND `Bedrooms` >= " . $bedrooms;
}
if(isset($elementaryschool)) {
$sql .= " AND `ElementarySchool` = " . $elementaryschool;
}
Then I run into an issue when $city isn't set because my query ends up with "SELECT * FROM $table_name WHERE AND Bedrooms >= $bedrooms"
That wouldn't exactly work. What are my options?
I completely understand how to do it if I am including all parameters in my query, which seems to be what all previous questions have asked. But how do I do this when not all fields will have a value? I have a total of 12 possible fields to use for searching, and they can search by just 1 or by all 12.
As I mentioned before, all of the questions I have been able to find refer to coming up with one static SQL query, instead of one that will have varying number of parameters.
I would go with:
$sql = "SELECT * FROM $table_name";
$where = array();
$params = array();
and then:
if(isset($city)) {
$where[] = "City LIKE ?";
$params[] = $city;
}
if(isset($bedrooms)) {
$where[] = "Bedrooms >= ?";
$params[] = $bedrooms;
}
if(isset($elementaryschool)) {
$where[] = "ElementarySchool = ?";
$params[] = $elementaryschool;
}
and finally:
if(!empty($where)) {
$sql .= "WHERE " . implode(" AND ", $where);
}
$result = $db->prepare($sql)->execute($params);
PLEASE NOTE that here, since I do not know what kind of database layer/abstraction you are using, $db represents the database connection, prepare() is used to create a prepared statement, and execute() tu run it, as you would do using PDO; this also protects against SQL injection.

Dynamic sql search in php

Trying to create a dynamic search functionality.
Goal : allowing user to search by email (if not empty), if empty (by last name), if both are not empty, than by both, etc.
I know I can write if statement depicting every scenario and than insert SQL command based on that, question is can this be handled in a more simplified manner. Thanks for your help.
Current function set up does OR across all fields, values are coming from $_POST:
find_transaction($email,$last_name,$first_name, $transaction_id)
{
GLOBAL $connection;
$query = "SELECT * ";
$query .= "FROM transactions WHERE ";
$query .= "email='{$email}' ";
$query .= "OR last_name='{$last_name}' ";
$query .= "OR first_name='{$first_name}' ";
$query .= "OR transaction_id='{$transaction_id}' ";
$query .= "ORDER BY date DESC";
$email = mysqli_query($connection,$query);
confirm_query($email);
return $email;
}
I do this all the time, it's not too much work. Basically build your WHERE statement dynamically based off your POST variables, using a series of if statements.
For example:
$where_statement = "";
// First variable so is simpler check.
if($email != ""){
$where_statement = "WHERE email = '{$email}'";
}
// Remaining variables also check if '$where_statement' has anything in it yet.
if($last_name != ""){
if($where_statement == ""){
$where_statement = "WHERE last_name = '{$last_name}'";
}else{
$where_statement .= " OR last_name = '{$last_name}'";
}
}
// Repeat previous 'last_name' check for each remain variable.
SQL statement would change to:
$query = "SELECT * FROM transactions
$where_statement
ORDER BY date DESC";
Now, the SQL will only contain filters depending on what values are present, so someone puts in just email, it would generate:
$query = "SELECT * FROM transactions
WHERE email = 'smith#email.com'
ORDER BY date DESC";
If they put in just last name, it would generate:
$query = "SELECT * FROM transactions
WHERE last_name = 'Smith'
ORDER BY date DESC";
If they put both, would generate:
$query = "SELECT * FROM transactions
WHERE email = 'email#email.com' OR last_name = 'Smith'
ORDER BY date DESC";
Etc., etc.
You could add as many variables you wish here, and basically if the specific variable is not blank, it will add it to the "$where_statement", and depending on if there is anything in the "$where_statement" yet or not, it will decide to start with = "WHERE ", or append .= " OR" (notice the '.=' and the space before 'OR'.
Better use Data Interactive table : http://datatables.net/
It's useful and no SQL-injection :) Good luck !

A way to skip over a row if it has already been displayed

I have a search script that retrieves an integer from one table and uses it to search through the IDs of a 2nd table. My issue is if the integer in Table1 appears more then once, I get duplicate results when querying Table2.
Does anyone know a way to use SQL or PHP so that if a row is already displayed it will skip it? Thanks
My code is rather convuleted but here it is if it helps:
//TV FILTERS
$sql = 'SELECT * FROM `table1`';
$where = array();
if ($searchlocation !== 'Any') $where[] = '`value` LIKE "%'.$searchlocation.'%"';
if ($searchmake !== 'Any') $where[] = '`value` LIKE "%'.$searchmake.'%"';
if ($searchtype !== 'Any') $where[] = '`value` LIKE "%'.$searchtype.'%"';
if (count($where) > 0) {
$sql .= ' WHERE '.implode(' OR ', $where);
} else {
// Error out; must specify at least one!
}
$tvqresult = mysql_query($sql);
$num_rowstvq = mysql_num_rows($tvqresult);
while ($rowtvq = mysql_fetch_array($tvqresult)) {
$contid = $rowtvq['contentid'];
//MAIN QUERY
$mainsql = 'SELECT * FROM `table2` WHERE `content` LIKE "%' . $searchterm . '%" AND `id` = ' . $rowtvq['contentid'] . ' AND `template` = 12';
$resultmain = mysql_query($mainsql);
$num_rowsmain = mysql_num_rows($resultmain);
if (!$resultmain) {
continue;
}
else {
while ($row = mysql_fetch_array($resultmain )) {
echo "[!Ditto? &parents=`134` &documents=" . $row['id'] . "&tpl=`usedtempchunk`!]";
}//END MAIN LOOP
}//END MAIN ELSE
}//END TV WHILE LOOP
You only seem to use the contentid column from your first query, so you could change it to:
$sql = 'SELECT distinct contentid FROM `table1`'; // rest would be the same
which would mean that no duplicates will be retreived saving you any hassle in changing your second set of code.
If you are using other columns from the first query somewhere else in your code, you can still fetch more columns with this method as long as there are no duplicate IDs:
$sql = 'SELECT distinct contentid, contentTitle, contentThing FROM `table1`';
If you have to have repeated IDs in your original query, I think you will have to store the data in a variable (like an array) and then make sure that the second dataset isn't repeating anything.
It sounds like you're only looking for 1 row, if so, then at the end of your SQL, simply add LIMIT 1. That'll ensure you only return 1 row, thereby ignoring any duplicate matches.

SELECT MYSQL record containing 2 possible values

I would like to Select rows where a value is being returned. If they have chosen Male or Female in the select box, I would want it to search for that. That part is working fine. However, if they choose Either, I want it to say that MySQL should look if the column contains Male or Female and return any results.
Please note that I do not want to use OR statements inside the query if possible based on how the code is being written out.
I tried the below, but it did not seem to work. The values are coming from a select box in a form which has Either, Male or Female.
if ($postgender == "either")
{
$male = "Male";
$female = "Female";
$postgenderuse = ($male || $female);
}
else {
$postgenderuse = $postgender;
}
$query4 = mysql_query("SELECT * FROM tennis WHERE gender='$postgenderuse' ORDER BY playerid DESC LIMIT 0,20");
start creating the query from statements, also check if the form is sending one of the 3 values (just to make sure)
if ($postgender == "Either")
{
$postgenderuse = " ( `gender`='Male' OR `gender`='Female' ) ";
}
elseif ($postgender == "Male" || $postgender == "Female") {
$postgenderuse = " `gender`='".$postgender."' ";
}
else {
die('Error, no gender selected');
}
$query4 = mysql_query("SELECT * FROM `tennis` WHERE ".$postgenderuse." ORDER BY `playerid` DESC LIMIT 0,20");
Assuming that you're treating gender in binary terms, as consisting of only two options (Male, Female):
$sql = "SELECT * FROM tennis";
if(in_array($postgender, array("Male", "Female"))
{
$sql .= " WHERE gender=".$postgender;
}
$sql .= " ORDER BY playerid DESC LIMIT 0,20)";
$query4 = mysql_query($sql);
if It is either, then change your query to do a wild card search.
SELECT * FROM tennis WHERE gender LIKE '$postgenderuse'
That way, when they choose either, you can set postgenderuse to a % Sign.
Although, it might be a better idea to just use OR in your query, and build your query off of conditions, like:
if($postgender == "Male") {
$condition = "WHERE gender='Male'";
} else if($postgender == "Female") {
$condition = "WHERE gender='Female'";
} else {
$condition = "";
}
$query = "SELECT * FROM tennis " . $condition . " ORDER BY BLAH";
In anycase, either way should work. Being able to construct queries from conditionals is part of the power of php.
~ Dan
The solution you have tried would work if you were using Bitwise instead of String for the field gender.
What I suggest, is to use the SQL IN function.
Something like:
$query = "SELECT * FROM tennis WHERE gender IN ('" + implode("', '", $postGenderArray) + "')";

Drafting SQL search query based on user entry

I'm currently coding a simple search script in PHP that requires three variables from the user namely:
$Capacity, $Location and $RoomType
Capacity is a required field which the jquery validate plugin checks for numerical entry on input - but Location and RoomType are optional.
I'm trying to now draft a SQL query that will search the table rooms.
There are three columns in the table also called Capacity, Location and RoomType that I want to search using the variables.
How would I write this SQL query? Especially with $Capacity being required, $Location / $RoomType expected to be left blank or filled in at the users discretion?
You could use LIKE ...% in your sql query, so that even when blank, it'll be treated as a wildcard.
$q = 'SELECT * FROM foo WHERE capacity = "'.$capacity.'" AND location LIKE "'.$location.'%" AND roomtype LIKE "'.$roomtype.'%"';
Of course, remember to escape the inputs.
Something like this should work:
function BuildSearchQuery($Capacity, $Location, $RoomType)
{
$where = array();
if (!empty($Capacity))
{
$where[] = "Capacity = '" . mysql_real_escape_string($Capacity) . "'";
}
if (!empty($Location))
{
$where[] = "Location = '" . mysql_real_escape_string($Location) . "'";
}
if (!empty($RoomType))
{
$where[] = "RoomType = '" . mysql_real_escape_string($RoomType) . "'";
}
if (empty($where))
{
return false;
}
$sql = "select * from `table` where ";
$sql += implode(" AND ", $where);
return $sql;
}
Although nowadays many frameworks exists that allow you to do this more easily and less error-prone than manually crafting queries.
$query =select * from table where Capacity =$Capacity
if(isset($Location) && $Location!='') $query.= and Location LIKE '%$location%'
if(isset($RoomType) && $RoomType!='') $query.= and RoomType LIKE '%$RoomType%'
Making use of LIKE or = operator in query is upto you.
Depend on how complex it is (and or not ???)
But basically
Select ... From Rooms Where Capacity = #Capacity
and ((Location = #Location) Or (IsNull(#Location,'') = ''))
and ((RoomType = #RoomType) or (IsNull(#RoomType,'') = ''))
Or some such.
If you aren't using parameterised queryies then replace #.... with the escaped inputs.

Categories