No result being displayed when running this query - php

I have to create a dynamic query based on the value received by the user's input, the value of the variables are posted by GET
When I simply run this
$qry = "SELECT* FROM LAPTOP WHERE 1=1";
$resul = mysqli_query($qry);
retrieve($resul);
all the content of this table are displayed without any error,(retrieve function here displays all the results based on the query) but when I try to modify it like this, I get a blank page
$qry = "SELECT * FROM LAPTOP WHERE 1=1";
if(!empty($company))
{
$qry .= " AND company='$company'" ;
}
if(!empty($cpu))
{
$qry.= " AND cpu='$cpu' " ;
}
if(!empty($lifestyle))
{
$qry.= " AND lifestyle='$lifestyle' " ;
}
if(!empty($display))
{
$qry.= " AND display='$display'" ;
}
if(!empty($ram))
{
$qry.= " AND ram='$ram' " ;
}
if(!empty($HDD))
{
$qry.= " AND HDD='$HDD' " ;
}
echo $qry;
$result= mysqli_query($qry) || die(mysqli_error()) ;
retrieve($result) ;
$p = basename($_SERVER['REQUEST_URI']) ;
The result of echo $qry; is as expected, it displays this
SELECT * FROM LAPTOP WHERE 1=1 AND company='Asus' AND cpu='intel i3'
Is there a way to correct this? The reason I tried using WHERE 1=1 clause is that when all the variables are equal to NULL then the query returns all the rows from the table.

i guess you have no data in your database matched with your conditions . OR you have case sensitive with names.
example :
cpu='Intel i3' // with big I
cpu='intel I3' // with big I
cpu='intel i3' // double space.
OR if you have big string , think to use LIKE
$qry.= " AND cpu LIKE '%$cpu%' " ;

Is this a typo also ($resul_T_)?
$resul = mysqli_query($qry);
retrieve($resul);
How you managed to lose that 't' and later get it back? ;)

As others have pointed out it may simply be that your query does not match any records.
Anyway what I usually do in a similar case is put all the conditions in an array, and then implode the array with 'AND'. That way you don't have to bother with 1=1 and it doesn't matter whether you have 0, 1 or more conditions.
<?php
$qry = "SELECT * FROM LAPTOP";
$conditions = array();
$cpu = 'Intel';
$ram = '24GB';
if(!empty($cpu))
{
$conditions[] = "cpu='$cpu'";
}
if(!empty($lifestyle))
{
$conditions[] = "lifestyle='$lifestyle'";
}
if(!empty($display))
{
$conditions[] = "display='$display'";
}
if(!empty($ram))
{
$conditions[] = "ram='$ram'";
}
if(!empty($HDD))
{
$conditions[] = "HDD='$HDD'";
}
if( count( $conditions ) > 0 )
{
$qry .= " WHERE ";
$qry .= implode( " AND ", $conditions );
}
print_r($qry);
?>

Related

running a query inside a loop to do another loop

Ok so what i am doing is getting member id's from 1 table and looping those ID's through another table to get values to output. I had it working going through the first loop, then notice the output was all screwy, so released I needed to loop it through again, since there will could be multiple entries in the 2nd query for MemID. now I put in the 2nd loop but its not even going through, not sure where I messed up the code, but doesn't seem to output now when running it through the 2nd loop. though it did output without the loop. but that won't work due to multiple rows for each $memid.
$qry_skamembers = "SELECT * FROM ap_skamembers ORDER BY id";
$qry_skamembers = $mysqli->real_escape_string($qry_skamembers);
if($result_skamembers = $mysqli->query($qry_skamembers)){
while($row_skamembers = $result_skamembers->fetch_array()){
$AffID = $row_skamembers['AffID'];
$MemID = $row_skamembers['MemberID'];
$skacon = new mysqli(OW_DB_HOST, OW_DB_USER, OW_DB_PASSWORD, OW_DB_NAME);
if ($skacon->connect_error) {
die('Connect Error');
}
$get_data = "SELECT * FROM ow_base_billing_sale WHERE userID = $MemID AND status = 'delivered' ORDER BY id";
$get_data = $skacon->real_escape_string($get_data);
if($result_data = $skacon->query($get_data)){
while($finish = $result_data->fetch_array()){
$test = $finish['status'];
if($test == 'delivered') {
$sale_amount = $finish['price'];
$product = $finish['transactionUId'];
$products = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM ap_earnings where product = $product"));
if(mysqli_num_rows($products) > 0) { }
else {
echo "AFF: " . $AffID . " | ";
echo "Mem: " . $MemID . " | ";
echo "PRICE: " . $sale_amount . " | ";
echo "PRODUCT: " . $product . " -- ";
include('controller/record-sale.php');
echo "inserting record";
echo "run finished <br><br>";
}
}
}
}
}
}
I am still rather new at coding, so it might look a bit sloppy, my apologies for that.
I do not know if that is ist bu try to replace:
$get_data = $skacon-->real_escape_string($get_data);
with
$get_data = $skacon->real_escape_string($get_data);
i think there is an extra -
And as we found out in comments you need to change $product to '$product'
You can do all that in one query,nevermind it will be much faster
SELECT aps.AffID,aps.MemberID,owb.price,owb.transactionUId
FROM db1.ap_skamembers aps JOIN db2.ow_base_billing_sale owb
ON aps.MemberID = owb.userID AND owb.status='delivered'
JOIN db3.ap_earnings ape
ON ape.product = owb.transactionUId
ORDER BY aps.id

