Constructing an SQL query around optional search parameters - php

I'm attempting to construct an MySQL query around some optional search parameters in PHP. There are 3 search fields linking to the three columns in my database. The user should be able to search each column individually, or up to all 3 if they want to narrow down their results.
My PHP code is built so that the if one of the search fields is empty, it doesn't matter and it will continue the search in the other two fields. However, I'm struggling to get my head around how to construct my SQL query afterwards as my where clauses have already been specified in the $whereclauses array. I am returning the same columns in any search the user makes so that should make the SQL query quite simple and mean it only needs to be defined once.
My PHP code:
<?php
require '../db/connect.php';
$whereclauses = array();
$subsets = false;
// for every field
if(!empty($_POST['name']))
{
$subsets = true;
$whereclauses[] = " ARTIST = ". mysql_real_escape_string(trim($_POST['name']));
}
if($subsets)
{
$whereclauses = implode(", ". $whereclauses);
}
else
{
$whereclauses ="";
}
SQL query in PHP
if(!empty($whereclauses)) {
$sql = "SELECT
`ARTIST`, `TRACKTITLE`, `DATE`, `LOCATION`
FROM
`table 3`";
};
$result = mysql_query($sql);
$data = array();
while ($array = mysql_fetch_assoc($result)) {
$data[] = $array;
}
header('Content-type: application/json');
echo json_encode($data);
How can I add the $whereclauses array into my $sql query?

<?php
require '../db/connect.php';
$whereclauses = array("where 1=1");
$subsets = false;
// for every field
if(!empty($_POST['name']))
{
$subsets = true;
$whereclauses[] = " ARTIST = '". mysql_real_escape_string(trim($_POST['name']))."'";
}
Just implode the array in sql
$sql = "SELECT
`ARTIST`, `TRACKTITLE`, `DATE`, `LOCATION`
FROM
`table 3` ".implode(" AND ",$whereclauses);

if(!empty($whereclauses)) {
$sql = "SELECT
`ARTIST`, `TRACKTITLE`, `DATE`, `LOCATION`
FROM
`table 3`";
$sql.= " WHERE 1=1 ";
foreach($whereclauses as $where){
$sql.= " AND ".$where;
}
}
$result = mysql_query($sql);
$data = array();
while ($array = mysql_fetch_assoc($result)) {
$data[] = $array;
}
header('Content-type: application/json');
echo json_encode($data);

Related

PHP get last insert id in first query and execute it on second query with multi row

I need help. I have a problem using multi query I want to put the last insert id in the next query the problem is it only adds one. Cart_id and qty has a multiple row. Please i need help thanks in advance.
Here is my code:
public function insertOrder($cart_id = null,$qty = null)
{
if (isset($cart_id)) {
$query = "INSERT INTO `tblsales`(`user_id`, `status`) VALUES ('23','delivery');";
$last_id = $this->db->con->insert_id;
$query .= "INSERT INTO `tblorders`(`sales_id`,`product_id`, `quantity`) VALUES ($last_id, {$cart_id},{$qty});";
$result = $this->db->con->multi_query($query);
if ($result) {
header("Location :" . $_SERVER['PHP_SELF']);
}
return $result;
}
}
Parameters inserting multiple values in each row
if (isset($_POST['cartid']) && $_POST['qty']){
foreach ($_POST["cartid"] AS $key => $item){
$result = $product->insertOrder($_POST['cartid'][$key], $_POST['qty'][$key]);
echo json_encode($result);
}
}
Tried you injecting a sql SELECT query between two insert methods?
public function insertOrder($cart_id = null,$qty = null){
if (isset($cart_id)) {
$query = "INSERT INTO `tblsales`(`user_id`, `status`) VALUES ('23','delivery');";
$last_id = getLastId("tablename");
$query .= "INSERT INTO `tblorders`(`sales_id`,`product_id`, `quantity`) VALUES ($last_id, {$cart_id},{$qty});";
$result = $this->db->con->multi_query($query);
if ($result) {
header("Location :" . $_SERVER['PHP_SELF']);
}
return $result;
}
}
Get last id function:
function getLastId($tablename){
$sql = "SELECT id FROM $tablename ORDER BY id DESC LIMIT 1";
//any necessary method, and $id = get sql result
return $id;
}

sqlsrv insert when columns vary

