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

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

Related

PHP Array sometimes returns just 'array'

I wonder why I haven't found any solutions for this strange problem.
Sorry if I haven't looked right but I am very desperate and try to fix this as much as I can.
In a recursive function, I collect sql data and store them in an array.
However, when I use print_r for outputting the array values, I get strange values like this:
a."parentMale" = '45273' OR a."parentFemale" = '44871' OR
a."parentMale" = '7625' OR a."parentFemale" = '7481' OR Array OR Array
OR Array OR Array OR a."parentMale" = ...
While my function looks like this:
public function getSelfAndAncestorsShort($id) {
$animalids = array();
if ($id != "")
{
$query = "SELECT a.\"parentMale\" AS sire, a.\"parentFemale\" AS dam
FROM animals a
WHERE a.id = ".$id;
$res = pg_query($query);
while ($row = pg_fetch_object($res))
{
if ($row->sire != "")
$animalids[] = "a.\"parentMale\" = '" .$row->sire ."'";
if ($row->dam != "")
$animalids[] = "a.\"parentFemale\" = '" .$row->dam ."'";
$animalids[] = $this->getSelfAndAncestorsShort($row->sire);
$animalids[] = $this->getSelfAndAncestorsShort($row->dam);
$animalids = implode (" OR ", $animalids);
}
}
return $animalids;
}
I hope someone can help me because I have really no idea.
You function returns an array if $id is empty. Also, you do not check the return of your function before to add into your $animalids array :
public function getSelfAndAncestorsShort($id) {
$animalids = array();
if ($id != "")
{
$query = "SELECT a.\"parentMale\" AS sire, a.\"parentFemale\" AS dam
FROM animals a
WHERE a.id = ".$id;
$res = pg_query($query);
while ($row = pg_fetch_object($res))
{
if ($row->sire != "")
$animalids[] = "a.\"parentMale\" = '" .$row->sire ."'";
if ($row->dam != "")
$animalids[] = "a.\"parentFemale\" = '" .$row->dam ."'";
$val = $this->getSelfAndAncestorsShort($row->sire);
if ($val) $animalids[] = $val; // Check here
$val = $this->getSelfAndAncestorsShort($row->dam);
if ($val) $animalids[] = $val; // Check here
}
}
if (empty($animalids)) return "" ; // Check here
return implode (" OR ", $animalids); // Only implode here
}

how to Search Result Record Paging

This code is working fine for searching with POST method, how to pagination search results?
I have attach images. First image searching with this field:
Searching result in which I want paging:
<? php
include('connection.php');
if (isset($_POST['search'])) {
$fields = array('EJAMAATID', 'GNAME', 'MOBNO', 'EMAILID', 'DNNO', 'GCNTRYID', 'PINCODE', 'GCITYID', 'DNTYPE');`search field`
$conditions = array();
foreach($fields as $field) {
if (isset($_POST[$field]) && $_POST[$field] != '') {
$conditions[] = "`$field` LIKE '%".mysql_real_escape_string($_POST[$field]). "%'";`condition`
}
}
$query = "SELECT * FROM donation ";
$orderby = "ORDER BY DNDATE desc";
$datebetween = "AND DNDATE >='$start' AND DNDATE<='$end'";
if (count($conditions) > 0) {
$yakin5 = implode(' AND ', $conditions);
$query. = "WHERE ".$yakin5.$datebetween.$orderby;
}
}
$jo = (isset($query)) ? $query : '';
$don4 = mysql_query($jo);
while ($roww = mysql_fetch_array($don4)) {
}
?>

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

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.

PHP OOP number of results

Can someone tell me how to return the number of results if I use this function to grab data from the database? I have tried including this:
$this->number = $result->num_rows;
But that didn't do the trick. Also, if anyone can give me some advice to do the below code in a better way, that would be helpful too.
<?php
public function grabResults($table, $values = '*', $where = NULL, $field1 = NULL, $and = NULL, $field2 = NULL, $order = NULL)
{
$result = 'SELECT '.$values.' FROM '.$table;
if($where != NULL)
{
$result = 'SELECT '.$values.' FROM '.$table.' WHERE '.$field1.' = '.$where;
}
if($and != NULL)
{
$result = 'SELECT '.$values.' FROM '.$table.' WHERE '.$field1.' = '.$where.' AND '.$field2.' = '.$and;
}
if($order != NULL)
{
$result = 'SELECT '.$values.' FROM '.$table.' WHERE '.$field1.' = '.$where.' ORDER BY '.$order.' ASC';
}
$query = $this->data->mysqli->query($result);
if($query)
{
while($row = $query->fetch_assoc())
{
$rows[] = $row;
}
return $rows;
}
else {
return false;
}
}
?>
$result->num_rows;
sounds like a Codeigniter function that you tried to use in raw php.
Have you tried to count() the query?
$count=count($query);

