How to change mysql statement depending on how many variables with php - php

So basically I have website that has names of cities that can be checked off. I save them into local storage under one key. And then I send them Via Ajax over to my php script below. Then in php I explode the city variable on "," and I filter the cities depending on which ones were given. But right now I only know how to do this manually, for example city[0], city[1] etc. Is there a way I can continually put those variables into mysql statement depending on how many there are? I am sorry if I am being confusing, I'm just totally lost. Any help would be appreciated.
Here is my code:
<?php
$con = mysql_connect("localhost", "test", "test") or die('could not connect to mysql');
mysql_select_db("test", $con) or die('could not find database');
$city2 = $_POST['city2'];
$cities = explode(",", $city2);
$rep2 = $_POST['rep2'];
$status2 = $_POST['status2'];
$size2 = $_POST['size2'];
$type2 = $_POST['type2'];
$lat2 = $_POST['lat2'];
$long2 = $_POST['long2'];
$radius2 = $_POST['radius2'];
if ($city2 == '') {
$city_stat = " city RLIKE '.*' ";
} else {
$city_stat = " (city='$cities[0]' OR city='$cities[1]') ";
}
if ($radius2 == '') {
$radius_stat = '10';
} else {
$radius_stat = $_POST['radius2'];
}
if ($size2 == '') {
$size_stat = '';
} else {
$size_stat = " AND size='$size2' ";
}
if ($rep2 == '') {
$rep_stat = '';
} else {
$rep_stat = " AND rep='$rep2' ";
}
if ($status2 == '') {
$status_stat = '';
} else {
$status_stat = " AND status='$status2' ";
}
$result = mysql_query("SELECT lat,lng,id,rep,rep_num,name,city,state,zip,address,status,category,size FROM test WHERE $city_stat $rep_stat $size_stat $status_stat LIMIT 0 , 50 ");
while ($array = mysql_fetch_assoc($result)) {
$array_json[] = $array;
}
echo json_encode($array_json);
?>

From what I think you are asking is that there might be a variable number of cities and you want to set a conditional that the city can be any of them.
So instead of:
$city_stat = " (city='$cities[0]' OR city='$cities[1]') ";
You can do something like this:
$city_stat = '(city IN ('.implode(',',$cities).'))';

Related

review system with function in variable

so basically I am trying to create a little thing where it outputs stars, based on the database saved rating integer. The problem is it does not seem to put the number I from the database, in the variable. Here is the code I used:
<?php
$productID = 100;
$con = mysqli_connect("localhost", "root", "", "example");
function connect()
{
$con = mysqli_connect("localhost", "root", "", "example");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
return $con;
}
}
function getStars($con)
{
$productID = 100;
$sql = "SELECT rating
FROM reviews
-- JOIN stockitemstockgroups USING (StockItemID)
-- JOIN stockgroups USING (StockGroupID)
WHERE reviewID = '5'
";
$result = $con->query($sql);
if ($con && ($result->num_rows > 0)) {
// output data of each row
while ($row = $result->fetch_assoc()) {
echo $row["rating"];
}
} else {
echo "error";
}
}
$value = getStars($con);
echo $value;
for ($x = 1; $x <= $value; $x++) {
echo '<div class="rating"><span>★</span></div>';
}
?>
I'm having trouble finding a duplicate, though I'm sure this is one. You aren't returning anything from your function, so $value doesn't have a value.
function getStars($con)
{
$productID = 100;
$sql = "SELECT rating FROM reviews WHERE reviewID = 5";
$result = $con->query($sql);
if ($result && ($result->num_rows > 0)) {
// output data of first row
$row = $result->fetch_assoc();
return $row["rating"];
} else {
return false;
}
}
As a general rule, never echo from a function. Also, no need for a loop over what will presumably be a single result.

Filter MYSQL query with form options

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).

Combination of field search using PHP & MYSQL

