PHP MySQL counter/loop query - php

I'm doing a MySQL query to search for items in a database. I've pulled variables out of the search form but I'm having some problems with my WHERE clause. As I don't want to search on fields that haven't been input in the form. The code I have at the minute is:
$query = " SELECT RequestID, clients.ClientName, clients.Username, RequestAssignee, requests.StatusID, requests.PriorityID, StatusName, PriorityName
FROM requests
INNER JOIN clients ON requests.ClientID = clients.ClientID
INNER JOIN statuses ON requests.StatusID = statuses.StatusID
INNER JOIN priorities ON requests.PriorityID = priorities.PriorityID
WHERE ";
if(!empty($RequestID))
{
$query2 .= "RequestID = '" . $RequestID . "' OR ";
}
if(!empty($ClientName))
{
$query2 .= "clients.ClientName = '" . $ClientName ."' OR ";
}
if(!empty($Username))
{
$query2 .= "clients.Username = '" . $Username . "' OR ";
}
if(!empty($RequestAssignee))
{
$query2 .= "RequestAssignee = '" . $RequestAssignee . "' OR ";
}
if(!empty($Status))
{
$query2 .= "statuses.StatusName = '" . $Status ."' OR ";
}
if(!empty($Priority))
{
$query2 .= "priorities.PriorityName = '" . $Priority ."'";
}
However you can see an issue whereby if someone only searches one field, the query adds an 'OR' to the end, resulting in an error:
SELECT RequestID, clients.ClientName, clients.Username, RequestAssignee, requests.StatusID, requests.PriorityID, StatusName, PriorityName FROM requests INNER JOIN clients ON requests.ClientID = clients.ClientID INNER JOIN statuses ON requests.StatusID = statuses.StatusID INNER JOIN priorities ON requests.PriorityID = priorities.PriorityID WHERE RequestID = '3' OR
Im guessing I'm going to have to put some sort of loop or counter in but unsure how to approach it. Any ideas?
Thanks, Matt.

$parts = array();
if(!empty($RequestID))
{
$parts[] = "RequestID = '" . $RequestID . "' ";
}
if(!empty($ClientName))
{
$parts[] = "clients.ClientName = '" . $ClientName ."' ";
}
if(!empty($Username))
{
$parts[] = "clients.Username = '" . $Username . "' ";
}
if(!empty($RequestAssignee))
{
$parts[] = "RequestAssignee = '" . $RequestAssignee . "' ";
}
if(!empty($Status))
{
$parts[] = "statuses.StatusName = '" . $Status ."' ";
}
if(!empty($Priority))
{
$parts[] = "priorities.PriorityName = '" . $Priority ."' ";
}
$query2 .= implode(' OR ', $parts);

Ok so the way i would approach this is to build the variables that will form your where clause separatley:
This could be done in an array:
FIELD1=>'Value1';
FIELD2=>'Value2';
I would then loop over this array, for the first element, i=1 i would build in a WHERE, for i+n -> i+(n-1) i would pre-pend an OR, for the last array value i wouldn't do anything.
I can then use the string i build in this loop - to stick into my query string.
Have a go at something like this and give us a shout if you need more help. Doing it this way is slightly more maintainable also.

Related

Convert "INSERT" MySQL query to Postgresql query