Dynamically create a SQL statment from passed values in PHP

I am passing a number of values to a function and then want to create a SQL query to search for these values in a database.
The input for this is drop down boxes which means that the input could be ALL or * which I want to create as a wildcard.
The problem is that you cannot do:
$result = mysql_query("SELECT * FROM table WHERE something1='$something1' AND something2='*'") or die(mysql_error());
I have made a start but cannot figure out the logic loop to make it work. This is what I have so far:
public function search($something1, $something2, $something3, $something4, $something5) {
//create query
$query = "SELECT * FROM users";
if ($something1== null and $something2== null and $something3== null and $something4== null and $something5== null) {
//search all users
break
} else {
//append where
$query = $query . " WHERE ";
if ($something1!= null) {
$query = $query . "something1='$something1'"
}
if ($something2!= null) {
$query = $query . "something2='$something2'"
}
if ($something3!= null) {
$query = $query . "something3='$something3'"
}
if ($something4!= null) {
$query = $query . "something4='$something4'"
}
if ($something5!= null) {
$query = $query . "something5='$something5'"
}
$uuid = uniqid('', true);
$result = mysql_query($query) or die(mysql_error());
}
The problem with this is that it only works in sequence. If someone enters for example something3 first then it wont add the AND in the correct place.
Any help greatly appreciated.
I would do something like this
criteria = null
if ($something1!= null) {
if($criteria != null)
{
$criteria = $criteria . " AND something1='$something1'"
}
else
{
$criteria = $criteria . " something1='$something1'"
}
}
... other criteria
$query = $query . $criteria
try with array.
function search($somethings){
$query = "SELECT * FROM users";
$filters = '';
if(is_array($somethings)){
$i = 0;
foreach($somethings as $key => $value){
$filters .= ($i > 0) ? " AND $key = '$value' " : " $key = '$value'";
$i++;
}
}
$uuid = uniqid('', true);
$query .= $filters;
$result = mysql_query($query) or die(mysql_error());
}
// demo
$som = array(
"something1" => "value1",
"something2" => "value2"
);
search( $som );
Here's an example of dynamically building a WHERE clause. I'm also showing using PDO and query parameters. You should stop using the deprecated mysql API and start using PDO.
public function search($something1, $something2, $something3, $something4, $something5)
{
$terms = array();
$values = array();
if (isset($something1)) {
$terms[] = "something1 = ?";
$values[] = $something1;
}
if (isset($something2)) {
$terms[] = "something2 = ?";
$values[] = $something2;
}
if (isset($something3)) {
$terms[] = "something3 = ?";
$values[] = $something3;
}
if (isset($something4)) {
$terms[] = "something4 = ?";
$values[] = $something4;
}
if (isset($something5)) {
$terms[] = "something5 = ?";
$values[] = $something5;
}
$query = "SELECT * FROM users ";
if ($terms) {
$query .= " WHERE " . join(" AND ", $terms);
}
if (defined('DEBUG') && DEBUG==1) {
print $query . "\n";
print_r($values);
exit();
}
$stmt = $pdo->prepare($query);
if ($stmt === false) { die(print_r($pdo->errorInfo(), true)); }
$status = $stmt->execute($values);
if ($status === false) { die(print_r($stmt->errorInfo(), true)); }
}
I've tested the above and it works. If I pass any non-null value for any of the five function arguments, it creates a WHERE clause for only the terms that are non-null.
Test with:
define('DEBUG', 1);
search('one', 'two', null, null, 'five');
Output of this test is:
SELECT * FROM users WHERE something1 = ? AND something2 = ? AND something5 = ?
Array
(
[0] => one
[1] => two
[2] => five
)
If you need this to be more dynamic, pass an array to the function instead of individual arguments.

Categories