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) + "')";
Related
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 !
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.
After hours of trying I need your advice.
I want to combine rows from 2 tables.
After I created a new row in table1 I want to find a row in table2 and combine some of the fields.
If I put the nested SELECT in the SET function
(SET postcode=(SELECT etc)
is works, but if I put it in the FROM function is gives an Error that the syntax is wrong
my code:
$sql = "INSERT INTO instanties(institution, category, postcode)
VALUES('$emapData[0]', '$emapData[1]', '$emapData[2]')";
if ($conn->query($sql) === TRUE) {
//get last added id
$last = $conn->insert_id;
//define WHERE function
$where="postcode_id=$postcode_id AND (minnumber <= $number AND maxnumber >= $number)";
//UPDATE last added row in table with info from other table
$sql2 = "UPDATE instanties
SET postcode_id=pc.postcode_id
FROM
(
SELECT postcode_id
FROM postcode
WHERE $where LIMIT 1
) pc
WHERE id=$last";
$result = $conn->query($sql2);
if ($result) {
echo 'update is done<br/><br/>';
}
}
else {
echo "Error: " . $sql2 . "<br>" . $conn->error.'<br/><br/>';
}
}
else {
echo "Error: " . $sql . "<br>" . $conn->error.'<br/><br/>';
}
That's not a valid MySQL syntax. You cannot add a "FROM" clause to an UPDATE statement.
http://dev.mysql.com/doc/refman/5.0/en/update.html
However, what you want to accomplish is still possible this way:
$sql2 = "UPDATE instanties
SET postcode_id=
(
SELECT postcode_id
FROM postcode
WHERE $where LIMIT 1
)
WHERE id=$last";
As long as there is only 1 result from the nested SELECT (and your LIMIT 1 kinda does that).
EDIT:
If you need many fields from the postcode table, you can join on it:
$sql2 = "UPDATE instanties as i
JOIN (
SELECT *
FROM postcode
WHERE $where LIMIT 1
) as pc
SET i.postcode_id=pc.postcode_id
WHERE i.id=$last";
We would usually use an "ON" clause with the join, but since you're only updating 1 row and your nested SELECT will also only return 1 row, it's not necessary.
try this:
$sql2 = "UPDATE instanties
SET postcode_id=(
SELECT postcode_id
FROM postcode
WHERE $where LIMIT 1)
WHERE id=$last";
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.
I have a php driven page that allows me to enter search parameters. One of these numbers is an ID that consists of several digits. When I search for one with these specific digits it returns all results.
I have done the exact same statement in phpmyadmin and the SQL terminal and it returns just the item I searched for. So I suppose the problem lies with the PHP I am using to submit the search query based on the html form.
The drop down with the status options works fine - any of the fields that requires input do not.
Also I am sure the fields are submitting to the database because I can view them and complete SQL statements with them in phpadmin
EDIT echo result when NumericIdentider is entered and default status of all is selected: Select * From Table Where Closed != ' '
<?php
if($_REQUEST['Search']) {
$sql = "SELECT";
if(strlen($_REQUEST['NumericIdentifier']) > 0) {
$sql .= " * FROM Table Where NumericIdentifier = ".$_REQUEST['NumericIdentifier'];
}
if(strlen($_REQUEST['BeginDate']) > 0) {
$sql .= " * From Table Where TDate >= {$_REQUEST['BeginDate']}";
}
if(strlen($_REQUEST['EndDate']) > 0) {
$sql .= " * From Table Where TDate <= {$_REQUEST['EndDate']}";
}
if($_REQUEST['Status'] == 'Shipped') {
$sql .= "* From Table Where Closed = 'true' ";
}
if($_REQUEST['AreaCode'] > 0) {
$sql .= " * From Table Where AreaCode = {$_REQUEST['AreaCode']}";
}
if($_REQUEST['Status'] == 'Recieved') {
$sql .= " * From Table Where Closed != 'true'";
}
if($_REQUEST['Status'] == 'All') {
$sql = "Select * From Table Where Closed != '\0'";
}
} else {
$sql = "SELECT * FROM Tickets";
}
$res = mysql_query($sql, $conn1);
while($a = mysql_fetch_array($res)) {
echo "<tr><td> <a href='ticket.php?id=".$a['id']."'>".trim($a['id'])."</a> </td> \n <td> ".$a['Name']."</td> \n <td>".date("m/d/Y", strtotime($a['TicketDate']))."</td> \n <td>".$a['Issue']."</td> \n <td>".Showstatus($a['Closed'])." </td></tr>";
} ?>
</table>
</body>
</html>
Yeesh, your SQL will never work. Let's say the user enters both a BeginDate and and EndDate, your query will be
SELECT
* From Table Where TDate >= {$_REQUEST['BeginDate']}
* From Table Where TDate <= {$_REQUEST['EndDate']}
Even if the dates were entered properly in MySQL form (YYYY-MM-DD), it will still come out as
SELECT
* FROM Table Where TDate >= 01/01/2011
* FROM Table Where TDate <= 31/12/2011
Notice there's no quotes around the dates. MySQL will see those "dates" as being numbers, being divided, so you're saying TDate >= 0.0004972... and TDate <= 0.001284...
On top of that, saying * from table twice is also illegal syntax.
Your code is very obviously NOT checking for error states. At absolute bare minimum you should have:
$result = mysql_query($sql) or die(mysql_error());
which will tell you exactly what's wrong with the query you've constructed.
And, worst of all, as others have said, you're completely open and vulnerable to SQL injection attacks, but I'm not going to go into that... your query is so hopeless broken already that an injection attack is the least of your worries.