Building a Dynamic MySQL Query Based on Multiple Variables and Conditions - php

I am hoping this title represents this question well. I am attempting to build a dynamic query based on multiple $vars existing. I am attempting to make this work using a simple if/ifelse/else block but can't seem to get it to work correctly. The first if statements execute accordingly but the third fails. I am new to PHP so I am assuming this a beginner mistake. I also believe there is most likely a far more eloquent way to achieve the desired results.
Basically the user enters a few inputs into multiple text fields. Only one field, out of the 3 needs to contain a value, but 2 or all 3 can as well. If the value does not exist in a field it should generate a Query based on the values provided. I am validating and a creating a variable for each input than checking to see if those variables contain a value or exist.
//////////////////////////////////////////////////////
if(isset($_POST['inputName']) && $_POST['inputName'] != ""){
$inputName = preg_replace('#[^a-z 0-9?!]#i', '', $_POST['inputName']);
}
if(isset($_POST['inputState']) && $_POST['inputState'] != ""){
$inputState = preg_replace('#[^a-z 0-9?!]#i', '', $_POST['inputState']);
}
if(isset($_POST['inputCost']) && $_POST['inputCost'] != ""){
$inputCost = preg_replace('#[0-9]#i', '', $_POST['inputCost']);
}
///////////////////////////////////////////////////////
if (!empty($inputName) AND !empty($inputState) AND !empty($inputCost)){
$sqlCommand = "SELECT * FROM hciproject WHERE school_name LIKE '%$inputName%' AND school_state LIKE '%$inputState%' AND school_cost < '$inputCost'";
}
elseif (!empty($inputName) AND !empty($inputState)){
$sqlCommand = "SELECT * FROM hciproject WHERE school_name LIKE '%$inputName%' AND school_state LIKE '%$inputState%'";
}
elseif (!empty($inputName) AND !empty($inputCost)){
$sqlCommand = "SELECT * FROM hciproject WHERE school_name LIKE '%$inputName%' AND school_cost < '$inputCost'";
}
elseif (!empty($inputState) AND !empty($inputCost)){
$sqlCommand = "SELECT * FROM hciproject WHERE school_state LIKE '%$inputState%' AND school_cost < '$inputCost'";
}
else{
$searchOut .= "0 Results Found";
}
// Connect to DB
include_once("database_connection.php");
$query = mysql_query($sqlCommand) or die(mysql_error());
$count = mysql_num_rows($query);
///////////////////////////////////////////////////////
Additionally I was going to create elseif statements containing only one variable.
Any help with this would be greatly appreciated.

try this:
$inputName = preg_replace('#[^a-z 0-9?!]#i', '',& $_POST['inputName']);
$inputState = preg_replace('#[^a-z 0-9?!]#i', '',& $_POST['inputState']);
$inputCost = preg_replace('#[0-9]#i', '',& $_POST['inputCost']);
$selectCondition = 1;
if($inputName) $selectCondition.= " and school_name LIKE '%$inputName%' ";
if($inputState ) $selectCondition.= " and school_state LIKE '%$inputState%' ";
if($inputCost ) $selectCondition.= " and school_cost < $inputCos ";
Important:
& $_POST['inputName'] is equal to (isset($_POST['inputName']) && $_POST['inputName'] != "")

Related

Undefined variable array

