I dont know whether it's a duplicate one or not?
Here is what i'm trying:
<?php
session_start();
include('db.php');
$valid_data=$_POST['data'];
if(isset($_POST['data']))
{
$list = isset($_SESSION['strtpnt1']) ? $_SESSION['strtpnt1'] : array();
$_SESSION['strtpnt1'][] =$valid_data;
$a=implode(',',$_SESSION['strtpnt1']);
}
?>
when i use print_r for $_SESSION['strtpnt1'] i could see like this:
array (size=5)
0 => string 'trivandrum' (length=10)
1 => string 'kochi' (length=5)
2 => string 'nagercoil' (length=9)
3 => string 'thrissur' (length=8)
I found nothing wrong with that
when i echoed the imploded variable i find the value like this:
trivandrum,kochi,nagercoil,thrissur
When i tested the imploded data in wampserver phpmyadmin's sql like this i could get an error message:
select start from tbl_place where start NOT IN(trivandrum,kochi,nagercoil,thrissur)
the error message is:
Unknown column 'trivandrum' in 'where clause'
But the query works when string value is passed ie 'trivandrum','kochi' etc.
i dont know what is wrong with my query ...here is the query part
$sql21 = "select start from tbl_place where start NOT IN('".$a."')";
For now you can try this but prepared statement is best for it. You can use PDO or MYSQLi . it doesn't work for you because NOT IN needs the list to individually be quoted and separated by commas.
$a=$_SESSION['strtpnt1'];
$new_a= "'" . implode("','", $a) . "'";
$sql21 = "select start from tbl_place where
start NOT IN($new_a)";
Similar Ideas
:Can I bind an array to an IN() condition?
Proper format for PDO and MySQL IN/NOT IN queries
There is error in your parameter $a value, all values inside IN() should be quoted and separated by commas.
Change your code like following:
$a=implode("','",$_SESSION['strtpnt1']); // ',' => "','"
$sql21 = "select start from tbl_place where start NOT IN('".$a."');";// no change
// NOW the SQL query will became: select start from tbl_place where start NOT IN('trivandrum','kochi','nagercoil','thrissur');
Now it should work.
$sql21 = "select start from tbl_place where start NOT IN('".$a."')";
will querying like this :
$sql21 = "select start from tbl_place where start NOT IN('trivandrum,kochi,nagercoil,thrissur')";
which will treat as a whole string
you have to do in passing variable
$a=implode("','",$_SESSION['strtpnt1']);
Related
I am attempting to do a string search with a like clause using PDO. The name has an apostrophe. All my attempts thus far have resulted in no results found even though the names exist.
This code works, where I have hardcoded the array values:
// looking for last names that start with A' and any first name
like_string = array("A'%", "B%");
$sql = "SELECT p.last_name, p.first_name
FROM person p
WHERE p.last_name LIKE ? AND p.first_name LIKE ? ";
$fields = array($like_string[0], $like_string[1]);
$stmt = $this->pdb->prepare($sql);
$stmt->execute($fields);
$result = $stmt->fetchALL(PDO::FETCH_ASSOC);
However this code, where the string array is built within the php code, does not, and I do not understand why.
// e.g $search val = "A', B";
$search_array = explode(',',$search_val);
$like_string[0] = trim($search_array[0]) . "%";
$like_string[1] = trim($search_array[1]) . "%";
The results from the code above produces array values of:
$like_string[0] = "A'%"
$like_string[1] = "B%"
yet no rows are returned. I have even tried adding addslashes as seen below - still no rows fetched:
// e.g $search val = "A', B";
$search_array = explode(',',$search_val);
$like_string[0] = addslashes(trim($search_array[0]) . "%");
$like_string[1] = addslashes(trim($search_array[1]) . "%");
Any help would be greatly appreciated.
As an update to a previous comment, the code below produces
$search_val = "A', B";
$search_array = explode(',',$search_val);
$like_string[0] = trim($search_array[0]) . "%";
$like_string[1] = trim($search_array[1]) . "%";
var_dump($like_string);
the following output from var_dump
array (size=2)
0 => string 'A'%' (length=3)
1 => string 'B%' (length=2)
And I believe the issue is that the resultant strings above are not surrounded in double quotes. So how do I force that to occur?
I discovered the issue. The search string entered by the user was being sanitized by calling
escape_string(filter_var($item_to_prep, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH));
This caused a conflict with the PDO functions.
I have this issue.
I need to receive, from comments column in mysql database, a string like this:
WHERE IDTable=$number
When i get this comment i have to put it like a Where clause in my query.
But if i write this code
$where=getComment($table,$field); //I get the string i wrote above
$number=5; //I initialize $number in my code
$sql="SELECT * FROM table $where";
print "SQL: $sql";
i get this:
SELECT * FROM table WHERE IDTable=$number
obviously i'd like to have in response:
SELECT * FROM table WHERE IDTable=5
How can I do that?
Thanks
I strongly suspect that the code you have a problem with is not the same code as above, as the above would not produce the result you stated. At the very least you are missing the definition of the function you're calling, to create said output.
However, what would produce such a result is by using single quotes around a string. Which prevents variable expansion, and treats them as regular strings instead.
Not only that, but your code is out of order as well. You cannot use a variable before you have declared it, as it simply does not exist yet.
The string returned by getComment() will not be parsed, so any PHP variables in it ($number) will be returned as the literal string.
I can think of two options -
1
Allow an extra parameter for getComment() so you can pass it $number
$number=5;
$where = getComment($table,$field,$number); // returns "WHERE IDTable=5"
$sql="SELECT * FROM table $where";
2
Do not return $number from getComment(), then you can add it when you build the query.
$where=getComment($table,$field); // returns "WHERE IDTable="
$number=5;
$sql="SELECT * FROM table $where $number";
Perhaps the String Value you got from MySQL: WHERE IDTable=$number may have been enclosed within Single Quotes. Consider the Example Below.
$number = 22;
$str = 'WHERE IDTable=$number';
var_dump($str); //<== YIELDS:: 'WHERE IDTable=$number' B'COS IT'S IN SINGLE QUOTES
$parts = explode("=", $str);
list($where, $var) = $parts;
$var = ltrim(trim($var), "\$");
$newStr = trim($where . "=" . $$var);
var_dump($$var); //<== YIELDS:: int 22
var_dump($newStr); //<== YIELDS:: 'WHERE IDTable=22' (length=16)
Assuming this is the case with your String; to get around that, You may simply want to extract the Variable from the String and then rebuild the String as the Snippet above demonstrates. Otherwise; if you have a possibility of enclosing the String in Double Quotes, this convoluted work-around would be utterly irrelevant.
I am currently testing how to use a simple implode for a mysql query after I have pushed the variables into the array. I just can't get around the error, I know it says, invalid arguments, but the array has been set up and I know it worked in another part of my page with an almost identical code.. I guess there are somewhere missing some ' or " or . or but no matter what I change it doesn't work.
I appreciate any help!
Here is the part where I set up the array:
$LFBsubjects = Array();
$LFBsubjects[] = $dataset2['subject1'];
$LFBsubjects[] = $dataset2['subject2'];
And the output I have printed via print_r is:
Array ( [0] => Mathematics [1] => English )
Now comes the query, which uses the implode function:
$SelectTSubjectsQuery = "
SELECT subject_id FROM subjects
WHERE subject IN (".implode(',', $LFBSubjects).")";
$statement = $pdo->query($SelectTSubjectsQuery);
The error is:
Warning: implode(): Invalid arguments passed in /var/www/xxx/html/lfb.php on line 626
Invalid argument error means you need to use quotes between string for MYSQL QUERY like IN ("test")
You can use as like:
$values = implode("','", $LFBsubjects);
$SelectTSubjectsQuery = " SELECT subject_id FROM subjects WHERE subject IN ('".$values."')";
Explanation:
Your array consists on string values when you use IN RANGE in MYSQL for string values than you must need to pass it in quotes.
Basic example:
$SelectTSubjectsQuery = "
SELECT subject_id FROM subjects
WHERE subject IN ('val1','val2')";
Update 1
After checking your comments, you are using wrong variable name in implode
$LFBSubjects
This should be this:
$LFBsubjects // with small s
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.
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