Select all records when no value is supplied - php

I have a function in php that does retrieval and display work from a MySql database.
It's like this:
function thisFunction($id,$country,$year){
global $conn;
$conn = connect();
$stmt = $conn->prepare("select * from table where id = :id and countryCode = :country and YEAR(addedDate) = :year and status = 0");
$stmt->execute(array(
':id' => $id,
':country' => $location,
':year' => $year
));
}
The problem is, sometimes $id has a value, sometimes it doesn't. When it does have a value, I'd like to select records with that value, when it doesn't I'd like to select all.
How do I write the sql in there, or do this thing, so that when there is a value it'll select only records with that value, and when there isn't a value, it'll select all. It's the part where when no value is selected - then select all where I'm stuck.
I call the function like anyone would. Nothing unique there.
select * from table where id = 9 -- works fine - displays all records where id = 9
select * from table where id = no value supplies - should display all value. How do I do this?
Can you please help?
select * from table where id = * //Does not work

Just remove the id part if it's empty:
function thisFunction($id,$country,$year){
global $conn;
$conn = connect();
if (!isset($id) || empty($id))
{
$stmt = $conn->prepare("select * from table where countryCode = :country and YEAR(addedDate) = :year and status = 0");
$stmt->execute(array(
':country' => $location,
':year' => $year
));
}
else
{
$stmt = $conn->prepare("select * from table where id = :id and countryCode = :country and YEAR(addedDate) = :year and status = 0");
$stmt->execute(array(
':id' => $id,
':country' => $location,
':year' => $year
));
}
}

select * from table where id = id;
Sample fiddle

You could use something like this:
function thisFunction($id,$country,$year){
global $conn;
$sql_query = "select * from table where status = 0";
$where_data = array();
if(isset($id) && $id != '*'){ // Only add this if ID is set to something other than *
$where_data[':id'] = $id;
$sql_query .= " AND id = :id";
}
if(isset($location)){
$where_data[':country'] = $location;
$sql_query .= " AND countryCode = :country";
}
if(isset($year)){
$where_data[':year'] = $year;
$sql_query .= " AND YEAR(addedDate) = :year";
}
$conn = connect();
$stmt = $conn->prepare($sql_query);
$stmt->execute($where_data);
}

you could potentially select them if the column is not null.
select * from table where id is not null

Related

How to get mysql records from a statement that has a LIKE clause for the TABLE_NAMES