I have searched around the web but no luck.
Am new to SQLSRV and i was migrating from PHP MySQL to PHP SQL and am having trouble inserting data from a form as some fields are optional which makes the column number vary. I need help on how i can insert when the column number varies.
thank you
here is how my insert code looks like
// sql fields and values for main table
$in_fields = array();
$in_values = array();
// prepare insertion
foreach ($_POST as $key => $value) {
if (!empty($value)) {
$value = sql_escape($value);
$in_fields[] = "[{$key}]";
$in_values[] = "'{$value}'";
}
}
// prepare sql stmt
if (!empty($in_fields)) {
$sql = "INSERT into [table_name](";
$sql .= implode(", ", $in_fields);
$sql .= ") VALUES ()";
if (executeSql($sql, $in_values)) {
$success = "Successfully Added New Record";
}
}
The executeSql function looks like this
function executeSql($sql, $params) {
global $conndb;
$rs = sqlsrv_query($conndb, $sql, $params)or die("Db query error.<br />".print_r(sqlsrv_errors(), true));
return !$rs ? false : true;
}
You need to add placeholder values (?) in the VALUES part of your query, you will need a placeholder for every value you pass through - i.e. for every value in $in_values.
To do this you could have another array, that will just have a number of ? as values, and then, like you have done for the fields, implode the array into the VALUES. Like so:
$in_fields = array();
$in_values = array();
$placeholders = array(); // new array
foreach ($_POST as $key => $value) {
if (!empty($value)) {
$value = sql_escape($value);
$in_fields[] = "[{$key}]";
$in_values[] = "'{$value}'";
// add a placeholder to the array
$placeholders[] = "?";
}
}
if (!empty($in_fields)) {
$sql = "INSERT into [table_name](";
$sql .= implode(", ", $in_fields);
$sql .= ") VALUES (" . implode(",", $placeholders) . ")";
if (executeSql($sql, $in_values)) {
$success = "Successfully Added New Record";
}
}

select from the whole database after applying where condtion on one of the table

