How to get all values when parameter is null - php

I have a query form where I need to fetch details from a custom table in MYSQL. If the parameter is left blank all records should be fetched. If there is a value entered in the parameter then records for that value should be fetched.
This is my code so far:
<?php
$host = 'localhost';
$dbname = 'test';
$username = 'test';
$password = 'xxx';
session_start();
global $wpdb, $current_user;
$conn = mysqli_connect($host, $username, $password, $dbname);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$param_1=mysqli_real_escape_string($conn,$_GET['param_1']);
if (!empty($param_1)){
$sql = "SELECT column1 ,column2,column3,column4,column5
FROM xxx
WHERE column1='$param_1'";
} else {
$sql = 'SELECT column1 ,column2,column3,column4,column5
FROM xxx';
}
$query = mysqli_query($conn, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
This works fine with one parameter. I will need to add more parameters and those could also be null.
For e.g.
$sql = "SELECT column1 ,column2,column3,column4,column5
FROM xxx
WHERE column1='$param_1' AND column2='$param_2";
Either of these could be null. How do I take care of this in MYSQL?
My question is what would be the best way to take care of this situation?
Thanks in advance.

You can keep appending the query like this:
$sql = "SELECT column1 ,column2,column3,column4,column5
FROM xxx
WHERE 1=1 ";
if(!empty($param1)){
$sql.= " and column1='$param1'";
}
if(!empty($param2)){
$sql.= " and column2='$param2'";
}
if(!empty($param3)){
$sql.= " and column3='$param3'";
}
Note: Passing parameters like this would lead to SQL injection, use binding to pass parameters to avoid SQL Injection. Here is a good read about it.

You can follow the below steps
<?php
$host = 'localhost';
$dbname = 'test';
$username = 'test';
$password = 'xxx';
session_start();
global $wpdb, $current_user;
$conn = mysqli_connect($host, $username, $password, $dbname);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$whereArr=[];
if(isset($_GET['param_1'])){
$whereArr[]="column1=" . mysqli_real_escape_string($conn,$_GET['param_1']);
}
if(isset($_GET['param_2'])){
$whereArr[]="column2=" . mysqli_real_escape_string($conn,$_GET['param_2']);
}
if(isset($_GET['param_3'])){
$whereArr[]="column3=" . mysqli_real_escape_string($conn,$_GET['param_3']);
}
$whereStr='';
if(count($whereArr)>0){
$whereStr="WHERE " . implode(" AND ",$whereArr);
}
$sql = "SELECT column1 ,column2,column3,column4,column5
FROM xxx " . $whereStr;
$query = mysqli_query($conn, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
Check for each param in the above demonstrated, Put them in array.
Then check if array is isset or not, if isset create a where string and the append it to your query.
Even if no param is set your query will run without where clause.

You can do something like this for optimization of your code,
$getArr = array_filter($_GET);
// checking sql injection
$getArr = array_map(function ($v) use ($conn) {
return mysqli_real_escape_string($conn, $v);
}, $getArr);
$temp = [];
// fetching numbers for that key
foreach ($getArr as $key => $value) {
$temp[$key] = preg_replace('/[^\d]/', '', $key);
}
$str = '';
// creating condition for data fetched in get
array_walk($temp, function ($item, $key) use (&$str, $getArr) {
$str .= " column$item = '" . $getArr[$key] . "' AND ";
});
// raw query
$sql = 'SELECT column1 ,column2,column3,column4,column5 FROM xxx';
// if not empty string
if (!empty($str)) {
$sql .= rtrim($str,'AND ');
}
echo $sql;die;

Related

Getting error Record updated successfully Fatal error: Uncaught Error: Call to a member function fetch_assoc() on array

<?php
getdata();
function getdata(){
$server="";
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "SELECT * from items";
$result = mysql_query($query);
if(!$result) die("Oh crap...: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j <= $rows; $j++)
{
$row = mysql_fetch_row($result);
$row[1]= $server;
$command = "nslookup ".$server;
exec($command, $result);
$nslookup_result="";
foreach($result as $line){
$nslookup_result.= $line."<br> ";
}
updatenslookup($server,$nslookup_result);
}
$mysqli->close();
}
function updatenslookup($url,$nsresult) {
// Create connection
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$updatesql = "UPDATE `items` SET `description`='".$nsresult."' WHERE `title` ='".$url."'";
if ($mysqli->query($updatesql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $mysqli->error;
}
$mysqli->close();
}
?>
This bit makes no sense to me:
function getdata(){
$server=""; //<---------- set here
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "SELECT * from items";
$result = mysql_query($query);
if(!$result) die("Oh crap...: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j <= $rows; $j++)
{
$row = mysql_fetch_row($result);
$row[1]= $server; //<---- sure you want to do this
//your basically setting $row[1] = '' on every iteration
//so your command below is "nslookup " because $server = ''
$command = "nslookup ".$server;
exec($command, $result);
$nslookup_result="";
foreach($result as $line){
$nslookup_result.= $line."<br> ";
}
updatenslookup($server,$nslookup_result);
}
$mysqli->close();
}
It seems to me this bit $row[1]= $server; is backwards.
But lets not forget the SQLInjection issues here:
function updatenslookup($url,$nsresult) {
// Create connection
$dbHost = "localhost";
$dbDatabase = "h_php";
$dbPasswrod = "";
$dbUser = "root";
$mysqli = new mysqli($dbHost, $dbUser, $dbPasswrod, $dbDatabase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$updatesql = "UPDATE `items` SET `description`='".$nsresult."' WHERE `title` ='".$url."'";
if ($mysqli->query($updatesql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $mysqli->error;
}
$mysqli->close();
}
Specifically this stuff:
function updatenslookup($url,$nsresult) {
// ....
$updatesql = "UPDATE `items` SET `description`='".$nsresult."' WHERE `title` ='".$url."'";
// ....
}
The big issue with it is I can inject whatever I want into this table, then you take that data and shoot it right into
exec("nslookup ".$row[1], $result); //simplified $server = $row[1] + exec("nslookup ".$server)
So in theory I can (or may be able to) inject my own command line calls into exec, at least to some extent. I'm not sure all what someone could do with these issues, what the worst case would be, but I would avoid it in any case.
There is no way for me to know where the data for updatenslookup($url,$nsresult) comes from or if its clean, but it doesn't matter. One reason to prepare the sql is to have the security right where the issue is so you can clearly tell by looking at just the query if its safe or not. And you don't have to worry about missing some piece of data that could sneak in there.
You should use escapeshellarg at the very least, and clean up the SQL vulnerabilities by preparing your queries.
As far as this Call to a member function fetch_assoc() on array, I don't even see a call to fetch_assoc() in your code. Maybe I missed it but all I see is this $row = mysql_fetch_row($result); for reading data, which is procedural where you use the OOP in the other code . which is irritating .. but I get it, which is why I only use PDO now...
Etc..
I always feel bad when I shred up someones hard work, but I would be remiss not to mention such a big security hole.
Cheers.

Why displaying array when select column in mysql?

I am trying to select a column in mysql in php,
function PageController() {
$data = [
'categories' => _db_get_select("categories", ['name'])
];
load_view("tutu", $data);
and
function _db_get_select($table_name, $columns) {
$servername = _c("database.server_name");
$username = _c("database.username");
$password = _c("database.password");
$dbname = _c("database.db_name");
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully";
$sql = "SELECT name=$columns FROM . $table_name.";
var_dump($sql);
the result is displaying like this
string(42) "SELECT ['name']=Array FROM . categories."
I want to be like this
SELECT name FROM . categories.
Thanks in advance.
You may use this script
function PageController() {
$data = [
'categories' => _db_get_select("categories", "name")
];
load_view("tutu", $data);
And the function will be
function _db_get_select($table_name, $columns) {
$servername = _c("database.server_name");
$username = _c("database.username");
$password = _c("database.password");
$dbname = _c("database.db_name");
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT {$columns} FROM {$table_name}";
}
Just echo your sql variable instead of var dump like below
echo $sql;
Use foreach loop to iterate through an array of columns to form a query.
function PageController() {
$data = array('categories' => _db_get_select("categories", array("name")));
load_view("tutu", $data);
}
And then:
//Start with select
$sql = 'SELECT ';
//Concat column names separated with commas
foreach ($columns as $value) {
$sql .= $value . ', ';
}
//Get rid of the last comma
$sql = rtrim($sql, ', ');
$sql .= ' FROM ' . $table_name;
Check if it's okey:
var_dump($sql);

How to put the output query from mySQL to php int variable

I want to do a query to get the last id (int) in a table to create a new row with that last id + 1 but actually this just put all rows with the same id
my code:
<?php
$servername = "localhost";
$user = "root";
$pass = "dbpass";
$dbname = "site";
$mail = $_POST['mail'];
$password = $_POST['password'];
// Create connection
$conn = mysqli_connect($servername, $user, $pass, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sqlID = "SELECT MAX(id) FROM `login`;";
if ($result = mysqli_query($conn, $sqlID)) {
$id = mysqli_fetch_row($result);
}
settype($id, "int");
$id = $id + 1;
$sql = "INSERT INTO login (`id`,`mail`,`password`)
VALUES ('".$id."','".$mail."','".$password."');";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
mysqli_fetch_row returns always an array, also if there is only 1 element. So the MAX(id) in in $row[0].
Fixing this, you also don't need to use settype.
If your id is autoincrement, change this:
$sql = "INSERT INTO login (`id`,`mail`,`password`)
VALUES ('".$id."','".$mail."','".$password."');";
to:
$sql = "INSERT INTO login (`mail`,`password`)
VALUES ('".$mail."','".$password."');";
Then get rid of all code from $sqlID to $id + 1; (for tidyness)

Getting data from MySQL table via Codeigniter

I'm having issues getting this data from within a codeigniter Controller.
$q = $this->db->get('offers_orders');
$this->db->select('total');
$this->db->where('order_number', $orderid);
$orderdata = $q->result_array();
$orderamount = $orderdata[0]['total'];
Do you see anything wrong with this code ?.
Yes, Try :
$this->db->select('count(*) as total', false);
$this->db->where('order_number', $orderid);
$q = $this->db->get('offers_orders');
OR,
$q = $this->db->select('count(*) as total', false)->where('order_number', $orderid)->get('offers_orders');
You need first to defined your select and where method then you call the get() method which are used for get data.
Like this:
$this->db->select('total');
$this->db->where('order_number', $orderid);
$q = $this->db->get('offers_orders');
And as I see from your query, you need to fetch only one result and for it better solution is to use row() function because this function returns a single result row.
Like this:
$orderdata = $q->row();
$orderamount = $orderdata->total;
Also to learn more about it you can read this acticle.
<!DOCTYPE html>
<html>
<body>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["id"]. " - Name: ". $row["firstname"]. " " . $row["lastname"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>

Fetching a result from selection query in php function

I have a php function of selection from mySql database:
function Master_file($name, $latin ){
$HOST_DB ="localhost";
$NAME_DB="nom";
$USER_DB ="utilisaeur";
$PWD_DB="K3Pud1";
$connect = mysql_connect($HOST_DB,$USER_DB,$PWD_DB);
$db=mysql_select_db($NAME_DB);
$qry = "SELECT tax_id FROM master where name =".$name." and latin =".$latin;
echo $qry;
$result = mysql_query($qry);
while ($Res_user = mysql_fetch_assoc($result) ) {
return $Res_user['tax_id'];
}
}
an error is shown Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/admin/public_html/hitlist/include/fg_membersite.php on line 446 and the line is while ($Res_user = mysql_fetch_assoc($result)
So what is the problem ? How can i fix it?
Try this
function Master_file($name, $latin ){
$dsn = 'mysql:host=localhost;dbname=nom';
$username = 'utilisaeur';
$password = 'K3Pud1';
try {
$db = new PDO($dsn, $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
exit;
}
$result = $db->prepare("SELECT tax_id FROM master where name =:name");
$result->bindValue(':name', $name);
$result->execute();
foreach($result->fetchAll(PDO::FETCH_ASSOC) as $row){
echo $Res_user['tax_id'] . '<br />';
}
}
EDIT
The function above has just been updated to use PDO, display any errors, and output the tax_id value to the browser
You may try this, since your returning here return $Res_user['tax_id']; so I think you need a single row instead
function Master_file($name, $latin ){
$HOST_DB ="localhost";
$NAME_DB="nom";
$USER_DB ="utilisaeur";
$PWD_DB="K3Pud1";
$connect = mysql_connect($HOST_DB,$USER_DB,$PWD_DB);
if (!$connect) {
die("Could not connect: " . mysql_error());
}
$db=mysql_select_db($NAME_DB, $connect);
if (!$db) {
die ("Can't use " . $NAME_DB . " : " . mysql_error());
}
$qry = "SELECT tax_id FROM master where name ='" . $name . "' and latin = '" . $latin . "'";
$result = mysql_query($qry);
if( $result ){
$row = mysql_fetch_assoc($result);
return $row['tax_id'];
}
}

Categories