I`m stuck for some time to fix this trouble. I followed this article https://www.sitepoint.com/creating-a-scrud-system-using-jquery-json-and-datatables/
to create SCRUD System. But I stuck when I need to add a new record to PostgreSQL.
The working MySQL part of the code is:
$db_server = 'localhost';
$db_username = 'root';
$db_password = '123456';
$db_name = 'test';
$db_connection = mysqli_connect($db_server, $db_username, $db_password, $db_name);
$query = "INSERT INTO it_companies SET ";
if (isset($_GET['rank'])) { $query .= "rank = '" . mysqli_real_escape_string($db_connection, $_GET['rank']) . "', "; }
if (isset($_GET['company_name'])) { $query .= "company_name = '" . mysqli_real_escape_string($db_connection, $_GET['company_name']) . "', "; }
if (isset($_GET['industries'])) { $query .= "industries = '" . mysqli_real_escape_string($db_connection, $_GET['industries']) . "', "; }
if (isset($_GET['revenue'])) { $query .= "revenue = '" . mysqli_real_escape_string($db_connection, $_GET['revenue']) . "', "; }
if (isset($_GET['fiscal_year'])) { $query .= "fiscal_year = '" . mysqli_real_escape_string($db_connection, $_GET['fiscal_year']) . "', "; }
if (isset($_GET['employees'])) { $query .= "employees = '" . mysqli_real_escape_string($db_connection, $_GET['employees']) . "', "; }
if (isset($_GET['market_cap'])) { $query .= "market_cap = '" . mysqli_real_escape_string($db_connection, $_GET['market_cap']) . "', "; }
if (isset($_GET['headquarters'])) { $query .= "headquarters = '" . mysqli_real_escape_string($db_connection, $_GET['headquarters']) . "'"; }
$query = mysqli_query($db_connection, $query);
I managed to write this and it fails to work for PostgreSQL:
$conn_string = "dbname=test user=postgres password=123456";
$query = "INSERT INTO it_companies VALUES ";
if (isset($_GET['rank'])) { $query .= "('" . pg_escape_string($db_connection, $_GET['rank']) . "', "; }
if (isset($_GET['company_name'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['company_name']) . "', "; }
if (isset($_GET['industries'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['industries']) . "', "; }
if (isset($_GET['revenue'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['revenue']) . "', "; }
if (isset($_GET['fiscal_year'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['fiscal_year']) . "', "; }
if (isset($_GET['employees'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['employees']) . "', "; }
if (isset($_GET['market_cap'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['market_cap']) . "', "; }
if (isset($_GET['headquarters'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['headquarters']) . "');"; }
$query = pg_query($db_connection, $query);
The message I gets from the system is: "Add request failed: parsererror"
The Edit and remove functions are working well.
I follow to build this clause from the PGSQL site example:
INSERT INTO films VALUES
('UA502', 'Bananas', 105, '1971-07-13', 'Comedy', '82 minutes');
Any what I`m doing wrong? Thanks!
UPDATE
The echo of the query and the error was the id column. In Mysql code there was no problem with the ID colum. Why when i use pgsql it does?:
INSERT INTO it_companies (rank,company_name,industries,revenue,fiscal_year,employees,market_cap,headquarters)
VALUES ('1', 'asd', 'asd', '1', '2000', '2', '3', 'asdf');
Warning: pg_query(): Query failed: ERROR: duplicate key value violates unique constraint "it_companies_pkey" DETAIL: Key (company_id)=(2) already exists. in C:\WEB\Apache24\htdocs\datatableeditor\data.php on line 121
{"result":"error","message":"query error"
,"data":[]}
UPDATE2
The working code with one bug:
$query = "INSERT INTO it_companies (rank,company_name,industries,revenue,fiscal_year,employees,market_cap,headquarters) VALUES ";
if (isset($_GET['rank'])) { $query .= "('" . $_GET['rank'] . "', "; }
if (isset($_GET['company_name'])) { $query .= "'" . $_GET['company_name'] . "', "; }
if (isset($_GET['industries'])) { $query .= "'" . $_GET['industries'] . "', "; }
if (isset($_GET['revenue'])) { $query .= "'" . $_GET['revenue'] . "', "; }
if (isset($_GET['fiscal_year'])) { $query .= "'" . $_GET['fiscal_year'] . "', "; }
if (isset($_GET['employees'])) { $query .= "'" . $_GET['employees'] . "', "; }
if (isset($_GET['market_cap'])) { $query .= "'" . $_GET['market_cap'] . "', "; }
if (isset($_GET['headquarters'])) { $query .= "'" . $_GET['headquarters'] . "') RETURNING company_id;"; }
echo $query;
After this query, the message "Add request failed: parsererror" is still there. But after a manual refresh of the page, the new data is saved. Any idea why this message apears and not loading the data automatically?
UPDATE 3 - Success
I forgot to remove echo $query; from the code causing the error message.
All works now. Thanks for the help to all! :)
You need a little more work in your query string building.
You only add the open parenthesis ( if rank is present
You only add the closing parenthesis ) if headquarters is present.
Also you need specify what field column get which value, otherwise you end with headquarter name into the fiscal_year field. If columns are not specified the values are add it on the same order as define on the table.
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
And as other have comment check the $query to see what you have.

PHP / MySQL - syntax to sort array results?

