Is it possible to use a MySQL query in a PHP variable? - php

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.

Related

Issue in using arrays as parameters of method of PHP custom class

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

SELECT Query, WHERE selects all when "" is empty

The Aim
Hi, I'm trying to shorten my code by building the query dynamically based on the $_GET. Current I have every possible If statement with the relevant SELECT query. However I would like to create a dynamic system for feature updates.
Current Progress
//Set Filter based on url
if ($_GET[GAME] != "") { $gameFilter = $_GET[GAME]; } else { $gameFilter = ''; }
if ($_GET[Region] != "") { $regionFilter = $_GET[Region]; } else { $regionFilter = ''; }
if ($_GET[Console] != "") { $consoleFilter = $_GET[Console]; } else { $consoleFilter = ''; }
$result = get_matchfinder($gameFilter, $regionFilter, $consoleFilter);
//The Function
function get_matchfinder($gameFilter, $regionFilter, $consoleFilter) {
//Set Varibles
$database = 'matchFinder';
$order = 'DESC';
$limit = '20';
//Query Function
$connection = connection();
$sql = 'SELECT * FROM '. $database .' WHERE game = "'.$gameFilter.'" AND region = "'.$regionFilter.'" AND console = "'.$consoleFilter.'" ORDER BY ID '. $order .' LIMIT '. $limit .'';
$response = mysqli_query($connection, $sql);
//Return
return $response;
}
Problem
Currenly it works when all of the filters are active but if one of them isn't the whole query fails, I know thats because it is try to SELECT something matching ''.
So my questions is how do I make it search for all when that filters is not set?
You should build the query parts depending on the length of the filter:
$sql = '
SELECT * FROM '.$database.'
';
$filters = array();
if (strlen($gameFilter) > 0) {
$filters[] = 'game = "'.mysqli_escape_string($connection, $gameFilter).'"';
}
if (strlen($regionFilter) > 0) {
$filters[] = 'region = "'.mysqli_escape_string($connection, $regionFilter).'"';
}
if (strlen($consoleFilter ) > 0) {
$filters[] = 'console= "'.mysqli_escape_string($connection, $consoleFilter).'"';
}
if (count($filters) > 0) {
$sql .= ' WHERE '.implode(' AND ', $filters);
}
if (strlen($oder) > 0) {
$sql .= ' ORDER BY ID '.$order;
}
if ($limit > 0) {
$sql .= ' LIMIT '.$limit;
}
$response = mysqli_query($connection, $sql);
What you're doing there is building up an array of conditions, based on the length of the condition. If the condition's input is an empty string, it isn't added to the array. At the end, if there are any filters, use implode to bind the conditions into a string. The way implode works, if there's only one condition, the glue string isn't used.
It also bears mentioning that you are exposing yourself to SQL injection. The above code shows the use of mysqli_escape_string to escape the input, but you should look in to parameterized queries to take full precaution: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php -- the above sample would only be slightly different if you used paraterized queries, but significantly more safe.
Documentation
strlen - http://php.net/manual/en/function.strlen.php
implode - http://php.net/manual/en/function.implode.php
Mysql parameterized queries - http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
You would have to build your search dynamically
You could start your base query with
$sql='SELECT * FROM '. $database .' WHERE 1=1'
Then, if $gameFilter!="", append to your existing $sql string with "and game=$gameFilter"
The syntax for appending would be like this
if ($gameFilter!="")
{
$sql.=' and game=$gameFitler'
}
and so on checking for all of your search conditions.
Make you string like this
$sql = 'SELECT * FROM '. $database .' WHERE 1=1 {0} {1} {2}'
if ( $gameFilter <> '')
$sql = str_replace("{0}", "AND game = '".$gameFilter."'" , $sql);
else
$sql = str_replace("{0}", "" , $sql);
if ( $regionFilter <> '')
$sql = str_replace("{1}", "AND region = '".$regionFilter."'" , $sql);
else
$sql = str_replace("{1}", "" , $sql);
if ( $consoleFilter <> '')
$sql = str_replace("{2}", "AND console = '".$consoleFilter."'" , $sql);
else
$sql = str_replace("{2}", "" , $sql);

Check empty rows query

In fact I am working on a small PHP script but I am facing a problem right now.The problem is that i want to check if my query return records this is my mysqli query:
$sql = "select * from specs where btitleid=$id and phoneid=$aydi"
$check = $conn->query($sql)
while($row = $check->fetch_assoc()) {$tocheck = $row['content'];}
I don't want to check the number of rows of this query to see if it is null.I want to check if all $row['content'] are empty.
How about this:
$sql = "select * from specs where btitleid=$id and phoneid=$aydi";
$check = $conn->query($sql);
$contentAllEmpty = true;
while ($row = $check->fetch_assoc()) {
if (strlen($row['content']) > 0) {
$contentAllEmpty = false;
}
}
if ($contentAllEmpty) {
//do something
}
use ==
while ($row = $check->fetch_assoc()) {
if ($row['content'] == '') {
... code here
}
}
To get back only records where the content column is not empty -
$sql = "SELECT * FROM `specs` WHERE `btitleid` = $id AND `phoneid` = $aydi AND (`content` IS NOT NULL OR `content` != '') ";

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

Categories