mysql php select a record that's similar to another

I know this may seem like a duplicated, out of stackoverflow, etc question but here we go.
I'm trying to make an SQL sentence that can find a coincidence between two strings
function getProductos($keyWords){
$keyWords = addslashes(strtolower($keyWords));
$keyWordsExploded = explode(" ",$keyWords);
$sql = "SELECT * FROM PRODUCTOS WHERE HOMBRE_MUJER LIKE :keyWords OR CATEGORIA LIKE :keyWords" OR NOMBRE LIKE :keyWords;
$query = self::$conn->prepare($sql);
$query->execute(array(":keyWords"=> "%" . $keyWords . "%"));
return $query;
}
In other part of the page I have this code:
<?php
if(isset($_GET['buscar'])){
require(PAGES_DIR . "queries_products.php");
$consultaProducts = new QueryProductos();
$productos = $consultaProducts->getProductos($_GET['buscar']);
if($productos->rowCount()!=0){
$arrayProductos = $productos->fetchAll(PDO::FETCH_ASSOC);
echo "<h3>Productos encontrados</h3>";
foreach($arrayProductos as $fila){
echo $fila['NOMBRE'] . " " . $fila['HOMBRE_MUJER'] . "<br>";
}
}else{
echo "<p class='alert alert-warning'>No results found <strong>" . $_GET['buscar'] . "</strong>";
}
}
?>
Everything works fine, In my database I store only 2 values in CATEGORIA which are: "hombres" and "mujeres", if i search for hombres I get all records which have a CATEGORIA of hombres but when i search for hombres y mujeres I get no results, I have tried using different sentences that i read but I haven't had any luck, I hope you can greatly save me by helping me solve this problem.
try this:
function getProductos($keyWords) {
$keyWordsExploded = explode(" ",$keyWords);
$sql = "SELECT * FROM PRODUCTOS WHERE ";
$likes = array("HOMBRE_MUJER", "CATEGORIA", "NOMBRE"); // build up our columns which will be used in our condition in sql statment
$params = array();
// building up our sql statment and collecting our params
foreach($likes as $like) {
foreach($keyWordsExploded as $kw) {
$sql .="$like like ? or ";
$params[] = "%".$kw."%";
}
}
$sql = rtrim($sql, "or "); // trim the last "or" condition in sql statment
$query = self::$conn->prepare($sql);
$query->execute($params);
return $query;
}

Generated MySQL 'AND' select behaving like 'OR' select

I'm trying to build a MySQL search to match keywords occurring in any order in the column being searched (not just whole phrases as would normally be the case). My class function is:
public function keywords_author($keywords, $author) {
$keywords = explode(" ", trim($keywords));
$keywords = array_filter($keywords);
$count_keywords = count($keywords);
if ($count_keywords != 0) {
$query = "SELECT * FROM `table` WHERE ";
$query_echo = $query;
$a = 0;
while ($a < $count_keywords) {
$query .= "`column` LIKE :keyword ";
$query_echo .= "`column` LIKE '%" . $keywords[$a] . "%' ";
$a++;
if ($a < $count_keywords) {
$query .= " && ";
$query_echo .= " && ";
}
}
$stmt = $this->db->prepare($query);
for ($a=0; $a<$count_keywords; $a++) {
$keyword = "%" . $keywords[$a] . "%";
$stmt->bindParam(':keyword', $keyword);
}
$stmt->execute();
$output = '';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// build $output
}
echo $output;
echo $query_echo;
}
}
I have just added $query_echo to check the query being built, which is:
SELECT * FROM `table`
WHERE `column` LIKE '%php%'
&& title LIKE '%mysql%'
&& title LIKE '%jquery%'
&& title LIKE '%ajax%'
This works fine when I copy that into the SQL command line in phpMyAdmin, returning only those records where ALL keywords are matched, but when I run the class file in my site it behaves like an OR select and returns results where ANY of the keywords occurs in the column.
I'm confused! Any ideas what's going on would be a huge help!
David -
Thanks, David Kmenta - that's certainly a step in the right direction and now I'm getting the correct query:
SELECT * FROM table WHERE column LIKE :keyword0 AND column LIKE :keyword1 AND column LIKE :keyword2 AND column LIKE :keyword3 AND column LIKE :keyword4
But it is still returning the result for the last value only. I am sure it is a basic, probably obvious error in the loop enclosing the new bindParam statement:
for ($a=0; $a<$count_keywords; $a++) {
$keyword = "%" . $keywords[$a] . "%";
$stmt->bindParam(':keyword'.$a, $keyword);
}
I'm very tired - can you spot the problem?
But
Problem is probably here:
for ($a=0; $a<$count_keywords; $a++) {
$keyword = "%" . $keywords[$a] . "%";
$stmt->bindParam(':keyword', $keyword);
}
Every occurrence of :keyword is replaced with last item in $keywords array.