Using a custom template (Journal 2) for a PHP-based E-commerce system.
In the control panel, there's a section that loads custom modules.
Problem is, the modules are presented in the order of creation, which makes it hard to find the right module.
I would like to sort them alphabetically.
How & where can I add a sort-by-name feature to this function?
public function all() {
if (isset($this->get_data['module_type'])) {
$module_type = $this->db->escape('journal2_' . $this->get_data['module_type']);
$query = $this->db->query('SELECT * FROM ' . DB_PREFIX . 'journal2_modules WHERE module_type = "' . $module_type . '"');
} else {
$query = $this->db->query('SELECT * FROM ' . DB_PREFIX . 'journal2_modules');
}
foreach ($query->rows as &$row) {
$row['module_data'] = json_decode($row['module_data'], true);
if (is_array($row['module_data'])) {
foreach($row['module_data'] as $key => &$value) {
if (!in_array($key, array('module_name', 'module_type'))) {
unset($row['module_data'][$key]);
}
}
}
}
return $query->rows;
}
Thanks in advance!
If you need an specific order, in sql you can use the order by clause. In your case could be useful order by module_name
$query = $this->db->query('SELECT * FROM ' . DB_PREFIX .
'journal2_modules WHERE module_type = "' .
$module_type . '" order by module_name ');
Try altering your query:
if (isset($this->get_data['module_type'])) {
$module_type = $this->db->escape('journal2_' . $this->get_data['module_type']);
$query = $this->db->query('SELECT * FROM ' . DB_PREFIX . 'journal2_modules WHERE module_type = "' . $module_type . '" ORDER BY module_data ASC');
} else {
$query = $this->db->query('SELECT * FROM ' . DB_PREFIX . 'journal2_modules ORDER BY module_data ASC');
}
At the end of your queries insert an ORDER BY condition like ORDER BY columnName to sort by that column.
public function all() {
if (isset($this->get_data['module_type'])) {
$module_type = $this->db->escape('journal2_' . $this->get_data['module_type']);
$query = $this->db->query('SELECT * FROM ' . DB_PREFIX . 'journal2_modules WHERE module_type = "' . $module_type . '"' . ' ORDER BY ' . $this->get_data['module_order_by']);
} else {
$query = $this->db->query('SELECT * FROM ' . DB_PREFIX . 'journal2_modules ORDER BY ' . $this->get_data['module_order_by']);
}
foreach ($query->rows as &$row) {
$row['module_data'] = json_decode($row['module_data'], true);
if (is_array($row['module_data'])) {
foreach($row['module_data'] as $key => &$value) {
if (!in_array($key, array('module_name', 'module_type'))) {
unset($row['module_data'][$key]);
}
}
}
}
return $query->rows;
}

PHP PDO how to bind values to varibale contains concatenated string

How do i bind values to a variable which is partially processed with diffrent statements and then concatenated using php .= method
Please note that I am not using array to bind parameters.
below is piece of code
$wher = '';
now I have added few varibles to $wher like
if (!empty($_SESSION['advs']['title']))
{
$wher .= '(';
if (isset($_SESSION['advs']['desc']))
{
$wher .= "(au.description like '%" . $system->cleanvars($_SESSION['advs']['title']) . "%') OR ";
}
$wher .= "(au.title like '%" . $system->cleanvars($_SESSION['advs']['title']) . "%' OR au.id = " . intval($_SESSION['advs']['title']) . ")) AND ";
}
more addition to $wher
if (isset($_SESSION['advs']['buyitnow']))
{
$wher .= "(au.buy_now > 0 AND (au.bn_only = 'y' OR au.bn_only = 'n' && (au.num_bids = 0 OR (au.reserve_price > 0 AND au.current_bid < au.reserve_price)))) AND ";
}
if (isset($_SESSION['advs']['buyitnowonly']))
{
$wher .= "(au.bn_only = 'y') AND ";
}
if (!empty($_SESSION['advs']['zipcode']))
{
$userjoin = "LEFT JOIN " . $DBPrefix . "users u ON (u.id = au.user)";
$wher .= "(u.zip LIKE '%" . $system->cleanvars($_SESSION['advs']['zipcode']) . "%') AND ";
}
now I am using $wher in database query like
// get total number of records
$query = "SELECT count(*) AS total FROM " . $DBPrefix . "auctions au
" . $userjoin . "
WHERE au.suspended = 0
AND ".$wher . $ora . "
au.starts <= " . $NOW . "
ORDER BY " . $by;
$wher is being used in SQL select query.
How do I put placeholders to $wher and bind the values??
my problem is something like PHP PDO binding variables to a string while concatenating it
But slight different way

Mutliple querystring parameters to mysql query