I want to select records from two tables. These two tables have the prefix "shop_".
How do I select the records for both shops in a sql statement?
My current statement:
// Select
$stmt = $mysqli->prepare("SELECT name, html_id, price FROM database_name WHERE TABLE_NAME LIKE 'shop%'");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$arr[] = $row;
}
$name = [];
foreach($arr as $arrs)
{
$name[] = array(0 => $arrs['name'], 1 => $arrs['html_id'], 2 => $arrs['price']); //here
}
$stmt->close();
print_r($name);
The mysql php current error is:
Fatal error: Uncaught Error: Call to a member function execute() on boolean in C:\wamp642\www\webcart\search.php on line 17 and line 17 is: $stmt->execute();
I can get the tables to "show" with this command:
$stmt = $mysqli->prepare("show tables like '%shop%'");
But it doesn't get the records, just an object I think.
The output of "show tables like '%shop%'" prints 2 arrays just like it should, but the arrays are empty with no data/records.
I'm thinking it's the sql statement that needs work. Thanks.
EDIT:
I've also tried:
$stmt = $mysqli->prepare("SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='feeds' AND TABLE_NAME LIKE 'shop%'");
EDIT: The contents of search.php
<?php
include 'define.php';
$mysqli = new mysqli($host, $db_user, $db_password, $db_database);
if($mysqli->connect_error)
{
?><script>var profiles_delete_modal_1 = ' Error 3: Problem deleteing profile. Make sure database login credentials are correct.';</script>
<script>$(".modal").css({"opacity":"1", "z-index":"100"});$(".modal_mid").html("<pre>" + profiles_delete_modal_1 + "</pre>");setTimeout(function(){$(".modal").css({"opacity":"0", "z-index":"-100"});},5000);</script><?php
exit;
}
$shop = 'shop';
// Select
//$stmt = $mysqli->prepare("show tables like '%shop%'");
//$stmt = $mysqli->prepare("SELECT * FROM feeds WHERE TABLE_NAME LIKE 'shop%'");
$stmt = $mysqli->prepare("SELECT name, html_id, price FROM database_name WHERE TABLE_NAME LIKE 'shop%'");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$arr[] = $row;
}
$n=0;
$name = [];
foreach($arr as $arrs)
{
$name[] = array(0 => $arrs['name'], 1 => $arrs['html_id'], 2 => $arrs['price']); //here
$n++;
}
$stmt->close();
print_r($name);
and the contents of define.php:
$www_dir = 'webcart';
$url_root = 'http://localhost/' . $www_dir . '';
$www_dir_slash = $_SERVER['DOCUMENT_ROOT'] . '' . $www_dir . '/';
$host = 'localhost';
$db_user = 'webcart_admin';
$db_password = 'asd123';
$db_database = 'shop';
$_SESSION['host'] = $host;
$_SESSION['db_user'] = $db_user;
$_SESSION['db_password'] = $db_password;
$_SESSION['db_database'] = $db_database;
EDIT
From going on the answer stated below I've been able to create a string like this:
SELECT name, html_id, price FROM shop_a UNION shop_b
however it won't execute properly.
This is my code:
$stmt = $mysqli->prepare("SELECT name, html_id, price FROM shop_a UNION shop_b");
$result = $stmt->execute();
It gives the following error:
Fatal error: Uncaught Error: Call to a member function execute() on boolean in C:\wamp642\www\webcart\search.php on line 43
EDIT Got it.
I'll post the answer up soon. The statement goes like this:
"SELECT name, html_id, price FROM shop_a UNION SELECT name, html_id, price from shop_b"
I got the answer pretty much from musafar, although I needed to get to the objects in the array. So I used some foreach loops to do this seeing as I don't know any other way. If there's another way to get to mysqli_object data, please let me know.
$stmt = $mysqli->prepare("SELECT TABLE_NAME FROM information_schema.tables WHERE table_schema = 'shop' AND table_name LIKE 'shop%'");
//table_schema is the database name and 'shop%' is the search string
$stmt->execute();
$tables = $stmt->get_result();
$stmt->close();
$arr = [];
foreach($tables as $tabless)
{
$arr[] = $tabless;
}
foreach($arr as $arrs)
{
$toby[] = implode(',',$arrs);
}
$tobyy = implode(' UNION SELECT name, html_id, price from ',$toby);
//$tobyy = "shop_a UNION SELECT name, html_id, price from shop_b"
$arr = [];
$stmt = $mysqli->prepare("SELECT name, html_id, price FROM " . $tobyy);
$result = $stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$arr[] = $row;
}
$n=0;
$name = [];
foreach($arr as $arrs)
{
$name[$n] = array(0 => $arrs['name'], 1 => $arrs['html_id'], 2 => $arrs['price']); //here
$n++;
}
$stmt->close();
print_r($name);
//$name = "Array ( [0] => Array ( [0] => Chromecast [1] => chromecast [2] => 59 ) [1] => Array ( [0] => EZCast [1] => ezcast [2] => 49 ) )"
SELECT query is used to fetch data from DB tables, not DB itself. So you need to provide a table name in the FROM part of your query.
Considering you're trying to fetch data from similar tables (same fields)...
$stmt = $mysqli->prepare("SELECT table_name FROM information_schema.tables WHERE table_schema = 'wp_105424' AND table_name LIKE 'shop%'");
$stmt->execute();
$tables = $stmt->get_result();
$dataStmt = $mysqli->prepare("SELECT name, html_id, price FROM " . implode(',', $tables)); // name, html_id, price should be in all tables that starts with *shop*
$dataStmt->execute();
$data = $dataStmt->get_result();
And you may need to add conditions to handle all scenarios.

Use PDO exec(array()) with several operands