I have a database consisting of 10 table listed in the $tables,
One of the table called tbl_module contain a column called delete_time, the following statment selects all data from these tables :
$statement = "SELECT * FROM tbl_".$table;
what i need to do is to add a condition to select all data from these table WHERE the value of delete_time in tbl_module IS NULL
the php code is:
<?php
// alle relevanten Tabellen abfragen und als json zurückgeben.
$json["status"] = "running";
$details[] = "started get_tables ";
// Include confi.php
include_once('confi.php');
//var_dump($_POST);
$request_body = file_get_contents('php://input');
// first store the given set of data to keep it for future analysis
$statement = "INSERT INTO tbl_archive (content) VALUES ('$request_body' );";
mysql_query($statement);
$input = json_decode($request_body, true);
// now check if valid user
$user = $input["user"];
$username = $user["username"];
$password = $user["password"];
if($password and $username){
$mySQLstring = "SELECT username, password, id FROM tbl_user where username = '$username' ;";
$json["statement"][] = $mySQLstring;
$qur = mysql_query($mySQLstring);
//var_dump ( $qur );
if ($qur){
$res = mysql_fetch_assoc($qur);
}
if ($res){
$json["res"] = $res;
if ($res["password"] == $password){
$json["username"] = $username;
$json["id"] = $res["id"];
$json["status"] = "ok";
$tables = array("class", "class_user", "module", "module_class", "module_user", "rating", "student", "student_class");
//$tables = array("class");
foreach($tables as $table){
$statement = "SELECT * FROM tbl_".$table;
$qur = mysql_query($statement);
if ($qur){
while($r = mysql_fetch_array($qur, MYSQL_ASSOC)){
//var_dump($r);
//echo (json_encode($r));
$result[$table][] = $r;
}
}
}
$json = array("status" => "ok", "data" => $result);
}
}
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
?>
That is fairly simple all you need to do is alter the $statement if the $table = module like this
$tables = array("class", "class_user", "module", "module_class",
"module_user", "rating", "student", "student_class");
foreach($tables as $table){
$statement = "SELECT * FROM tbl_".$table;
if ( $table == 'module' ) {
$statement .= ' WHERE delete_time IS NOT NULL ';
// and to add not equal to 0000-00-00 00:00:00
$statement .= " AND delete_time != '0000-00-00 00:00:00' ";
}
$qur = mysql_query($statement);
if ($qur){
while($r = mysql_fetch_array($qur, MYSQL_ASSOC)){
//var_dump($r);
//echo (json_encode($r));
$result[$table][] = $r;
}
}
}
NOTE1:
Please dont use the mysql_ database extensions, it is deprecated (gone for ever in PHP7)
Especially if you are just learning PHP, spend your energies learning the PDO or mysqli_ database extensions,
and here is some help to decide which to use
NOTE2:
You have some other major problems in this code, mainly that you are using data straight from the $_POST array without doing any validation or sanity checks on it, and putting it directly into a query. This you should fix, but using PDO and named or ? positional parameters would go a long way to mitigating this problem.

Insert sql query result to a new query

So the task is:
Do a query like Select * from table.
Take some cell value
Insert this value to a new query.
What do I have so far:
$Conn = odbc_connect("...");
$Result = odbc_exec("Select ...");
while($r = odbc_fetch_array($Result))
// showing result in a table
Here it looks like I should use the r array and insert data like
$var = r['some_field'];
$query = 'Select * from table where some_field = {$var}";
But how can I fill this array with values and how to make it available out of while loop?
Here I'm using odbc, but it doesn't matter, I need the algorithm. Thanks.
The whole code looks like:
<?php
$data = array();
$state = 'false';
if($_REQUEST['user_action']=='')
{
$Conn = odbc_connect("...");
$data = array();
if($_REQUEST['name']!='')
{
$Result = odbc_exec($Conn, "select ...");
//Showing result table
while($r = odbc_fetch_array(Result))
{
array_push($data, $r['cardgroup']);
$state = 'true';
}
// print_r($data); WORKS;
}
}
if ($_REQUEST['user_action'] == 'action1')
{
//I need to use $data HERE. Doesn't work
// $state = 'false' here...
}
?>
Define array outside while loop
$data = array();//defining
while($r = odbc_fetch_array($Result))
use array_push() inside while loop
array_push($data, $r['some_field']);
then try to print array of complete data outside loop
print_r($data);
Updates
Place $data = array(); at the top of first IF statement. Try this code:
$data = array();//at top
if($_REQUEST['user_action']=='')
{
$Conn = odbc_connect("...");
if($_REQUEST['name']!='')
{
$Result = odbc_exec($Conn, "select ...");
//Showing result table
while($r = odbc_fetch_array(Result))
{
array_push($data, $r['cardgroup']);
}
// print_r($data); WORKS;
}
}
if ($_REQUEST['user_action'] == 'action1')
{
//print_r($data) works here also
}
try something like this to store data in array
$allrows = array();
while($r = odbc_fetch_array( $result )){
$allrows[] = $r;
}
use foreach loop to print or use as per your choice
foreach($allrows as $singlerow) {
//use it as you want, for insert/update or print all key value like this
foreach($singlerow as $key => $value) {
//echo $key . '=='. $value;
}
}
You can try this as i understand your query hope this is your answer
$arr ='';
while($row = odbc_fetch_array($Result)) {
$arr .= '\''.$row['some_field'].'\',';
}
$arr = trim($arr, ",");
$query = "SELECT * from table where some_field IN ($arr)";
Your all task can be completed in single query
INSERT INTO table2 (col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM table1

Delete command Issue in PHP

I have a similar problem with delete command too..
function deleteUsers($userID) {
foreach($userID as $key => $val)
{
$query = "DELETE FROM members WHERE member_id = '$val'";
$result = mysql_query($query);
}
//$query = "DELETE FROM members WHERE member_id = $userID";
//$result = mysql_query($query);
if($result)
{
return 'yes';
}
}
its not performing multi delete.... the $userID contains array. Its not going inside the Query.
When using multiple IDs use variable IN (1,2,3) format rather than simple equality. Also if you have more than one ID maybe the variable should be called $userIDs?
if(count($userID) > 0) {
$query = 'DELETE FROM members WHERE member_id IN ('. implode(',', $userID) .')';
}
Without foreach:
function deleteUsers($userID) {
if (count($userID)) {
$query = "DELETE FROM `members` WHERE `member_id` IN (".implode(",", array_values($userID)).");";
if (mysql_query($query)) { return true; }
}
return false;
}
This will make the function to understand array as well as single integer:
function deleteUsers($u) {
$condition = is_array($u)
? "member_id IN (" . implode(',', $u) . ")"
: "member_id = " . (int)$u;
$res = mysql_query("DELETE FROM `members` WHERE $condition");
return $res ? true : false;
}
Remember that your parameters are not properly escaped and cannot be trusted. To learn more on escaping SQL and preventing injection attacks read about Prepared Statements.
Please, for the love of the internet, don't built an SQL query yourself. Use PDO.

Categories