I originally had this working:
url: http://server/blah.php?FacilityCode=FT
$facilitycode = mysql_real_escape_string($_GET["FacilityCode"]);
$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
"AND ('" . $facilitycode . "' = '' OR Facility.FacilityCode = '". $facilitycode . "')";
$result = mysql_query($sql);
But I want to change this so that people can submit multiple values in the query strying somehow, ie: http://server/blah.php?FacilityCode=FT,CC,DD,EE
I tried changing the query to an "IN" clause instead of an "equals" but I'm not sure how to get the ' marks around each element.
Use implode() function for IN (...).
$a = array('AB', 'CD', 'EF', 'ZE');
echo "field IN ('" . implode("', '", $a) . "')";
... will output:
field IN ('AB', 'CD', 'EF', 'ZE')
+escape every option you get.
$facilitycode = mysql_real_escape_string($_GET["FacilityCode"]);
$array=explode(',',$facilitycode);
foreach ($array as $a){$output.="'$a',";}
$clause=substr($output,0,-1);
If your trying to create a string which looks like this: 'AB', 'CD', 'EF', 'ZE'
Try this before its placed inside the query:
$facilitycode = preg_replace('/([^,]+)/', '\'$1\'', $facilitycode);
I wrote this based on your query, but still I dont get this part of query "AND ('" . $facilitycode . "' = ''", anyway you need to check if $_GET data have "," and if does explode that variable by "," so that you can add an OR clausule for everything that was separated by "," in $_GET data.
After that just form your query by doing a foreach for every element in exploded array like I done below:
<?php
$facilitycode = $_GET["FacilityCode"];
$facility_number_chk = strpos($facilitycode, ",");
if ($facility_number_chk > -1) {
$facilitycode = explode(",", $facilitycode);
$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
"AND ('" . $facilitycode . "' = ''";
foreach($facilitycode as $facode) {
$facode = mysql_real_escape_string($facode);
$sql .= " OR Facility.FacilityCode = '". $facode . "'";
}
$sql .= "')";
}
else {
$facilitycode = mysql_real_escape_string($facilitycode);
$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
"AND ('" . $facilitycode . "' = '' OR Facility.FacilityCode = '". $facilitycode . "')";
}
$result = mysql_query($sql);
And if there is only one element in $_GET data just do an else like I done with your regular query.
I ended up using a combination of a few of the answers. Basically I exploded on the ",", then did a foreach to add the ' marks and call escape_string, and then imploded it back.
$facilitycodes = $_GET["FacilityCode"];
if ($facilitycodes == '') {
$additionalfilter = '';
}
else {
$facilitycodearray = explode(",", $facilitycodes);
foreach($facilitycodearray as &$facilitycode) {
$facilitycode = "'" . mysql_real_escape_string($facilitycode) . "'";
}
$facilitycodesformatted = implode(",", $facilitycodearray);
$additionalfilter = " AND Facility.FacilityCode IN (" . $facilitycodesformatted . ")";
}
$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
$additionalfilter;

How to write query for a php array?

I have the following php array that gets all values from a form full of radios and check-boxes.
foreach(array('buss_type','anotherfield','anotherfield','...etc') as $index)
{
if (isset($this->request->post[$index])) {
$this->data[$index] = $this->request->post[$index];
} else {
$this->data[$index] = NULL;
}
}
Now, I am wondering how to write the query to send those values to my database, to a new table I just created (retailer). Every radio/checkform value has its column in my retailer table, how do I write the query so that all the values contained in $index go to their specific column.
The following is an example of how my other queries look like...
public function addCustomer($data) {
//this is the one I am trying to write, and this one works,
//but I'd have to add every single checkbox/radio name to the
//query, and I have 30!
$this->db->query("INSERT INTO " . DB_PREFIX . "retailer SET buss_t = '" .
(isset($data['buss_t']) ? (int)$data['buss_t'] : 0) .
"', store_sft = '" .
(isset($data['store_sft']) ? (int)$data['store_sft'] : 0) .
"'");
//Ends Here
$this->db->query("INSERT INTO " . DB_PREFIX . "customer SET store_id = '" .
(int)$this->config->get('config_store_id') . "', firstname = '" .
$this->db->escape($data['firstname']) . "', lastname = '" .
$this->db->escape($data['lastname']) . "', email = '" .
$this->db->escape($data['email']) . "', telephone = '" .
$this->db->escape($data['telephone']) . "', fax = '" .
$this->db->escape($data['fax']) . "', password = '" .
$this->db->escape(md5($data['password'])) . "', newsletter = '" .
(isset($data['newsletter']) ? (int)$data['newsletter'] : 0) .
"', customer_group_id = '" .
(int)$this->config->get('config_customer_group_id') .
"', status = '1', date_added = NOW()");
Thanks a lot for any insight you can provide.
the best way would be to create a function that accepts an array and table name as an argument and executes a insert query.
function insertArray($table, $array)
{
$keys =""; $values = "";
foreach($table as $k=>$v)
{
$keys.=($keys != "" ? ",":"").$k:
$values .=($values != "" ? "," :"")."'".$v."'";
}
$this->db->query("INSERT INTO ".$table." (".$keys.") VALUES (".$values.");
}
The array has to be structured like this:
array("db_attribute1"=>"value1","db_attribute2"=>"value2");
Store the column names and column values in separate arrays and use implode() to generate a comma-separated list of columns and values
$values = array();
$columns = array('buss_type','anotherfield','anotherfield','...etc');
foreach($columns as $index)
{
if (isset($this->request->post[$index]))
{
$this->data[$index] = $this->request->post[$index];
$values[] = $this->db->escape($this->request->post[$index]);
}
else
{
$this->data[$index] = NULL;
$values[] = "''";
}
}
$this->db->query("INSERT INTO table_name (" . implode(",", $columns) . ") VALUES (" . implode(",", $values) . ");

Categories