I would like to secure my requests in my code.
Today my curent functions are like this.
public function UpdatePMS($table,$data,$where) {
$ret = array();
$set_data = "";
foreach($data as $key => $value){
$set_data .= $key."= '".$value."', ";
}
if (isset($where)) {
$where = "WHERE ".$where;
}
$sql = "UPDATE ".$table." SET ".$set_data."".$where;
$sql = str_replace(", WHERE", " WHERE", $sql);
$stm = $this->db->prepare($sql);
$ret = $stm->execute();
return $ret;
}
With this way, i can select any tables, any datas, and any conditions.
For example:
WHERE id = 1 and status < 10
Or only
WHERE id = 10
Or sometimes
WHERE id = 1 and status >= 5
The content of where could change.
A kind of universal request.
Same for Delete, Update, Select, insert.
I tried to do like this, but it doesn't work.
$db = new PDO('mysql:host=localhost;dbname=asterisk','root','');
$table = "my_table";
$where = "WHERE id = 1";
$sql = 'SELECT * FROM :table :where';
$stm = $db->prepare($sql);
$stm->execute(array(":table" => $table, ":where" => $where));
$ret = $stm->fetchall(PDO::FETCH_ASSOC);
Any ideas?
Frankly, you cannot use prepared statements this way. There are rules to follow. So it just makes no sense to write something like this
$table = "my_table";
$where = "WHERE id = 1";
$sql = 'SELECT * FROM :table :where';
$stm = $db->prepare($sql);
$stm->execute(array(":table" => $table, ":where" => $where));
instead you should write this code
$sql = 'SELECT * FROM my_table WHERE id = ?';
$stm = $db->prepare($sql);
$stm->execute(array($id));
Besides, you cannot parameterize table and field names, so it's better to write them as is.
so i need to make one function per different requests, right?
Honestly - yes. It will spare you from A LOT of headaches.
public function UpdatePMS($data, $id)
{
$data[] = $id;
$sql = "UPDATE table SET f1 = ?, f2 = ? WHERE id = ?";
$stm = $this->db->prepare($sql);
$ret = $stm->execute($data);
return $ret;
}
which is going to be used like
$obj->UpdatePMS([$f1, $f2], $id);

MySql query not working with variables weird bug

