Problem with Yii2 PDO Statement Postgres Query - php

I have some problems/doubt with PDO statement and Yii2 query.
I've search and read some question here but i didn't find a solution.
So i have an array like this
array (size=3)
0 => string '12345'
1 => string '6789'
2 => string '101258'
From this array i create a string to insert in my IN condition for SQL query
//$split_var is the previous array
$var_query = implode( "','" , $split_var);
//'12345','6789','101258' i obtained this string
So now I try to create a query like this way
$tupla = Yii::$app->db->createCommand("
SELECT * FROM oln, opt WHERE opt_cod = oln_opt_cod AND oln_cod IN ( :var_query) order by oln_cod ASC
")
->bindValue(':var_query' ,$var_query);
$result = $tupla->queryAll();
It doesn't give me any error but the resulted query isn't what I'm expected. In fact I'll get that query:
SELECT * FROM oln, opt WHERE opt_cod = oln_opt_cod AND oln_cod IN ( '01Y0BIAN'',''05C2LARG'',''0661NO00') order by oln_cod ASC
The problem is in the IN condition and I don't know Why it added another '.
I tried also this method but I don't know how to bind parameters in this way:
$query = (new \yii\db\Query())
->select('*')
->from('oln, opt')
->where('opt_cod = oln_opt_cod')
->andwhere('in', 'oln_cod',[':oln_cod' => $var_query])
->addParams([':oln_cod' => $var_query])
->orderBy('oln_cod ASC')
->all();

Another ' is added because of escaping. Since $var_query is actually a string, it will be treated as single string value and any ' will be escaped to prevent SQL injection. You're building your IN condition in wrong way, you should bind every ID in IN separately:
$tupla = Yii::$app->db->createCommand(
"SELECT * FROM oln, opt WHERE opt_cod = oln_opt_cod"
. " AND oln_cod IN (:var_query1, :var_query2, :var_query3) order by oln_cod ASC"
)
->bindValue(':var_query1', 12345)
->bindValue(':var_query2', 6789)
->bindValue(':var_query3', 101258);
It probably will be easier to use foreach to bind all params. It is also much simpler with Yii wrapper, which has nice shortcut for building IN conditions:
$query = (new \yii\db\Query())
->select('*')
->from('oln, opt')
->where('opt_cod = oln_opt_cod')
->andwhere(['in', 'oln_cod', $split_var]) // $split_var is array of values
->orderBy('oln_cod ASC')
->all();

Related

very strange thing in cake php... converting multiple value to string

i am using below query ,its converting all things to string
$idsv =$_GET['ids'];
$ids=$db->value($idsv, 'string');
$search = $this->Search->query("select * from colleges where college_id!='' and college_id in ($ids) ");
above code is working ok for single string , but if $idsv =1,2,3,4 its giving result only for 1
You need to it like below:-
$idsv =$_GET['ids'];
$ids=$db->value($idsv, 'string');
$ids = "'".implode("','",explode(',',$ids))."'";
$search = $this->Search->query("select * from colleges where college_id!='' and college_id in ($ids) ")
output:- https://eval.in/716469
Note:- IN query works perfectly for ('1','2','3',...) but takes only first one when comes like this:-('1,2,3,4').
And that's the exact reason why it's failing in your case.
What you shown in comment,do like below:-
$idsv =$_GET['ids'];
$ids=$db->value($idsv, 'string');
$ids = implode("','",explode(',',$ids));
$search = $this->Search->query("select * from colleges where college_id!='' and college_id in ($ids) ")

How to create multiple word search? SQL

We have made a search field where you can search for ingredients and find recipes.
For now you can only type in 1 ingredient:
if (isset($_POST['search'])) {
$searchquery = $_POST['search'];
$query = mysql_query("SELECT * FROM opskrifter WHERE id IN
(SELECT opskrifterid FROM ingredienser WHERE ing_name IN ('$searchquery'))") or die("search failed");
We want to be able to search for multiple ingredients in the same search field by seperating the ingredients with a "," or something like this.
Is there a simple way to make that happen ?
EDIT:
We tried to use explode like this without succes.
$searchTerms = explode(' ', $searchquery);
$searchTermBits = array();
foreach ($searchTerms as $term) {
if (!empty($term)) {
$searchTermBits[] = "ing_name '$term'";
}}
...
$result = mysql_query("SELECT * FROM opskrifter WHERE id IN (SELECT * FROM WHERE ".implode(' AND ', $searchTermBits)));
Thanks! :)
You could simply get the user to type in his values comma-separated, the the input would be almost in the right syntax for the query. You just have to add semicolons around the values because you search for a string in your table.
You can use PHP's str_replace()-Function:
$vals = $_POST['search'];
$valsFormatted = "'" . str_replace(",", "','", $vals) . "'";
In this code, you replace all the commas of the input with the comma plus semicolons before and behind them in orderto wrap all values of the input with semicolons. You also have to add one at the beginning and at the end of the string. Replace the first comma in the function above with the char you want your users to separate the values with.
After that, you can simply change your query to the following:
$query = "SELECT * FROM opskrifter WHERE id IN
(SELECT opskrifterid FROM ingredienser WHERE ing_name IN ('$valsFormatted'))";
Please also be informed, that your code like this is vulnerable for SQL Injections! Check out this link to learn how to prevent this.
A simple statement like this would work:
$array = implode("','",explode($_POST['search'], ","));
$query = mysql_query("SELECT * FROM opskrifter WHERE id IN (SELECT opskrifterid FROM ingredienser WHERE ing_name IN ({$array}))") or die("search failed");
First explode your search, then implode it (might not even need to do so). After that make sure the array gets used as the 'in' operator as a string/array.
For more information about this, you could read this question: PHP/MySQL using an array in WHERE clause
The working copy from my local machine was this;
$_POST['search'] = "0, 1, 2";
$array = implode ( "','", explode ( ",", $_POST['search'] ) );
$query = mysql_query("SELECT * FROM users WHERE id IN ('$array')") or die(mysql_error());
var_dump ( $array );
var_dump ( $query );
var_dump ( "SELECT * FROM users WHERE id IN ('$array')" );
var_dump ( mysql_fetch_array ( $query ) );
which actually did return users, so if we would take this example and change it to your code, it would be (the query, at least):
$query = mysql_query("SELECT * FROM opskrifter WHERE id IN (SELECT opskrifterid FROM ingredienser WHERE ing_name IN ('$array'))") or die(mysql_error());
Do take note of the changed $array variable too.
First you need to convert the text coming from the search field to array with:
$string = $_POST['search'];
$array = explode( '"' , $string);
So if you put in the search: test"hello"hi
the array will be:
1 => test,
2 => hello,
3 => hi
After that, you need to use the SQL format:
WHERE column_name IN (value1,value2,...)
So you need to change the array we have created to a string with this format:
$string = implode(',',$array);
So the echo of $string will be:
test,hello,hi
and SQL will be :
WHERE column_name IN ($string)

How to use like clause in Laravel when we are using Raw SQL ?

I'm using Laravel raw sql query feature. And have to perform a like query. There are so many joins and checking in this code. So it's better to use raw SQL. Everything is working fine. But when I use the like , there's an error.
$Stars = DB::select('select v.videoid,s.seriesshortname, v.videotitle, v.VideoShortName, v.VideoImagepath, v.Views, v.Likes, v.Dislikes, v.Rating, v.videocategory, v.lastupdated,v.videocategory,v.seriesid,v.genreid,v.studioid from tblvideo v, tblpornstarvideo pv,tblseries s,tblpornstar p where v.videoid = pv.videoid and v.seriesid = s.seriesid and upper(v.Active) = \'Y\' and pv.psid = p.psid and pv.psid = :id and (v.site = 1 or v.site=3) and v.videotitle like \':letter%\' order by v.videotitle limit 6 offset :offset', ['id' => $id, 'offset' => $offset]);
Please check the like code. (v.videotitle like \':letter%\')
And please tell me how to make that working.
I followed the documentation here.
https://laravel.com/docs/5.1/database
Add the wildcards to your variable, not the query, and don't add the quotes. You're also not passing in the letter variable:
$Stars = DB::select("select v.videoid,s.seriesshortname, v.videotitle, v.VideoShortName, v.VideoImagepath, v.Views,
v.Likes, v.Dislikes, v.Rating, v.videocategory, v.lastupdated,v.videocategory,v.seriesid,v.genreid,v.studioid
from tblvideo v, tblpornstarvideo pv,tblseries s,tblpornstar p
where v.videoid = pv.videoid and v.seriesid = s.seriesid and
upper(v.Active) = 'Y' and pv.psid = p.psid and pv.psid = :id and (v.site = 1 or v.site=3)
and v.videotitle like :letter order by v.videotitle limit 6 offset :offset", ['id' => $id, 'letter'=> $letter.'%', 'offset' => $offset]);

PHP: How to insert array value into mysql statement

i have this array and get it from from an url. this array is member id that i need to pass to mysql.
$member_id = $_GET['member_id'];
the array like this : Array ( [0] => 1269 [1] => 385 )
how can i transfer this array into my mysql statement and make , become AND :
$answer_sql = mysql_query("SELECT tna_category. * , tna_question. *, tna_answer. *
FROM tna_category, tna_question, tna_answer
WHERE tna_category.section_id = '$section_id1'
AND tna_question.id = tna_answer.question_id AND tna_question.category_id = tna_category.id
AND tna_answer.member_id = ['1269' , '385']
ORDER BY tna_answer.question_id");
should i put bracket?..
in this part : tna_answer.member_id = Array or $member_id
As others have said, you can use IN() but you are apparently open to SQL injection attacks as it is. You need to do this:
$escaped_ids = array_map('mysql_real_escape_string', $member_ids);
Or, if they are surely all integers
$escaped_ids = array_map('intval', $member_ids);
Then, you can write your query like:
$query = "SELECT tna_category. * , tna_question. *, tna_answer. *
FROM tna_category, tna_question, tna_answer
WHERE tna_category.section_id = '" . mysql_real_escape_string($section_id1) . "'
AND tna_question.id = tna_answer.question_id
AND tna_question.category_id = tna_category.id
AND tna_answer.member_id IN (".implode(",", $escaped_ids).")
ORDER BY tna_answer.question_id";
Never, never, never put unescaped values in your query.
Also, you should not be using the mysql_ functions anymore. Please consider using the mysqli_ functions instead.
First split the array value, get no. of rows in the array value and pass the value one by one into the query by using for or foreach loop.
try this
$member_id = $_GET['member_id'];
If you're already getting comma seprated values then there's no need to use explode function just use implode function in database query.
$member_id = explode(",", $member_id);
and then
answer_sql = mysql_query("SELECT tna_category. * , tna_question. *, tna_answer. *
FROM tna_category, tna_question, tna_answer
WHERE tna_category.section_id = '$section_id1'
AND tna_question.id = tna_answer.question_id AND tna_question.category_id = tna_category.id
AND tna_answer.member_id IN (".implode(",", $member_id).")
ORDER BY tna_answer.question_id");
the explode function create array it depends on you explode value with comma OR space and then implode mean join these values with comma OR space.
for more detail explode and implode.
you can use IN clause of mysql like this
$your_array = array("0"=>"1269", "1"=>"385");
$in_text = implode(",", $your_array);
$sql = "SELECT tna_category. * , tna_question. *, tna_answer. *
FROM tna_category, tna_question, tna_answer
WHERE tna_category.section_id = '$section_id1'
AND tna_question.id = tna_answer.question_id
AND tna_question.category_id = tna_category.id
AND tna_answer.member_id IN ($in_text)
ORDER BY tna_answer.question_id";

How to mysql_query from same table with different where clause in same php file

I have a table containing 4 articles with id 1,2,3 and 4 as well as ordering value 1,2,3,4.
They have separate columns for their title, image etc. I need to get them distinctly with where clause. So i did:
For article 1:
//topstory1
$sql_topstory1 ="SELECT * FROM topstory WHERE story_active='1' && story_order='1'";
$result_topstory1 = mysql_query($sql_topstory1);
$row_topstory1 = mysql_fetch_array($result_topstory1);
$story1_title = $row_topstory1['story_title'];
$story1_abstract = $row_topstory1['story_text'];
And for article 2
//topstory2
$sql_topstory2 ="SELECT * FROM topstory WHERE story_active='1' && story_order='2'";
$result_topstory2 = mysql_query($sql_topstory2);
$row_topstory2 = mysql_fetch_array($result_topstory2);
$story2_title = $row_topstory2['story_title'];
$story2_abstract = $row_topstory2['story_text'];
As I have to reuse them in a page.
PROBLEM IS, the first query works but the second one doesn't. It seems like MySql cannot execute two consecutive queries on the same table in a single php file. But I think there is a simple solution to this...
Please help me soon :( Love you guys :)
There are several possible reasons for the second query to fail, but the fact that it's the second query in the file does not cause it to fail.
I would expect that article 2 does not have the active flag set to 1, causing you to get an empty result set.
Another option is that you may have closed the mysql connection after the first query, then you can't execute another query. (General rule: don't close database connections. PHP takes care of that.)
Why not just get them both with 1 query?
$sql_topstory ="SELECT * FROM topstory WHERE story_active='1' && story_order IN(1, 2) ORDER BY story_order DESC";
$result_topstory = mysql_query($sql_topstory) or trigger_error('Query Failed: ' . mysql_error());
while ($row = mysql_fetch_assoc($result_topstory)) {
$title[] = $row['story_title'];
$abstract[] = $row['story_abstract'];
}
// Then to display
echo 'Story 1 is ' . $title[0] . ' with an abstract of ' . $abstract[1];
There are plenty of ways to do this, this is just a simple demonstration.
$query = <<<SQL
SELECT
story_title
, story_text
FROM
topstory
WHERE
story_active
ORDER BY
story_order ASC
SQL;
$result = mysql_query($query);
$stories = array();
while ($row = mysql_fetch_assoc($result)) {
$stories[] = $row;
}
Now you have an array of stories like so:
array(
0 => array(
'story_title' => ?
, 'story_text' => ?
)
, 1 => array(
'story_title' => ?
, 'story_text' => ?
)
)
Should be pretty easy to iterate through.

Categories