Infinite scrolling - php

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

Related

Multiple Loops running together

$a_forms = array("a_GG", "a_FF");
$sql = "SELECT name, field FROM categories WHERE enabled = '1' ";
$result = mysqli_query($con,$sql);
$Others = array();
while($row = mysqli_fetch_array($result)) {
$Other_names[] = $row['name'];
$Other_fields[] = $row['db_field'];
}
for ($i=0;$i<count($a_forms);$i++) {
if ($a_forms[$i] == "a_FF") {
$dforms_sql = "SELECT *
FROM a_FF
where id=".$id;
$dforms_result = mysqli_query($con,$dforms_sql);
while ($forms_row = mysqli_fetch_array($dforms_result)) {
for ($i=0; $i<count($Other_fields); $i++) {
echo "<tr><td colspan='3'>".$Other_names[$i]."</td></tr>";
}
}
} elseif ($a_forms[$i] == "a_GG") {
$dforms_sql = "SELECT *
FROM a_GG where id=".$id;
$dforms_result = mysqli_query($con,$dforms_sql);
while($forms_row = mysqli_fetch_array($dforms_result)) {
echo 'Other cool stuff';
}
}
} //END (first) For Loop
So, for some reason, if that second for loop, $Other_field is there it will only show the IF statement for a_FF. But if the array = a_FF and a_GG and the for loop for $other_field is NOT there it displays them both. So it's obviously that for loop that is breaking something, I have no idea what though. Anyone have any thoughts?

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

Filter by brand loop

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']."'";
}
}

MySQL count w/ php trying to optimize for efficiency and non redundancy

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

SQL won't work? It doesn't come up with errors either

I have PHP function which checks to see if variables are set and then adds them onto my SQL query. However I am don't seem to be getting any results back?
$where_array = array();
if (array_key_exists("location", $_GET)) {
$location = addslashes($_GET['location']);
$where_array[] = "`mainID` = '".$location."'";
}
if (array_key_exists("gender", $_GET)) {
$gender = addslashes($_GET["gender"]);
$where_array[] = "`gender` = '".$gender."'";
}
if (array_key_exists("hair", $_GET)) {
$hair = addslashes($_GET["hair"]);
$where_array[] = "`hair` = '".$hair."'";
}
if (array_key_exists("area", $_GET)) {
$area = addslashes($_GET["area"]);
$where_array[] = "`locationID` = '".$area."'";
}
$where_expr = '';
if ($where_array) {
$where_expr = "WHERE " . implode(" AND ", $where_array);
}
$sql = "SELECT `postID` FROM `posts` ". $where_expr;
$dbi = new db();
$result = $dbi->query($sql);
$r = mysql_fetch_row($result);
I'm trying to call the data after in a list like so:
$dbi = new db();
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
$sql .= " ORDER BY `time` DESC LIMIT $offset, $rowsperpage";
$result = $dbi->query($sql);
// while there are rows to be fetched...
while ($row = mysql_fetch_object($result)){
// echo data
echo $row['text'];
} // end while
Anyone got any ideas why I am not retrieving any data?
while ($row = mysql_fetch_object($result)){
// echo data
echo $row->text;
} // end while
I forgot it wasn't coming from an array!

Categories