I have a list of users ids and my goal is to get the name of each user using the id
the sql variable prints: SELECT name FROM users WHERE unique_id = '56d4814fb37cf3.17691034 '
If i copy paste the query the name is returned and works as well with other ids, but i don't want the function to allways return the same name, i want to add the variable $userID to my query and return the name
But this only works when i hardcode de id
public function returnNameByID($userID){
//User ID: 56d4814fb37cf3.17691034
$sql = "SELECT name FROM users WHERE unique_id = '$userID'";
echo $sql; // Prints SELECT name FROM users WHERE unique_id = '56d4814fb37cf3.17691034 '
//Doesn't work $name returns Null
// $stmt = $this->conn->prepare("SELECT name FROM users WHERE unique_id = '$userID'");
//Doesn't work $name returns Null
$stmt = $this->conn->prepare($sql);
// Works $name returns name of the user
$stmt = $this->conn->prepare(" SELECT name FROM users WHERE unique_id = '56d4814fb37cf3.17691034 ' ");
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();
$name = $result["name"];
return $name;
EDIT
require_once 'db_functons.php';
$db = new db_functions();
$userID = $_GET['userID'];
$mArray = array();
$mArray = $db->getFriendsList($userID);
//Printing the array Prints the correct id's
$name = $db->returnNameByID($mArray[0]);
echo $name;
Seems you have some space around your code try using a trim
$sql = "SELECT name FROM users WHERE trim(unique_id) = '" . trim($userID) . "';";

how to use PDO rowCount() function in foreach?

i need some help , i have simple code like count rows in php, i use PDO ,
so i check if rowCount > 0 i do job if no other job but i have it in foreach function, in first step i get true result but in other i get invalid
so i think it is function like a closeCursor() in PDO but i try and no matter . maybe i do it wrong ?
it is part of my code
public function saveClinicCalendar($post){
$daysItm = '';
$Uid = $post['Uid'];
$ClinicId = $post['ClinicId'];
$type = $post['type'];
$resChck = '';
foreach($post['objArray'] as $arr){
foreach($arr['days'] as $days){
$daysItm = $days.",".$daysItm;
}
$daysItm = substr($daysItm, 0, -1);
$dateTime = $arr['dateTime'];
$sqlChck = 'SELECT * FROM clinic_weeks WHERE dates = :dates AND Uid = :Uid AND category = :category AND Cid = :Cid AND type = :type';
$resChck = $this->db->prepare($sqlChck);
$resChck->bindValue(":dates",$dateTime);
$resChck->bindValue(":Cid",$ClinicId);
$resChck->bindValue(":type",$type);
$resChck->bindValue(":Uid",$Uid);
$resChck->bindValue(":category",$Uid);
$resChck->execute();
$co = $resChck->rowCount();
if($co > 0){
/*UPDATE*/
$sql = 'UPDATE clinic_weeks SET dates = :dates ,time = :time, Cid = :Cid, type = :type, Uid = :Uid, category = :category ';
$res = $this->db->prepare($sql);
$res->bindValue(":dates",$dateTime);
$res->bindValue(":time",$daysItm);
$res->bindValue(":Cid",$ClinicId);
$res->bindValue(":type",$type);
$res->bindValue(":Uid",$Uid);
$res->bindValue(":category",$Uid);
}else{
/*INSERT*/
$sql = 'INSERT INTO clinic_weeks (dates,time, Cid,type,Uid,category) VALUES (:dates,:time, :Cid,:type,:Uid,:category)';
$res = $this->db->prepare($sql);
$res->bindValue(":dates",$dateTime);
$res->bindValue(":time",$daysItm);
$res->bindValue(":Cid",$ClinicId);
$res->bindValue(":type",$type);
$res->bindValue(":Uid",$Uid);
$res->bindValue(":category",$Uid);
}
$res->execute();
$resChck->closeCursor();
$resChck = null;
$daysItm = '';
}
}
what i am doing wrong?
many thanks to Barmar, he suggest me a true answer.
here is a code
$sql = "INSERT INTO clinic_weeks
(`timestam`,`time`,dates,Cid,type,Uid,category)
VALUES
('$timestamp','$daysItm','$dateTime','$ClinicId','$type','$Uid','$Uid')
ON DUPLICATE KEY UPDATE `time` = '$daysItm' ";
I use there "ON DUPLICATE KEY UPDATE" and it`s work perfectly!
instead a big code top of page i make a two line of code.

SQL / PHP How to pull data from a table and place it in variable

Assuming I have a uniqid key in my table and that same key is sent to my site in a get method, how do I pull that specific key out and assign all the data from the table to variables. This is what I have so far but cant seem to figure it out.
$query1 = "SELECT *
FROM todo_item2 as ti INNER JOIN todo_category2 as tc ON ti.todo_id = tc.todo_id'
WHERE todo_id = :todo_id";
$statement1 = $db->prepare($query1);
$statement1 -> execute(array(
'todo_id' =>$id
));
while ($row = $statement1->fetch())
{
$text = $row['todo'];
$cat = $row['category'];
$percent = $row['precent'];
$date = $row['due_date'];
}
You should ready about what execute actually does .. the parameters to execute (and I assume you're using PDO or something similar here) are the tokens of the query. What you want is something like:
$query = " ... WHERE todo_id = ?"
$stmt = $db->prepare($query);
$stmt->execute(array($id));
while ($row = $stmt->fetch()) {
//$row is now an associative array of row values.
}
// Start the Load
$query1 = "SELECT *
FROM todo_item2 as ti INNER JOIN todo_category2 as tc ON ti.todo_id = tc.todo_id
WHERE ti.todo_id = :todo_id";
$statement1 = $db->prepare($query1);
$statement1 -> execute(array(
'todo_id' =>$id
));
// Make Sure the Data Exists
if( $statement1->rowCount() == 0 )
{
die('Please Enter a Valid ID Tag - (id)');
}
while($row = $statement1->fetch())
{
$text = $row['todo'];
$cat = $row['category'];
$percent = $row['percent'];
$date = $row['due_date'];
}

Categories