I get an error on line 15 that says "Undefined variable: row2". How can I resolve this?
$limit = 20;
$res1 = mysql_query('SELECT *
FROM contact
WHERE name = "Greg"');
$res2 = mysql_query('SELECT name
FROM contact c, passport p
ON c.idNum = p.iNum
WHERE date >= "2015-03-03" AND t< "2015-03-21');
if(!$res1 && !$res2) {
die('Query no valid: ' . mysql_error());
}
else {
while(($row1 = mysql_fetch_array($res1)) || ($row2 = mysql_fetch_array($res2))) {
$sub = $row1['num'] - $row2['num'];
if($sub <= $limit) {
echo '<br>row name is: ', $row2['name'];
}
}
}
What I'm trying to do is get a number from the first table (it only results to just Greg's row). Then subtract it with the numbers from the results of the second table. The result of this is placed into the sub variable and it's check to see if it's <= 20. If yes, it prints out the row. If not, it goes back to while loop to check another row. Am I going about the right way so far?
You need to change the while() loop's condition. Consider this example:
$a = 1;
if ($a == 1 || $b = 2) {
var_dump(isset($b));
}
Output of var_dump() will be boolean false because $b does not exist, which is the same case why your $row2 is undefined.
The thing is, while evaluation conditions with ||, PHP will stop evaluating other conditions once the match is found, so other comparisons or assignments on the right side will not be performed.
Change your while to be like this, you need both $row1 and $row2 anyway:
while(($row1 = mysql_fetch_array($res1)) && ($row2 = mysql_fetch_array($res2))) {
(note the && instead of ||)
Also, looks like you may want to use SELECT c.* in your second query, too, because you're only selecting the name column, and trying to use num too.
Note : Select all columns in your 2nd Query if num is already available in your columns so your problem will be solved then.!
Note : Try to replace || with && and you will be good to go.
By using || or OR as in conceptional language as I would say it.You are making the code like in a way that either and only one will pass but if you are passing both ones so then you should replace || with && so that's why your $row2 will be already created then so it will be available for more operation.!
$limit = 20;
$res1 = mysql_query('SELECT *
FROM contact
WHERE name = "Greg"');
$res2 = mysql_query('SELECT *
FROM contact c, passport p
ON c.idNum = p.iNum
WHERE date >= "2015-03-03" AND t< "2015-03-21');
if(!$res1 && !$res2) {
die('Query no valid: ' . mysql_error());
}
else {
while(($row1 = mysql_fetch_array($res1)) && ($row2 = mysql_fetch_array($res2))) {
$sub = $row1['num'] - $row2['num'];
if($sub <= $limit) {
echo '<br>row name is: ', $row2['name'];
}
}
}

PHP mysql Query Builder that displays just what I want

I'm relatively new to PHP and I need some help on a search query.
I have a few drop down 'select' and a 'checkbox group' which will filter the search from database using (...WHERE somethingA = 'somethingA' && somethingB = 'somethingB' etc)
That's all working great but the problem comes when I want to make it so that some search fields DONT have to be used, so if 'SomethingA' is either disabled or value='none' then it will only return WHERE somethingB = 'SomethingB'.
I have tried using OR instead of AND but that returns both values if they are true and not really filtering it properly.
my initial solution was to have if..else statements to define the query,
for example:
$query = "SELECT * FROM table";
$results = $con->query("$query $where $QueryA $QueryB $QueryC");
if($_GET['SomethingA'] == "none" && $_GET['SomethingB'] == "none" && $_GET['SomethingC'] == "none"){
$where = ""
$QueryA = ""
$QueryB = ""
$QueryC = "ORDER by ID" //if all search field is 'none' then get all results
}elseif($_GET['SomethingB'] == "none" && $_GET['SomethingC'] == "none"){
$where = "WHERE"
$QueryA = "SomethingA = '{SomethingA}'" //only use A filter one field
$QueryB = ""
$QueryC = ""
}elseif($_GET['SomethingA'] == "none" && $_GET['SomethingC'] == "none"){
$where = "WHERE"
$QueryA = ""
$QueryB = "SomethingB = '{SomethingB}'" //only use B filter one field
$QueryC = ""
.....
it works but you can already see the problem as if i wanted to cross matrix all conditions it becomes very lengthy and confusing.
So my question is whether there is a much better way of doing this, for instance, make value='none' return all results?
been looking around and attacking it from many angles but cant find a solution..
maybe javascript could help but im not the best with it.
thanks in advance
The question is not too clear but look into this. It should help.
$query="SELECT * FROM table WHERE";
$query_link = " AND ";
$isASet=false;
$isBSet=false;
$isCSet=false;
if(strcmp($_GET['SomethingA'],"none") != 0){
$query.=" column = {$_GET['SomethingA']}";
//set this to true for later if statements
$isASet=true;
}
if(strcmp($_GET['SomethingB'],"none") != 0){
//check if A has been set, if yes include an AND
if($isASet){
$query.=$query_link;
}
//include this one as usual
$query.=" column = {$_GET['SomethingB']}";
$isBSet=true;
}
if(strcmp($_GET['SomethingC'],"none") != 0){
//check if A or B has been set, if yes include an AND
if($isASet || $isBSet){
$query.=$query_link;
}
//include this as usual
$query.=" column = {$_GET['SomethingC']}";
}
//run query and collect result
$result = $connection->query($query);

PHP Search Query is not working

I am trying to do a search on my website but for some reason my SELECT query is swapping the keyword and name of the column name when it is executed. Below is code for my query:
if(empty($_POST)=== false){
$output = '';
$error = '';
$input = $_POST['search_input'];
$i=0;
if($input){
$keyword = explode(" ", $input);
require ('core/dbconnection.php');
//If a user is logged in check if the user is Admin or Customer.
if(isset($_SESSION['userid'])){
if($admin == 1){
//enter admin code here
}
}else{
//If user is not logged in search items table only.
$search_items = "SELECT * FROM fyp_items WHERE ";
foreach($keyword as $k){
$i++;
if($i == 1){
$search_items .= "name LIKE $k OR description LIKE $k";
}else
$search_items .= " OR name LIKE $k OR description LIKE $k";
}
$item_qry = mysql_query($search_items)or die(mysql_error());
}
}else
$error = '<p class="pageerror">Please enter your search terms.</p>';
The $search_items is concatanating the search query which is then executed by $item_query .
So I searched for "conwerse" and echo'ed out the $search_itemsvariable I got the following:
http://awesomescreenshot.com/0302ft5mc3
However, when I run the query I get this mysql_error...
http://awesomescreenshot.com/0552ft6bb4
Seems like it swaps the keyword and column name when I run the query. My database tables are of type InnoDB> I would much appreciate your help!
First of all, dont use mysql_query as all mysql_ functions are deprecated. Use mysqli or pdo.
Second, escape your keywords with mysql_escape_string();, like
$k = mysql_real_escape_string($k);
Third, your query, when you echo it, needs to look like this:
SELECT * FROM fyp_items WHERE `name` LIKE 'conwerse' OR `description` LIKE 'conwerse';
There is more, but this should get you started.

php mysql multiple field search empty fields

<?php
if(isset($_POST['submit'])) {
$fields = array('field1', 'field2', 'field3');
$conditions = array();
foreach($fields as $field){
if(isset($_POST[$field]) && $_POST[$field] != '') {
$conditions[] = "`".$field."` like '%" . mysql_real_escape_string($_POST[$field]) . "%'";
}
}
$query = "SELECT * FROM customer ";
if(count($conditions) > 0) {
$query .= "WHERE " . implode (' AND ', $conditions);
}
$result = mysql_query($query);
$say = mysql_num_rows($result);
if ($say == 0) {
echo "<tr>no result.</tr>";
} else {
echo '...';
while($row = mysql_fetch_array($result))
{
...
}}
} ?>
Why doesn't this code checking empty fields? It returns results that has empty field even form submits empty.
The only improvement I think of is trim():
if(isset($_POST[$field]) && trim($_POST[$field]) != '') {
however, I am sure it is not the issue.
Have you ever thought of printing the resulting query out?
Look, you're writing a program to create some string (SQL query). But for some reason never interested in this program's direct result, judging it by some indirect results. May be it's data/query logic makes such results, but the query itself is okay?
if the query is still wrong - continue debugging.
Echo everything involved - print variables, condition results, intermediate results in the loop - and look for inconsistencies
$query = "SELECT * FROM customer ";
if(count($conditions) > 0) {
$query .= "WHERE " . implode (' AND ', $conditions);
}
When form is submitted empty ($conditions=0) it returns all table (select * from customer).
Added an else condition and fixed. Thanks for print query advices.
For checking something is empty or not. You can use empty() method.
Check this:
empty()
isset() only check whether that object/variable is set or not. For more details check this
isset()

table updates empty spaces when user do not enter anything to the textbox

i am doing a project where one may update the name, position, department and tag of the employee.
But as i do my project, it wont update, i know there is something wrong with my code. would you guys mind checking it.
my php page has an index.php which is the main menu, if you click the employee name in the list, a pop up window will appear. that pop up is for updating.
my php code (it now updating) but errors found:
<?php
$con=mysql_connect('localhost','root','pss') or die(mysql_error());
mysql_select_db('intra',$con);
if(isset($_POST['submitted']))
{
$sql = "SELECT * FROM gpl_employees_list where emp_id='".$_POST['eid']."'";
$result = mysql_query($sql) or die (mysql_error());
if(!$result || mysql_num_rows($result) <= 0)
{
return false;
}
$qry = "UPDATE gpl_employees_list SET emp_nme = '".$_POST['ename']."', emp_pos = '".$_POST['pos']."', emp_dep = '".$_POST['dep']."', emp_tag = '".$_POST['tag']."' WHERE emp_id = '".$_POST['eid']."' ";
mysql_query($qry) or die (mysql_error());
?><script>window.close();</script><?php
}
?>
*NOTE : this is now updating, but if a user leaves one of the textboxes empty, it updates the table with empty spaces as well and that is my problem now. how do i avoid that? i mean if a user leaves one textbox empty,the data with empty values must still contain its old value,but how to do that with this code? thanks for those who will help
MisaChan
You use $_POST for 'name/pos/dep/tag' and $_GET for 'emp' so you're probably not getting the values.
Change the GETs to POST - that should do it.
Since you're updating, I'd recommend using POST over GET.
GET is more appropriate for searching.
Also, you can put all your update queries into one update query.
Like so.
$name = $_POST['name'];
$pos = $_POST['pos'];
$dep = $_POST['dep'];
$tag = $_POST['tag'];
$emp = $_POST['emp'];
$qry_start = "UPDATE gpl_employees_list SET ";
$where = " WHERE emp_id = $emp";
$fields = "";
$updates = "";
if($name){
$updates .= " `emp_name` = $name,";
}
if($pos){
$updates .= " `emp_pos` = $pos,";
}
if($dep){
$updates .= " `emp_dep` = $dep,";
}
if($tag){
$updates .= " `emp_tag` = $tag,";
}
$updates = substr($updates, 0, -1); //To get rid of the trailing comma.
$qry = $qry_start . $updates . $where;
this is what i used to keep it working :) i hope this could be a source for others as well :)
$col['emp_nme'] = (trim($_POST['ename']))?trim($_POST['ename']):false;
$col['emp_pos'] = (trim($_POST['pos']))?trim($_POST['pos']):false;
$col['emp_dep'] = (trim($_POST['dep']))?trim($_POST['dep']):false;
$col['emp_tag'] = (trim($_POST['tag']))?trim($_POST['tag']):false;
// add a val in $col[] with key=column name for each corresponding $_POST val
$queryString ="UPDATE `gpl_employees_list` SET ";
foreach($col as $key => $val){
if($val){
$queryString .="`".$key."`='".$val."',";
}
}
$queryString = substr($queryString ,0 ,strlen($queryString) - 1 )." WHERE emp_id = '".$_POST['eid']."'";
mysql_query($queryString);
After making changes to an SQL database, remember to commit those changes, otherwise they'll be ignored.

Categories