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']."'";
}
}
Related
To explain my issue, here is a simple code at first:
public function sql($data) {
if (is_array($data)) {
$cells = $data['cells'];
$from = $data['from'];
$where = $data['where'];
$joins = $data['joins'];
$order_by = $data['order_by'];
$o_type = $data['order_by_type'];
$limit = $data['limit'];
/*****************************/
if ($cells == '') { $cells = "*"; }
if ($where != '') { $where = "where ".$where; }
if ($oredr_by != '') { $order_by = "order by ".$order_by." ".$o_type; }
if ($limit != '') { $limit = "limit ".$limit; }
//
$sql = "select ".$cells." from ".$from." ".$joins." ".$where." ".$order_by." ".$limit;
$run = mysqli_query($_SESSION['con'], $sql);
}else{
$run = mysqli_query($_SESSION['con'], $data);
}
}
When I start using this method, I pass a multidimensional array as a parameter, like this:
$sql = $class->sql([ "from" => "table", "order_by" => "id", "order_by_type" => "asc" ]);
/* This will generate and run this query: select * from table order by id asc */
// Notice that I've only used 3 keys, not the all above.
In Apache server, it works OK perfectly when I just use some of the keys of array, but in XAMPP it doesn't because it says that I have to pass all the parameters (cells, from, where, joins, ...) even if they are empty.
Please help me to resolve this, and thanks.
You can use isset to check if an array key is present, then get it's value like.
public function sql($data) {
if (is_array($data)) {
$cells = '';
if(isset($data['cells']) {
$cells = $data['cells'];
}
....
/*****************************/
if ($cells == '') { $cells = "*"; }
if ($where != '') { $where = "where ".$where; }
if ($oredrby != '') { $orderby = "order by ".$orderby." ".$od_type; }
if ($limit != '') { $limit = "limit ".$limit; }
$sql = "select ".$cells." from ".$table." ".$joins." ".$where." ".$orderby." ".$limit;
$run = mysqli_query($_SESSION['con'], $sql);
}else{
$run = mysqli_query($_SESSION['con'], $data);
}
}
Or simply just do error_reporting(1) before calling this function or in your index.php.
The problem is this.
$arr = ["a"];
echo $arr["b"];
You will get an error notice.
Notice: Undefined index: b
If you want to avoid this use it in this way.
$arr = ["a"];
$arr = ["b"] = "";
echo $arr["b"];
Change $from to $table, you have not $table variable
$from = $data['from'];
to
$table = $data['from'];
Also you have spelling mistake biggest spelling mistake which is very difficult to find.orderby and oredrby
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'm having a hard time getting this search results with pagination code to work. It does successfully grab the search keyword entered in the html form on another page and brings it into this search.php page. if I echo $search I see the keyword on the page. But I get no results even though I should for the query. Can anyone see what might be going on?
require "PDO_Pagination.php";
if(isset($_REQUEST["search_text"]) && $_REQUEST["search_text"] != "")
{
$search = htmlspecialchars($_REQUEST["search_text"]);
$pagination->param = "&search=$search";
echo $search;
$pagination->rowCount("SELECT * FROM stories WHERE stories.genre = $search");
$pagination->config(3, 5);
$sql = "SELECT * FROM stories WHERE stories.genre = $search ORDER BY SID ASC LIMIT $pagination->start_row, $pagination->max_rows";
$query = $connection->prepare($sql);
$query->execute();
$model = array();
while($rows = $query->fetch())
{
$model[] = $rows;
}
}
else
{
$pagination->rowCount("SELECT * FROM stories");
$pagination->config(3, 5);
$sql = "SELECT * FROM stories ORDER BY SID ASC LIMIT $pagination->start_row, $pagination->max_rows";
$query = $connection->prepare($sql);
$query->execute();
$model = array();
while($rows = $query->fetch())
{
$model[] = $rows;
}
}
$query = "SELECT * FROM stories";
if(isset($_REQUEST["search_text"]) && $_REQUEST["search_text"] != "")
{
$search = htmlspecialchars($_REQUEST["search_text"]);
$pagination->param = "&search=$search";
$query .= " WHERE genre LIKE '%$search%'";
}
// No need for else statement.
$pagination->rowCount($query);
$pagination->config(3, 5);
$query .= " ORDER BY SID ASC LIMIT {$pagination->start_row}, {$pagination->max_rows}";
$stmt = $connection->prepare($query);
$stmt->execute();
$model = $stmt->fetchAll();
var_dump($model);
In your query do:
WHERE stories.genre LIKE '%string%');
instead of:
WHERE stories.genre = 'string');
Because the equals will want to literally equal the field.
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);
My query is working OK. But I am trying to find out the best way to optimize and not have to repeat my $sqlRecCount and $records_count (and would like to know if it's possible to not need to duplicate the GETs). This is what I have now:
if ((int)$_GET['products_id'] === 13) {
$sqlRecCount = "select count(*) as recTotal from table_sql_1";
$recCnt = $db->Execute($sqlRecCount);
$records_count = $recCnt->fields['recTotal'];
}
elseif ((int)$_GET['products_id'] === 2) {
$sqlRecCount = "select count(*) as recTotal from table_sql_2";
$recCnt = $db->Execute($sqlRecCount);
$records_count = $recCnt->fields['recTotal'];
} else {
$records_count = "Updating...";
}
$id = intval($_GET['products_id']);
if ($id == 13 || $id == 2) {
$sqlRecCount = "select count(*) as recTotal from table_sql_" .
($id==13?'1':'2');
$recCnt = $db->Execute($sqlRecCount);
$records_count = $recCnt->fields['recTotal'];
} else {
$records_count = "Updating...";
}
ps: if you have a set of tables without direct correspondence to the product_id you can rewrite snippet as
$id = intval($_GET['products_id']); // casting to int is not required here
$tables = array('13'=>'1', '2'=>'2', and so on);
if (isset($tables[$id])) {
$sqlRecCount = "select count(*) as recTotal from table_sql_" . $tables[$id];
$recCnt = $db->Execute($sqlRecCount);
$records_count = $recCnt->fields['recTotal'];
} else {
$records_count = "Updating...";
}
ps: #downvoter - any comment?
The right way apparently would be
if ($id = (int)$_GET['products_id']) {
$sql = "SELECT count(*) as total FROM table_sql WHERE products_id=$id";
$res = $db->Execute($sql);
$records_count = $res->fields['total'];
}
or something similar according to your db API syntax