pg_query_params and pg function on DB - php

I'm switching from pg_exec to pg_query_param and when I use a normal query everything it's ok but, I have a problem when I want to use a Postgres function on the database.
Here my actual code:
$sql = "select accsmap.prep_download_files('".$dataType."','{".
$severity."}','{".
$year."}','{".
$region."}')";
$result = pg_exec($connect,$sql);
$connect it's just the DB info to connect to it.
and Here my new code:
$result = pg_query_params($connect,"select accsmap.prep_download_files( ".
"$1" ." ,{ ". "$2" ." },{ ". "$3" ." },{ ". "$4" ." });",
array($dataType, $severity, $year, $region) );
I've tried a lot of ways to translate the $sql var into the query but always it returns me errors near , or { }
and here a sample of $sql
select accsmap.prep_download_files('for Accidents occuring in the following
Authorities','{1,2,3}','{2014,2016}','{E08000001,E06000028,E06000036}')
The function expect $severity, $year and $region as array.

The problem is the way you are handling the parameters. For example:
pg_query_params($dbconn, 'SELECT * FROM shops WHERE name = $1', array("Joe's Widgets"));
If you see the query, there is a column called name (character data type) and it should be single quoted name = 'name'. But since it is inside the pg_query_params, you just use name = $1 'cause the function escapes the parameter and adds the quotes.
Therefore, since you use a postgreSQL array, it fails in constructing the query because your parameters arent well constructed. If your variable $severity is like this $severity="1,2,3" it will try to add a escaped parameter to the reference returning something like this: {'1,2,3'}.
On the other hand, If one of the parameters is an array like in your case (array of ints being passed to a stored procedure), it must be denoted as a set within the array, not php array notation.
I can't test the code, but I believe that the correct way to do it should be:
$severity='{1,2,3}';
$year='{2014,2016}';
$region='{E08000001,E06000028,E06000036}';
$result = pg_query_params($connect,"select accsmap.prep_download_files($1, $2, $3, $4)",
array($dataType, $severity, $year, $region) );

Related

Php search Splitting criteria type

I have a php search form with two fields. One for $code another for '$name'.The user uses one or the other, not both.
The submit sends via $_POST.
In the receiving php file I have:
SELECT * FROM list WHERE code = '$code' OR name = '$name' ORDER BY code"
Everything works fine, however I would like that $code is an exact search while $name is wild.
When I try:
SELECT * FROM list WHERE code = '$code' OR name = '%$name%' ORDER BY code
Only $code works while $name gives nothing. I have tried multiple ways. Changing = to LIKE, putting in parentheses etc. But only one way or the other works.
Is there a way I can do this? Or do I have to take another approach?
Thanks
If you only want to accept one or the other, then only add the one you want to test.
Also, when making wild card searches in MySQL, you use LIKE instead of =. We also don't want to add that condition if the value is empty since it would become LIKE '%%', which would match everything.
You should also use parameterized prepared statements instead of injection data directly into your queries.
I've used PDO in my example since it's the easiest database API to use and you didn't mention which you're using. The same can be done with mysqli with some tweaks.
I'm using $pdo as if it contains the PDO instance (database connection) in the below code:
// This will contain the where condition to use
$condition = '';
// This is where we add the values we're matching against
// (this is specifically so we can use prepared statements)
$params = [];
if (!empty($_POST['code'])) {
// We have a value, let's match with code then
$condition = "code = ?";
$params[] = $_POST['code'];
} else if (!empty($_POST['name'])){
// We have a value, let's match with name then
$condition = "name LIKE ?";
// We need to add the wild cards to the value
$params[] = '%' . $_POST['name'] . '%';
}
// Variable to store the results in, if we get any
$results = [];
if ($condition != '') {
// We have a condition, let's prepare the query
$stmt = $pdo->prepare("SELECT * FROM list WHERE " . $condition);
// Let's execute the prepared statement and send in the value:
$stmt->execute($params);
// Get the results as associative arrays
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
The variable $results will now contain the values based on the conditions, or an empty array if no values were passed.
Notice
I haven't tested this exact code IRL, but the logic should be sound.

MySQL UPDATE and INSERT both returning error message about bad syntax, but it is correct syntax when trying it on phpMyAdmin

I have a PHP program that will either INSERT a new row, or UPDATE the existing one if it's already there. When running on a browser, it returns errors.
But, the actual call runs OK on phpMySQL - no error reported and row is updated.
"Errormessage: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"updated", `conditions` =" ",' at line 1.
Code to connect to mySQL and make the update or insert is very simple
require_once ('mysqli_connect.php');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error($dbcon);
exit ;
}
Then I make the actual body of the call, which produces variable $call containing this (example is for UPDATE):
UPDATE `deal` SET `deal_lotus_source` = "updated", `conditions` =" ", `termsnotes` = " ", `walkprovision` = " ", `sector` = "Application Software", `industry` = "Airconditioning", `tgt` = "Bcd", `acq` = "E", `dtstart` = "2015/03/08" , `dtclose` = "2015/03/23", `dtexdivtgt` = "2015/03/17", `dtexdivacq` = "2015/03/17", `dtexdivtgtexp` = "2015/03/17", `dtexdivacqexp` = "2015/03/17", `acq` = "E",`stat`= "Closed",`acqtype`= "Domestic",`dealtype`= "Acquisition of Private Company Cash-Stoc",`analyst`= "Fred Blogs",`tgttkr`= "ABC",`tgtx`= "C",`tgtprec`= "$",`tgtpret`= "1",`tgtshrout`= "2",`acqtkr`= "D",`acqx`= "F",`acqprec`= "$",`acqpret`= "3",`acqshrsout`= "4",`dlvalue`= "5",`eacls`= "Actual",`tgtlaw`= "",`acqlaw`= "",`tgtbank`= "",`acqbank`= "",`tgtshrsoutfd`= "6",`acqshrsoutfd`= "7",`tgtdebt`= "8",`acqdebt`= "8",`suppress`= "0",`pricingp`= "",`terminate`= " ",`divstattgt`= "",`divstatacq`= "",`divfreqtgt`= "Quarterly",`divfreqacq`= "Quarterly",`divcurrtgt`= "$",`divcurracq`= "$",`divamttgt`= "0.000",`divamtacq`= "0.000", `cos` = "", `mot` = "" WHERE deal_id =578
and the code to update (or insert) is
if (!mysqli_query($dbcon, $call)) {
printf("Errormessage: %s\n", mysqli_error($dbcon));
die;
}
Any ideas?
You have to use single quotes arround the values:
UPDATE `deal` SET `deal_lotus_source` = 'updated', `conditions` =' ', `termsnotes` = ' ', `walkprovision` = ' ', `sector` = 'Application Software', ...
Quotes in PHP can be confusing, because depending on which type of quote you use there are (different rules](http://www.trans4mind.com/personal_development/phpTutorial/quotes.htm). The most important things (in this case) to keep in mind are these 2:
* If you have a variable ($var) inside double-quotes ("$var") then it will get substituted (your string will now contain value) whereas if it is in single-quotes ('$var') then it will NOT get substituted (it remains in your string as $var)
* If you are need single-quotes as part of your string then use double-quotes around the string. ("I don't like contractions and I can't bear to use them.") If you need double-quotes as part of your string then use single quotes to surround the string. ('He said, "Hello, Dear!" and she slapped him.')
You are using double quotes (note the values you want to compare conditions and termsnotes and etc. to) but you are going to want to change to single-quotes inside the string so you can surround the whole thing with double-quotes. This also has the advantage of allowing you to use variables inside it.
$call = "UPDATE `deal`
SET `deal_lotus_source` = 'updated',
`conditions` =' ',
`termsnotes` = ' ',
`walkprovision` = ' ',
...
`mot` = ''
WHERE deal_id =578";
Note that the only double-quotes in that whole line of code are the ones at the very beginning and ending of the string. If you want to put a double-quote inside the string then you would have to put a backslash in front of it.
One very important step when you are constructing a query in a string (especially if you are getting errors with it) is to actually look at it. Use echo "call=<pre>$call</pre><br />\n"; and then look very carefully at all your quotes and etc. You can actually copy/paste the results of this echo into phpMyAdmin and see if the actual query works in your sql tab - this is a great test.
In summary, quotes in PHP are very consistent and very powerful, but they do have the potential to change your string during the process of assigning the string to a variable. It's very important to verify that the string after assignment is the string that you expect.

PDO params not passed but sprintf is

Unless I am missing something very obvious, I would expect the values of $data1 and $data2 to be the same?? But for some reason when I run this scenario twice (its run once each function call so I'm calling the function twice) it produces different results.
Call 1: PDO = Blank, Sprintf = 3 rows returned
Call 2: PDO = 1 row, Sprintf = 4 rows (which includes the PDO row)
Can someone tell me what I'm missing or why on earth these might return different results?
$sql = "SELECT smacc.account as Smid,sappr.*,CONCAT('$domain/',filepath,new_filename) as Image
FROM `{$dp}table`.`territories` pt
JOIN `{$dp}table`.`approvals` sappr ON pt.approvalID = sappr.ID
JOIN `{$dp}table`.`sm_accounts` smacc ON pt.ID = smacc.posted_territory_id
LEFT JOIN `{$dp}table`.`uploaded_images` upimg ON pt.imageID = upimg.ID
WHERE postID = %s AND countryID = %s AND smacc.account IN (%s) AND languageID = %s";
echo sprintf($sql,$postID,$countryID,implode(',',$accs),$langID);
$qry1 = $db->prepare(str_replace('%s','?',$sql));
$qry1->execute(array($postID,$countryID,implode(',',$accs),$langID));
$data1 = $qry1->fetchAll();
print'<pre><h1>PDO</h1>';print_r($data1);print'</pre>';
$qry2 = $db->query(sprintf($sql,$postID,$countryID,implode(',',$accs),$langID));
$data2 = $qry2->fetchAll();
print'<pre><h1>Sprintf</h1>';print_r($data2);print'</pre><hr />';
The root of the problem is the implode(',',$accs) function.
While you are using sprintf() it will generate a coma separated list and that list will be injected into the query string.
The result will be something like this:
smacc.account IN (1,2,3,4,5)
When you are binding the same list with PDO, it handles it as one value (a string: '1,2,3,4,5'). The "result" will be something like this:
smacc.account IN ('1,2,3,4,5')
Note the apostrophes! -> The queries are not identical.
In short, when you are using PDO and binding parameters, you have to bind each value individually (you can not pass lists as a string).
You can generate the query based on the input array like this:
$query = ... 'IN (?' . str_repeat(', ?', count($accs)-1) . ')' ...
// or
$query = ... 'IN (' . substr(str_repeat('?,', count($accs)), 0, -1) . ')'
This will add a bindable parameter position for each input value in the array. Now you can bind the parameters individually.
$params = array_merge(array($postID, $countryID), $accs, array($langID));
$qry1->execute($params);
Yes as Kris has mentioned the issue with this is the IN part of the query. Example 5 on the following link helps fix this: http://php.net/manual/en/pdostatement.execute.php. I tried using bindParam() but that didn't seem to work so will use Example 5 instead.

Handling Postgres output function parameters in PHP

I have a Postgres database I wish to access. I need to call several functions that exist in the DB. I have achieved connection to the database and running queries. I have also achieved to call the functions I want. My problem is that when a Postgres function has more than one OUT parameters, instead of returning an array I can access either with the offset or with the row name, it instead returns a string with both the OUT parameters:
$query = "Select pg_function('" . Getenv("REMOTE_ADDR") . "')";
$result = pg_query($query);
$line = pg_fetch_array($result, NULL, PGSQL_ASSOC);
var_dump($line);
What var_dumb returns is this:
array
'ua_bl_session_request' => string '(c6787f5f2b2c885168162c8c8ffff220,8fe04393-c188-0e08-b710-a2ce89066768)' (length=71)
I can of course parse that string but is there a way to achieve what I want and I am missing it?
SELECT * FROM pg_function(REMOTE_ADDR);
Maybe you are using pg_fetch_array() incorrectly, because you should give the row number in the second parameter. For example:
// To get the first row (Rows are numbered from 0 upwards)
$line = pg_fetch_array($result, 0, PGSQL_ASSOC);
// To get the second row
$line = pg_fetch_array($result, 1, PGSQL_ASSOC);
But if you know what you are doing, you can use regexp_split_to_table(), it is a Posgtres string function that split a string to rows using a POSIX regular expression as the delimiter. For example:
$query = "select regexp_split_to_table(
pg_function('" . Getenv("REMOTE_ADDR") . "'), ','
)";
In your case, it will split the function's result using ',' as delimiter. It should return a result set with two rows, like below:
c6787f5f2b2c885168162c8c8ffff220
8fe04393-c188-0e08-b710-a2ce89066768

MySQL where clause equals anything (SELECT * WHERE col = ANY_VALUE)

I'd like to create a query in MySQL that has an optional value. When the value is specified the query is filtered by that value, when the value is not all rows are returned. Here's the idea:
public function doQuery($item = 'ANY_VALUE') {
$query = "SELECT * FROM table WHERE item = ?";
db->fetchAll($query,array($item))
...
}
doQuery(); // Returns everything
doQuery($item='item1'); // Returns only rows where item = 'item1'
Is there an easy way to do this without creating two query strings depending on the value of $item?
As far as I know, no such "any" placeholder exists.
If you can use LIKE, you could do
SELECT * FROM table WHERE item LIKE '%'
if you can append a condition, you could nullify the item clause like this:
SELECT * FROM table WHERE item = ? OR 1=1
(won't work in your example though, because you are passing "item" as a parameter)
That's all the options I can see - it's probably easiest to work with two queries, removing the WHERE clause altogether in the second one.
This would probably work, but I*m not sure whether it's a good idea from a database point of view.
public function doQuery($item = 'ANY_VALUE') {
$query = "SELECT * FROM table WHERE item = ? OR 1 = ?";
db->fetchAll($query,array($item, ($item == 'ANY_VALUE' ? 1 : 0))
...
}
Better way to do this is first generate sql query from the parameter you need to bother on, and then execute.
function doQuery($params) {
$query = 'SELECT * FROM mytable ';
if (is_array($params) // or whatever your condition ) {
$query .= 'WHERE item = ' . $params[0];
}
$query .= ' ;';
// execute generated query
execute($query);
}
You cannot get distinct results without giving distinct query strings.
Using $q = "... WHERE item = '$item'" you DO create distinct query strings depending on the value of $item, so it is not that different from using
$q = "..." . ($item=='ANY_VALUE' ? something : s_th_else);.
That said I see two or three options:
use function doQuery($item = "%") { $query = "SELECT ... WHERE item LIKE '$item'"; ...}
But then callers to that function must know that they must escape a '%' or '_' character properly if they want to search for an item having this character literally (e.g. for item = "5% alcoholic solution", giving this as argument would also find "50-50 sunflower and olive oil non alcoholic solution".
use function doQuery($item = NULL) { $query = "SELECT ..."; if ($item !== NULL) $query .= " WHERE item = '$item' "; ...} (where I use NULL to allow any other string or numerical value as a valid "non-empty" argument; in case you also want to allow to search for NULL (without quotes) you must choose another "impossible" default value, e.g., [], and you must anyway use a distinct query without the single quotes which however are very important in the general case), or even:
use function doQuery($item = NULL) { if($item === NULL) $query = "SELECT ..."; else $query = "SELECT ... WHERE item = '$item' "; ...}, which is more to type but probably faster since it will avoid an additional string manipulation (concatenation of the first and second part).
I think the 2nd & 3rd options are better than the first one. You should explain why you want to avoid these better solutions.
PS: always take care of not forgetting the quotes in the SQL, and even to properly escape any special characters (quotes, ...) in arguments which can depend on user input, as to avoid SQL injections. You may be keen on finding shortest possible solutions (as I am), but neglecting such aspects is a no-no: it's not a valid solution, so it's not the shortest solution!

Categories