Search by criteria not returning any records

I am trying to check if the POST or the GET has my search variables and then add the variables to my query. I then want to pass the array name of those variables into the URL for paginating my search results. With someone's help, this is how far I have gone.
$criteria = array('ctitle', 'csubject', 'creference', 'cat_id', 'cmaterial', 'ctechnic', 'cartist', 'csource', 'stolen');
$likes = "";
$url_criteria = '';
foreach ( $criteria AS $criterion ) {
if ( ! empty($_POST[$criterion]) ) {
$value = ($_POST[$criterion]);
$likes .= " AND `$criterion` = '%$value%'";
$url_criteria .= '&'.$criterion.'='.htmlentities($_POST[$criterion]);
} elseif ( ! empty($_GET[$criterion]) ) {
$value = mysql_real_escape_string($_GET[$criterion]);
$likes .= " AND `$criterion` = '%$value%'";
$url_criteria .= '&'.$criterion.'='.htmlentities($_GET[$criterion]);
}
}
$sql = "SELECT * FROM collections WHERE c_id>0" . $likes . " ORDER BY c_id ASC";
echo $sql;
The problem I have here is that after modifying the query I had before, any criteria I use to search does not return any records even when those records exist. I also echoed thequery and it printed the following line:
SELECT * FROM collections WHERE c_id>0 AND `cmaterial` = '%wood%' ORDER BY c_id ASC
Please, what am I missing here?
You should use LIKE keyword instead of = when concatenating parts of criteria. Your condition means searching for exact match including % symbols, while LIKE means searching by pattern.
$likes .= " AND `$criterion` LIKE '%$value%'";

Building an SQL query using multiple (optional) search fields

I have a form that is going to be used to search through a table of support tickets.
the user can search from a few difficult optional fields.
Date (to/from)
Ticket Status
Engineer
Ticket Contact
I'm wondering what is the best way to deal with optional search filters. So I have a query that takes in parameters from the user. So if the user searches using both the from and to dates then the query would want to include BETWEEN. So do I have to write a different query for if the user searches for only from. or another query when the user has not added any date parameters? Then what if the status dropdown is blank? Is that another query?
Any help to clear this up would be great!
Jonesy
Build your query in parts. Start with whatever is constant in your query, and add on more SQL depending on what extra conditions:
$query = "SELECT ...
FROM ...
WHERE [where conditions that are always going to be present]";
if (isset($_POST['date_from']) && isset($_POST['date_to']))
{
$query .= ... // query code for dealing with dates
}
if (isset($_POST['status']))
{
$query .= ... // deal with status
}
// etc.
// Once you have your query fully built, execute it
$result_set = mysql_query($query);
This code is obviously just a skeleton, but that's how I would construct my query.
Hard to say without knowing what sort of DB abstraction you're using, but assuming you're hand-writing the SQL, it's fairly simple, just build up sections of your where clause individually for each variable. (Assuming here that your vars are already escaped/quoted.)
$where_clause = array();
if (!empty($date_from)) {
$where_clause[] = "table.date >= $date_from";
}
if (!empty($date_to)) {
$where_clause[] = "table.date <= $date_to";
}
if (!empty($status)) {
$where_clause[] = "status = $status";
}
$query = 'select * from table where ' . join(' and ', $where_clause);
This is an elegant way that I use alot and wish will help you too:
$q = 'SELECT * FROM Users';
$buildQ = array();
if (empty($idOrName) === false) {
$buildQ[] = '(userid = "' . $idOrName . '" OR username LIKE "%' . $idOrName. '%")';
}
if (empty($nickname) === false) {
$buildQ[] = 'nickname="' . $nickname . '"';
}
if (empty($salary) === false) {
$buildQ[] = 'salary="' . $salary . '"';
}
// ... any other criterias like above if statements
if (count($buildQ) === 1) {
$q .= ' WHERE ' . $buildQ[0];
} else if (count($buildQ) > 1) {
$count = 0;
foreach ($buildQ as $query) {
if ($count === 0) {
$q .= ' WHERE ' . $query;
} else {
$q .= ' AND ' . $query;
}
$count++;
}
}
I think it would be better if You generate query dynamically at runtime based on which fields are filled. So You could make some helper which appends specific query fragments if only one date is passed and the other one is null, or when both are passed and so on.

Categories