I am working on an assignment using PHP & MYSQL.
one of the tasks is to search on any combination of the fields. That includes Dropdown boxes populated from the Database. and Text fields.
t2ath contains
ID
SPORT
COUNTRY
GENDER
FIRSTNAME
LASTNAME
Image
I've been working on this code for a week to be able to search on any combination with no errors.
I am wondering if there is another more efficient way to do it.
$selectedSport = $_POST['sport']; $gender =$_POST['gender']; $fName =$_POST['fname']; $lName =$_POST['lname']; $country =$_POST['country'];
$sql_fName=""; $sql_lName=""; $sql_gender=""; $sql_sport=""; $sql_country="";
$checkFiled=False;
$where="";
$and="";
//
if ( $selectedSport=="showAll")
{
!isset($selectedSport);
}
else
{
if (isset($selectedSport))
{
if ($checkFiled==True)
{
$sql_sport = " AND t2ath.sport = '$selectedSport'" ;
}
else
{
$sql_sport = " t2ath.sport = '$selectedSport' " ;
$checkFiled=True;
}
}
else {
$sql_sport = "";
}
}
//
if ( $country =="showAll")
{
!isset($country);
}
else
{
if (isset($country))
{
if ($checkFiled ==True)
{
$sql_country = " AND t2ath.country = '$country'" ;
}
else
{
$sql_country = " t2ath.country = '$country' " ;
$checkFiled=True;
}
}
else {
$sql_country = "";
}
}
//
if ( $gender=="Gender")
{
!isset($gender);
}
else
{
if (isset($gender))
{
if ($checkFiled ==True)
{
$sql_gender = " AND t2ath.gender = '$gender'" ;
}
else
{
$sql_gender = " t2ath.gender = '$gender' " ;
$checkFiled=True;
}
}
else {
$sql_gender = "";
}
}
//
if ($fName =="")
{
!isset($fName);
}
else
{
if (isset($fName))
{
if ($checkFiled==True)
{
$sql_fName = " AND t2ath.firstName = '$fName'" ;
}
else
{
$sql_fName = " t2ath.firstName = '$fName' " ;
$checkFiled=True;
}
}
else {
$sql_fName = "";
}
}
//
if ($lName =="")
{
!isset($lName);
}
else
{
if (isset($lName))
{
if ($checkFiled==True)
{
$sql_lName = " AND t2ath.lastName = '$lName' " ;
}
else
{
$sql_lName = " t2ath.lastName = '$lName' " ;
$checkFiled=True;
}
}
else
{
$sql_lName = "";
}
}
if ($checkFiled == True)
$where=" where ";
$selectString = "SELECT t2ath.lastName,t2ath.firstName,t2ath.image,t2ath.sport,t2ath.gender,t2ath.country,t2country.flag FROM t2ath LEFT JOIN t2country
ON t2ath.country = t2country.name $where $sql_sport $sql_country $sql_gender $sql_fName $sql_lName ";
$result = mysql_query($selectString);
Instead of all those conditionals about whether to add AND when concatenating to the query, use an array and implode.
$fields = array('sport' => 'sport',
'gender' => 'gender',
'fname' => 'firstName',
'lname' => 'lastName',
'country' => 'country');
$wheres = array();
foreach ($fields as $postfield => $dbfield) {
if ($_POST[$postfield] != 'showAll') {
$wheres[] = "$dbfield = '" . mysql_real_escape_string($_POST[$postfield]) . "'";
}
}
$selectString = "SELECT t2ath.lastName, t2ath.firstName, t2ath.image, t2ath.sport, t2ath.gender, t2ath.country, t2country.flag
FROM t2ath LEFT JOIN t2country
ON t2ath.country = t2country.name";
if (count($wheres) > 0) {
$selectString .= " WHERE " . implode(" AND ", $wheres);
}
$result = mysql_query($selectString);
To see how to do it similarly using PDO prepared statements, see my answer here: What code approach would let users apply three optional variables in PHP/MySQL?
I've done something similar in the past where I checked the value from different fields and then added them to a series of arrays. I created an array for select, from, where, order. You can do similar for other sets like group or limit. Then I ran 'array_unique', imploded them and put them into the SQL string.
$array_select = array('users.Id'); // SET SOME DEFAULTS SO THE QUERY WILL ALWAYS RUN
$array_from = array('users');
$array_where = array();
$array_order = array();
if (isset($first_name)) {
$array_select[] = 'First_Name';
$array_from[] = 'users';
}
if (isset($city)) {
$array_select[] = 'City';
$array_from[] = 'user_contact';
$array_where[] = 'users.Id = user_contact.City';
}
if ($array_select) {
$array_select = array_unique($array_select);
$string_select = implode(', ', $array_select);
}
if ($array_where) {
$array_where = array_unique($array_where);
$string_where = 'WHERE '.implode(' AND ', $array_where);
}
// REPEAT FOR OTHERS ...
// BUILD THE QUERY OUT
$sql = 'SELECT '.$string_select.' FROM '.$string_from.' '.$string_where.' ...
Why not evaluate your string with each column (this is a guide only, I'm not building your PHP code there:
SELECT
*
FROM
table
WHERE
(ID = $id OR $id = 'showAll')
AND (SPORT = $sport OR $sport = 'showAll')
AND (COUNTRY = $country OR $country = 'showAll')
AND (GENDER = $gender OR $gender = 'showAll')
AND (FIRSTNAME = $firstname OR $firstname = 'showAll')
Just need to make sure you NVL the variables to an appropriate value (whether it be int or string)

Php Mysql Search Issue

I'm trying create a simple search script with php and mysql. I've html select tag which is
people
country
region
destination
from
to
With this I get the content from from mysql database. so following is my php script.
if(isset($_GET['Submit']) && $_GET['Submit'] == "Search")
{
$people = mysql_real_escape_string(htmlspecialchars(trim($_GET['people'])));
$country = mysql_real_escape_string(htmlspecialchars(trim($_GET['country'])));
$region = mysql_real_escape_string(htmlspecialchars(trim($_GET['region-depart'])));
$destination = mysql_real_escape_string(htmlspecialchars(trim($_GET['destination'])));
$from = mysql_real_escape_string(htmlspecialchars(trim($_GET['from'])));
$to = mysql_real_escape_string(htmlspecialchars(trim($_GET['to'])));
if(isset($people))
{
$search = mysql_query("SELECT * FROM property_step1 WHERE pro_no_sleep LIKE
'%$people%'");
$num = mysql_num_rows($search);
while($result = mysql_fetch_array($search))
{
$propertyid = (int) $result['propertyid'];
echo $country_d = $result['pro_country'];
echo $region_d = $result['pro_state'];
echo $destination_d = $result['pro_city'];
}
}
elseif(isset($country))
{
$search2 = mysql_query("SELECT * FROM property_step1 WHERE pro_country LIKE
'%$country%'");
$num = mysql_num_rows($search2);
while($result2 = mysql_fetch_array($search2))
{
$propertyid = (int) $result2['propertyid'];
echo $country_d = $result2['pro_country'];
echo $region_d = $result2['pro_state'];
echo $destination_d = $result2['pro_city'];
}
}
else
{
echo "nope";
}
}
Well, if i select people (which value is 1, 2, 3 and so on) it's show the content from database but when i select country it's doesn't show anything. Is there anything wrong in my query?
isset($people) always evaluates to true; you need to check if it is not empty as well:
if (isset($people) && !empty($people)) {
// ...
}
Your elseif condition for country is creating problem replace it with if only, writing if...elseif only one condition will get execute.
use this code
if (isset($_GET['Submit']) && $_GET['Submit'] == "Search") {
$people = mysql_real_escape_string(htmlspecialchars(trim($_GET['people'])));
$country = mysql_real_escape_string(htmlspecialchars(trim($_GET['country'])));
$region = mysql_real_escape_string(htmlspecialchars(trim($_GET['region-depart'])));
$destination = mysql_real_escape_string(htmlspecialchars(trim($_GET['destination'])));
$from = mysql_real_escape_string(htmlspecialchars(trim($_GET['from'])));
$to = mysql_real_escape_string(htmlspecialchars(trim($_GET['to'])));
if (isset($people)) {
$search = mysql_query("SELECT * FROM property_step1 WHERE pro_no_sleep LIKE
'%$people%'");
$num = mysql_num_rows($search);
while ($result = mysql_fetch_array($search)) {
$propertyid = (int) $result['propertyid'];
echo $country_d = $result['pro_country'];
echo $region_d = $result['pro_state'];
echo $destination_d = $result['pro_city'];
}
}
if (isset($country)) {
$search2 = mysql_query("SELECT * FROM property_step1 WHERE pro_country LIKE
'%$country%'");
$num = mysql_num_rows($search2);
while ($result2 = mysql_fetch_array($search2)) {
$propertyid = (int) $result2['propertyid'];
echo $country_d = $result2['pro_country'];
echo $region_d = $result2['pro_state'];
echo $destination_d = $result2['pro_city'];
}
} else {
echo "nope";
}
}
You are defining each variable so all variables will always "be set".
if(isset($people)) will always run, as it is defined meaning that isset($country) will never run.
This needs to be changed to:
if(!empty($people)){
}
if(!empty($country)){
}

Infinite scrolling

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);

Categories