I have a search function that lets you input into different type boxes of the last, first and middle names. I don't have any problems with the code, but does anyone know how to optimize it?
The code has multiple if statements that finds out what textbox is unempty and that is then used in the WHERE as you can see below:
$where1 = $_POST['firstname'];
$where2 = $_POST['midname'];
$where3 = $_POST['lastname'];
if(!empty($where1) && empty($where2) && empty($where3)){
$result = $connection->query("SELECT * FROM senior WHERE firstname = '$where1'");
} else if(!empty($where1) && !empty($where2) && empty($where3)){
$result = $connection->query("SELECT * FROM senior WHERE firstname = '$where1' AND midname = '$where2'");
} else if(!empty($where1) && !empty($where2) && !empty($where3)){
$result = $connection->query("SELECT * FROM senior WHERE firstname = '$where1' AND midname = '$where2' AND lastname = '$where3' ");
} else if(!empty($where1) && empty($where2) && !empty($where3)){
$result = $connection->query("SELECT * FROM senior WHERE firstname = '$where1' AND lastname = '$where3' ");
} else if(empty($where1) && !empty($where2) && !empty($where3)){
$result = $connection->query("SELECT * FROM senior WHERE lastname = '$where3' AND midname = '$where2' ");
} else if(empty($where1) && !empty($where2) && empty($where3)){
$result = $connection->query("SELECT * FROM senior WHERE midname = '$where2'");
} else if(empty($where1) && empty($where2) && !empty($where3)){
$result = $connection->query("SELECT * FROM senior WHERE lastname = '$where3'");
}
My suggestion for you
$where = '';
if($where1) $where .= ($where ? " AND " : " ")."firstname = '$where1'";
if($where2) $where .= ($where ? " AND " : " ")."midname = '$where2'";
if($where3) $where .= ($where ? " AND " : " ")."lastname = '$where3'";
$query = "SELECT * FROM senior".($where ? " WHERE ".$where : "");
$result = $connection->query($query);
First of all, I encourage you to use Prepared Statements in order to improve security among other things.
Related with the code you write above you can try something like this:
$query = "SELECT * FROM senior";
$firstcondition = true;
if (!empty($where1))
addConditon($query, "firstname = ".$where1);
if (!empty($where2))
addConditon($query, "midname = ".$where2);
if (!empty($where3))
addConditon($query, "lastname = ".$where3);
$result = $connection->query($query);
function addCondition($query, $condition) {
if (!$firstcondition)
$query.= " AND ";
else {
$firstcondition = false;
$query.= " WHERE ";
}
$query.= $condition;
}
Just a suggestion: why not use LIKE, because it is a search query?
$where1 = $_POST['firstname'];
$where2 = $_POST['midname'];
$where3 = $_POST['lastname'];
$result = $connection->query("SELECT * FROM senior WHERE firstname LIKE '%".$where1."%' AND midname LIKE '%".$where2."%' AND lastname LIKE '%".$where3."%' ");
Related
I have a form with multiple inputs which are my filters.
This is my code (not all of it, just the part I want to fix):
$req_resumo = '';
$req_status = '';
$req_usuario = '';
$n_req = 0;
$parametros = "";
// Checks which fields are filled and increases the number of filters for future usage
if (isset($_POST['usuario']) && $_POST['usuario'] != "") {
$req_usuario = $_POST['usuario'];
$n_req++;
}
if (isset($_POST['resumo']) && $_POST['resumo'] != "") {
$req_resumo = $_POST['resumo'];
$n_req++;
}
if (isset($_POST['status']) && $_POST['status'] != "") {
$req_status = $_POST['status'];
$n_req++;
}
// Then (there is some code between these parts)
if ($n_req > 0 && $funcao != 'usuario') $parametros.= " where ";
if ($req_usuario != "") {
$parametros.= " usuario = '$req_usuario' ";
if ($n_req > 1) $parametros.= " and ";
}
if ($req_resumo != "") {
$parametros.= " resumo = '$req_resumo' ";
if ($n_req > 1 && ($req_status != "") || ($req_data_inicial != "")) $parametros.= " and ";
}
if ($req_status != "") {
$parametros.= " status = '$req_status' ";
}
// This will create the query and add the parameters string at the end.
$tot = mysqli_query($con, "SELECT * FROM solicitacoes $parametros");
This code looks ugly, and even for me (begginer), it doesn't feels right, does not sounds like the way of coding.
So, is there any better and easier way of building this code?
Give this a try. From my testing locally (without db) looked right.
$n_req = 0;
$_POST['usuario'] = 'test';
$_POST['resumo'] = 'test2';
$_POST['status'] = 'test3';
if (!empty($_POST['usuario'])) {
$req_usuario = $_POST['usuario'];
$where[] = " usuario = ? ";
$params[] = $req_usuario;
$n_req++;
}
if (!empty($_POST['resumo'])) {
$req_resumo = $_POST['resumo'];
$where[] = " resumo = ? ";
$params[] = $req_resumo;
$n_req++;
}
if (!empty($_POST['status'])) {
$req_status = $_POST['status'];
$where[] = " status = ? ";
$params[] = $req_status;
$n_req++;
}
$sql_where = !empty($where) ? ' where ' . implode(' and ', $where) : '';
echo $sql_where;
$tot = mysqli_prepare($con, "SELECT * FROM solicitacoes $sql_where");
if(!empty($params)) {
//foreach($params as $param) {
// mysqli_stmt_bind_param($tot, "s", $param);
//echo $param;
//}
$params = array_merge(array($tot),
array(str_repeat('s', count($params))),
array_values($params));
print_r($params);
call_user_func_array('mysqli_stmt_bind_param', $params);
// adapated from https://stackoverflow.com/questions/793471/use-one-bind-param-with-variable-number-of-input-vars and http://www.pontikis.net/blog/dynamically-bind_param-array-mysqli may need to be altered
}
echo "SELECT * FROM solicitacoes $sql_where";
mysqli_execute($tot);
If all three values are populated your query should be
SELECT * FROM solicitacoes where usuario = ? and resumo = ? and status = ?
The ? are populated with the values by the driver later in the process. This prevents the user(s) from adding in malicious code to manipulate the SQLs processing.
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet#Defense_Option_1:_Prepared_Statements_.28Parameterized_Queries.29
How can I prevent SQL injection in PHP?
I also didn't see where $funcao was set..
You can comment out the mysqli functions and decomment out the echo lines to see what the code does. That is how I confirmed queries were being built as expected.
$predicates = array();
if ($_POST['usuario'] != "") {
$predicates[] = "usuario = '{$_POST["usuario"]}'";
}
if ($_POST['resumo'] != "") {
$predicates[] = "resumo = '{$_POST["resumo"]}'"
}
if ($_POST['status'] != "") {
$predicates[] = "status = '{$_POST["status"]}'"
}
if (count($predicates) == 0) {
// handle case when nothing specified in POST
} else {
$tot = mysqli_query($con, "SELECT * FROM solicitacoes WHERE "
. implode(" and ", $predicates) );
}
I may not have all your logic exactly as required ... but the ideas are there. Use implode() to insert and between the predicates of your WHERE clause (it'll figure out how many are needed, if any). Also, since it is your HTML form that is submitting the POST, you can be certain that at least some value is being passed for each POST variable (so isset() is not required).
Edit: I've changed the query to this version but I'm still not getting any
results even when I should be.
if (isset($_POST['schbttn'])) {
$breed1 = $_POST['schbreed1'];
$breed2 = $_POST['schbreed2'];
$sex = $_POST['schsex'];
$colour = $_POST['schcolour'];
$age = $_POST['schage'];
include ('inc/dbconn.php');
// If breed2 NULL, search with this query
if ($breed2 == "NULL") {
$search = mysqli_query($dbconn, "SELECT * FROM `lstfnd` WHERE `doglf_stat` = 'Lost' AND `doglf_breed1` = '$breed1' AND `doglf_breed2` IS NULL AND `doglf_sex` = '$sex' AND `doglf_colour` = '$colour' AND `doglf_age` = '$age'");
// Else search with this query
} else {
$search = mysqli_query($dbconn, "SELECT * FROM `lstfnd` WHERE `doglf_stat` = 'Lost' AND `doglf_breed1` = '$breed1' AND `doglf_breed2` = '$breed2' AND `doglf_sex` = '$sex' AND `doglf_colour` = '$colour' AND `doglf_age` = '$age'");
}
$schrow = mysqli_fetch_assoc($search);
}
I'm trying to create a simple search function where a user can search by multiple fields.
I've taken the entries of each field
$breed1 = $_POST['breed1'];
$breed2 = $_POST['breed2'];
$sex = $_POST['sex'];
$colour = $_POST['colour'];
$age = $_POST['age'];
and built the query through if loops
$query = "SELECT * FROM `table` WHERE `stat` = 'Lost'";
// If breed1 is not ALL, add to search
if ($breed1 != "ALL") {
$query = $query." AND `breed1` = '$breed1'";
}
// If breed2 is not ALL, add to search
if ($breed2 != "ALL") {
if ($breed2 == "NULL") {
$query = $query." AND `breed2` IS NULL";
} else {
$query = $query." AND `breed2` = '$breed2'";
}
}
// If sex is not ALL, add to search
if ($sex != "ALL") {
$query = $query." AND `sex` = '$sex'";
}
// If colour is not ALL, add to search
if ($colour != "ALL") {
$query = $query." AND `colour` = '$colour'";
}
// If age is not ALL, add to search
if ($age != "ALL") {
$query = $query." AND `age` = '$age'";
}
$query = $query.";";
and placed the query in a PHP variable to use when running the query.
include ('inc/dbconn.php');
$search = mysqli_query($dbconn, "'.$query.'");
$schrow = mysqli_fetch_assoc($search);
However, when I try to display the results of the search, I get an error code.
mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null given...
So is what I am attempting possible to accomplish using this method? And if not, any suggestions for alternative methods?
change this line
$search = mysqli_query($dbconn, "'.$query.'");
to
$search = mysqli_query($dbconn, $query);
$query is variable, do not use that as string.
I have many nested ifs and conditions in my code but it is not giving the desired output. What is the best way to write the following code :
$driver_code = $this->input->post('filter_driver_code');
$unit_code = $this->input->post('filter_unit_code');
$fuel_type = $this->input->post('filter_fuel');
$date_to = $this->input->post('date_to');
$date_from = $this->input->post('date_from');
if (isset($date_from) and isset($date_to) and empty($unit_code) and empty($driver_code) and empty($fuel_type)) {
$sql = "SELECT * FROM fuel_usage where (date between '$date_from' and '$date_to') ";
$result = $this->db->query($sql);
} elseif (isset($driver_code) and isset($unit_code) and isset($fuel_type) and isset($date_from) and isset($date_to)) {
$sql = "SELECT * FROM fuel_usage where driver_code='$driver_code' AND unit_code='$unit_code' AND fuel_type='$fuel_type' and (date between '$date_from' and '$date_to')";
$result = $this->db->query($sql);
} elseif (empty ($date_from) and empty ($date_to) and isset ($unit_code) and isset ($driver_code) and isset ($fuel_type)) {
$sql = "SELECT * FROM fuel_usage where driver_code='$driver_code' AND unit_code='$unit_code' AND fuel_type='$fuel_type'";
$result = $this->db->query($sql);
} else {
$sql="SELECT * FROM FUEL_USAGE";
$result = $this->db->query($sql);
}
It does not give the right output.
Try all check with empty() may be isset() gives you problem cause on post isset for all variable will return true even values blank
if (!empty($driver_code) && !empty($unit_code) && !empty($fuel_type) && !empty($date_from) && !empty($date_to)) {
$sql = "SELECT * FROM fuel_usage where driver_code='$driver_code' AND unit_code='$unit_code' AND fuel_type='$fuel_type' and (date between '$date_from' and '$date_to')";
$result = $this->db->query($sql);
}elseif (!empty($date_from) && !empty($date_to) && empty($unit_code) && empty($driver_code) && empty($fuel_type)) {
$sql = "SELECT * FROM fuel_usage where (date between '$date_from' and '$date_to') ";
$result = $this->db->query($sql);
} elseif (empty($date_from) && empty($date_to) && !empty($unit_code) && !empty($driver_code) && !empty($fuel_type)) {
$sql = "SELECT * FROM fuel_usage where driver_code='$driver_code' AND unit_code='$unit_code' AND fuel_type='$fuel_type'";
$result = $this->db->query($sql);
} else {
$sql="SELECT * FROM FUEL_USAGE";
$result = $this->db->query($sql);
}
or try in short way
$sql = "SELECT * FROM fuel_usage where 1 ";
if (!empty($driver_code)) {
$sql .= " AND driver_code='$driver_code' ";
}
if (!empty($unit_code)) {
$sql .= " AND unit_code='$unit_code' ";
}
if (!empty($fuel_type)) {
$sql .= " AND fuel_type='$fuel_type' ";
}
if (!empty($date_from) && !empty($date_to)) {
$sql .= " AND date between '$date_from' and '$date_to' ";
}
$result = $this->db->query($sql);
if (!empty($driver_code) && !empty($unit_code) && !empty($fuel_type) && !empty($date_from) && !empty($date_to)) {
$sql = "SELECT * FROM fuel_usage where driver_code='$driver_code' AND unit_code='$unit_code' AND fuel_type='$fuel_type' and (date between '$date_from' and '$date_to')";
$result = $this->db->query($sql);
}
elseif(!empty ($unit_code) && !empty ($driver_code) && !empty ($fuel_type)) {
$sql = "SELECT * FROM fuel_usage where driver_code='$driver_code' AND unit_code='$unit_code' AND fuel_type='$fuel_type'";
$result = $this->db->query($sql);
}
elseif (!empty($date_from) and !empty($date_to)) {
$sql = "SELECT * FROM fuel_usage where (date between '$date_from' and '$date_to') ";
$result = $this->db->query($sql);
} else {
$sql="SELECT * FROM FUEL_USAGE";
$result = $this->db->query($sql);
}
I'm making an online store and I need to filter results by brand from the database. How can I create a loop to go through all the brands because they are not only three.
Here is the code:
$sortby = $_GET['sortby'];
if(!$sortby) { $sortby = 'name'; }
if($sortby == 'Brand1')
{
$sort_query = "WHERE category = 'Brand1";
}
else if($sortby == 'Brand2')
{
$sort_query = "WHERE category = 'Brand2'";
}
else if($sortby == 'Brand3')
{
$sort_query = "WHERE category = 'Brand3'";
}
else if($sortby == 'name')
{
$sort_query = "";
}
else { unset($sortby); }
if($sortby)
{
$select[$sortby] = 'selected';
}
$sql = mysql_query("SELECT * FROM products $sort_query");
Something like this:
$sortby = $_GET['sortby'];
if(!$sortby) {
$sort_query = "";
} else {
$sort_query = "WHERE category = '".mysql_real_escape_string($sortby)."'";
}
$sql = mysql_query("SELECT * FROM products $sort_query");
Remember: never trust the user! Always escape user input!
Also, using mysql-prefixed functions is outdated. You should check how to use mysqli.
Try this:
$sortby = mysql_real_escape_string($_GET['sortby']) or $sortby = "name";
if($sortby != "name") {
$sort_query = "WHERE category = '$sortby'";
$select[$sortby] = 'selected';
} else {
$sort_query = "";
}
$sql = mysql_query("SELECT * FROM products $sort_query");
I'll write the code like this:
$sortby = $_GET['sortby'];
$valid_brands = array('brand1','brand2');
if(in_array($sortby, $valid_brands)){
$sql = "SELECT * FROM products where category = ?";
$stmt = $db_usag->prepare($sql);
$stmt->bind_param($sortby);
}
else{
$sql = "SELECT * FROM products";
$stmt = $db_usag->prepare($sql);
}
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
that is a pseudo code.. but is clean code without injection issues :)
it's simple. Why write code so hard? php is dynamic.
to sort you must use ORDER BY, you want to filter..
here example, variable names I doesn't change.
This is only query buiding statement.
$sortby = $_GET['sortby'];
$sort_query = $sortby == 'name' ? "" : "WHERE category = '{$sortby}'";
$sql = mysql_query("SELECT * FROM products {$sort_query}");
You should select all avaiable brands from your database and than loop thorugh them.
$sql = "SELECT DISTINCT `category` FROM products"
[mysql stuff]
while($cat = [assoc array]) /*use your prefered functions*/
{
if($sortby == $cat['category'])
{
$sort_query = "WHERE category = '".$cat['category']."'";
}
}
I am trying to add some "Infinite Scrolling" to my product pages. However, i can't get it working at all, so i have nothing.
The page currently works, but it just outputs all of the products. I can't get the infinite scrolling scripts i found working, as my query is not always the same.
This is the code that builds my query, using GETs:
$kategori_q = "";
if ($kategori !== "") {
if ($hkat !== "") {
$ukator = "";
$underkategorier = sqlSelect("SELECT * FROM underkategorier WHERE fk_hkategori = '$kategori'");
while ($row = sqlFetch($underkategorier)) {
$ukator .= " fk_ukategori = '".$row['underkategori_id']."' OR";
}
$kategori_q = rtrim($ukator, "OR");
$kategori_q = "WHERE ($kategori_q)";
}
else {
$kategori_q = "WHERE fk_ukategori = '$kategori'";
}
}
$query = "SELECT * FROM annoncer $kategori_q ORDER BY annonce_id DESC";
$soeg = "";
if (isset($_GET['soeg'])) {
$soeg = $_GET['soeg'];
if (substr_count($query, "WHERE") == 1) {
$soeg = " AND (overskrift LIKE '%$soeg%' OR beskrivelse LIKE '%$soeg%')";
}
else {
$soeg = " WHERE (overskrift LIKE '%$soeg%' OR beskrivelse LIKE '%$soeg%')";
}
}
$query = "SELECT * FROM annoncer $kategori_q $soeg ORDER BY annonce_id DESC";
$q = sqlSelect($query);