I m trying to pass comma separated values inside IN condition in cakephp 3 but it gets values with single quotes inside brackets ('12,18').
Please suggest me how to remove this.
Expected output (12,18)
Below is my code
public function checkPermission(){
$userId = $this->request->getSession()->read('Auth.User.id');
$arodta = TableRegistry::get('Aros');
$Arosdata = $arodta->find()->where(['foreign_key' => $userId])->first()->toArray();
if(!empty($Arosdata)){
$aroId = $Arosdata['parent_id'];
$aroAcodata = TableRegistry::get('ArosAcos');
$arocodata = $aroAcodata->find()->where(['aro_id =' => $aroId]);
if(!empty($arocodata)) {
foreach ($arocodata as $data){
$acoId[] = $data['aco_id'];
}
if(!empty($acoId)){
$acoData = implode(',',$acoId);
$acosName = TableRegistry::get('Acos');
$arac = $acosName->find()->where(['id IN' => $acoData]);
sql($arac);exit;
}
}
}
}
My Array data
$acoId[] =
Array
(
[0] => 12
[1] => 18
)
I am getting output like
SELECT
Acos.id AS `Acos__id`,
Acos.parent_id AS `Acos__parent_id`,
Acos.model AS `Acos__model`,
Acos.foreign_key AS `Acos__foreign_key`,
Acos.alias AS `Acos__alias`,
Acos.lft AS `Acos__lft`,
Acos.rght AS `Acos__rght`
FROM
acos Acos
WHERE
id in ('12,18')
In Cakephp you can directly pass array for IN clause instead imploding it with comma. Use $acoId array in your query:
$arac = $acosName->find()->where(['id IN' => $acoId]);
Related
I have a data array like:
$skill_set=$_POST['ckbox'];
When I print the skill set with print_r($skill_set); the results are:
Array ( [0] => core_UniversityEngScience [1] => core_CommercialPilot [2] => core_ATC [3] => core_5yrsExpinAerodromesOps [4] => core_5yrsExpinFltOps )
Now i want write a query like
Select * from tbl where core_UniversityEngScience='yes' AND core_CommercialPilot='yes' AND core_ATC='yes' AND core_5yrsExpinAerodromesOps='yes' AND core_5yrsExpinFltOps='no'
Hope you got my point what i want. Please help me.
Use the following kind of logic to capture the variables for your sql string:-
$core_UniversityEngScience = in_array("core_UniversityEngScience", $skill_set)?"yes":"no";
$xxx_checkbox = in_array("xxx_checkbox", $skill_set)?"yes":"no";
// similar way for other variables and then you can use them.
Follow the answer by nandal (which is a good "help" answer as a start) and set all the variables and the full query becomes:
$sql = "Select * from tbl where core_UniversityEngScience='$core_UniversityEngScience' AND core_CommercialPilot='$core_CommercialPilot' AND core_ATC='$core_ATC' AND core_5yrsExpinAerodromesOps='$core_5yrsExpinAerodromesOps' AND core_5yrsExpinFltOps='$core_5yrsExpinFltOps'";
<?php
//Just copy & paste below code & enjoyed
//suppose that your skill_test array is look like below
$skill_test = array (0 => 'core_UniversityEngScience', 1 => 'core_CommercialPilot' ,2 => 'core_ATC' ,3=> 'core_5yrsExpinAerodromesOps' , 4 => 'core_5yrsExpinFltOps' );
$var = 'yes';
$condtion = [];
foreach($skill_test as $row){
if($row == 'core_5yrsExpinFltOps'){
$var = 'no';
}
$condtion[]= " `$row` = '$var'";
}
if(!empty($condtion)){
$condtion = implode(' AND ', $condtion);
$sql = "Select * from tbl where $condtion";
die($sql);
}
?>
I'm trying to save with foreach
here is what i get from my form
Array
(
[mulai] => 2016-08-28
[akhir] => 2016-08-31
[keterangan] => remarks
[nip] => Array
(
[0] => 1004384
[1] => 1602744
[2] => 1501039
)
)
and then here is my saving query.
$jumlahrange = $this->db->query("SELECT DATEDIFF(day,'".$mulai."','".$akhir."') AS diff")->row();
$totaldata = count($nip);
$skrg = $this->db->query("SELECT GETDATE() tgl")->row();
for($x = 0;$x<=$totaldata;$x++)
{
for($y=0;$y<$jumlahrange->diff;$y++){
$this->db->query("INSERT INTO attendance
(Nip,AttendanceDate,InTime,OutTime,AttendanceCode,RosterCode,LocationCode,Remarks,CreatedDate,CreatedBy,ModifiedDate,ModifiedBy)
values(
'".$nip[$x]."',DATEADD(DAY,".$y.",'".$mulai."'),'','','P3','','','".$keterangan."','".$skrg->tgl."','$niplogin','','')
");
}
}
i have no problem with my save but i have empty field like this in my table. In row 10,11,12 . That row should not exist right?.
I using SqlServer 2008 and Codeigniter . I know i can use insert_batch, but i want use this way.
in your line for($x = 0;$x<=$totaldata;$x++) i'm pretty sure you wanted to write < instead of <=
To overcome these kind of issues you can use foreach loop instead
foreach($resourcedata as $value){
//your code goes here and you will get all array elements sequentially in **$value** variable
}
This one is right at your fingertips. $nip[$x] is null. Error log or dump and die on the first loop $nip[$x] and see what it returns. If it is in fact not null, then it might be a data type problem (string vs int).
I am trying to search one word in my whole table.
So if you search Eminem, you have to get everything with the word Eminem.
I search
<?php
$sql="SELECT * FROM album WHERE albumartiest like '$zoek'";
$resultaatcolumn = Yii::app()->db->CreateCommand($sql)->queryAll();
if($resultaatcolumn != null){
$zoekresultaat[] = $resultaatcolumn;}
$sql="select * from album where albumnaam like '%$zoek%'";
$resultaatcolumn = Yii::app()->db->CreateCommand($sql)->queryAll();
if($resultaatcolumn != null){
$zoekresultaat[] = $resultaatcolumn;}
$sql="select * from album where albumartiest like '%$zoek%'";
$resultaatcolumn = Yii::app()->db->CreateCommand($sql)->queryAll();
if($resultaatcolumn != null){
$zoekresultaat[] = $resultaatcolumn;}
$sql="select * from album where albumgenre like '%$zoek%'";
$resultaatcolumn = Yii::app()->db->CreateCommand($sql)->queryAll();
if($resultaatcolumn != null){
$zoekresultaat[] = $resultaatcolumn;}
$sql="select * from album where albumafspeelijst like '%$zoek%'";
$resultaatcolumn = Yii::app()->db->CreateCommand($sql)->queryAll();
if($resultaatcolumn != null){
$zoekresultaat[] = $resultaatcolumn;}
It works, but not exactly how I want it.
The result is this:
Array ( [0] => Array ( [0] => Array ( [albumcode] => 45 [albumnaam] => recovery [albumafspeelijst] => ["Cold Wind Blows","Talkin' 2 Myself","On Fire","Won't Back Down","W.T.P.","Going Through Changes","Not Afraid","Seduction","No Love","Space Bound","Cinderella Man","To Life","So Bad","Almost Famous","Love The Way You Lie","You're Never Over",""] [albumartiest] => Eminem [albumgenre] => hip-hop [albumimage] => images\eminemrecovery.png [albumprijs] => 20 ) ) [1] => Array ( [0] => Array ( [albumcode] => 45 [albumnaam] => recovery [albumafspeelijst] => ["Cold Wind Blows","Talkin' 2 Myself","On Fire","Won't Back Down","W.T.P.","Going Through Changes","Not Afraid","Seduction","No Love","Space Bound","Cinderella Man","To Life","So Bad","Almost Famous","Love The Way You Lie","You're Never Over",""] [albumartiest] => Eminem [albumgenre] => hip-hop [albumimage] => images\eminemrecovery.png [albumprijs] => 20 ) ) )
that's okay, but what I want is take out variable's and use it.
is there a way that I can get variable's out of the array and use it?
If you guys want more information about my code please ask!
Try using this
Yii::app()->db->CreateCommand($sql)->setFetchMode(PDO::FETCH_OBJ)->queryAll()
This will give you an array of objects with column name as the properties.
Eg:-
foreach($result as $row)
{
echo $row->albumcode;
}
If you want to access the result set like an object you can use the native PHP class ArrayObject and provide the flag to indicate that.
$album = new ArrayObject($result, ArrayObject::ARRAY_AS_PROPS);
You can now access the results like the following:
$code = $album->albumcode;
$name = $album->albumnaam;
Hope this can guide you, happy coding!
uhhh just do
foreach($zoekresultaat as $key => $value) {
//do what I want with each seperate returened result. The array key is in $key and the result array is in $value
echo $value['albumcode'] . ' = '. $value['albumnaam'];
}
aka, basic php
And please for the security of your app, learn how to do prepared statements in yii
The way your query is now I could wipe your entire database
I am trying to create an array from an mysql query,
It gets around 300 values from the database yet only the first value is stored in the array. when I echo the array it says: Array ( [0] => 0.99 ). What I'm trying to archieve is
Array ( [0] => 0.99 )
Array ( [1] => 0.25 )
etc.
$activering = mysql_query("SELECT tarieven.id, bundels.bundel_id, betaalmethodes.bet_id , bundels.psp_id, bundels.aanmeldkosten, bundels.maandelijkse_kosten, bundels.transactiekosten, bundels.batchkosten, psp.psp_naam, tarieven.percentage, tarieven.prijs, bundels.actief
FROM tarieven
INNER JOIN bundels
ON tarieven.bundel_id = bundels.bundel_id
INNER JOIN betaalmethodes
ON tarieven.bet_id = betaalmethodes.bet_id
INNER JOIN psp
ON bundels.psp_id = psp.psp_id");
if($activering === FALSE) { die(mysql_error()); } // to do better error handling
if ($result = mysql_fetch_array($activering)) {
$prijs = array($result['prijs']); }
It's probably something really easy but I just don't see it..
Try
while ($result = mysql_fetch_array($activering)) {
$prijs[] = array($result['prijs']);
}
your over writing the value(array) in hte loop so you only get the last one:
$prijs[] =$result['prijs']; }
Please, see Cha's answer where we are pretty close the final solution. We are debugging the code with these data
database in PostgreSQL
test sql-queries
--
Problem related to the Unsolved problem in the code
How can you refer to the php -element in the following array?
I have the following data
Array
(
[1] => Array
(
[tag] => Array
(
[0] => php
[1] => scripts
)
)
[2] => Array
(
[tag] => Array
(
[0] => ssh
[1] => network
)
)
)
where the arrays stand for tags_and_id, question_id and tag respectively.
In other words, the variable $tags_and_id has the column question_id and that still has a subcolumn tag and that still each single tag.
I would like know how you can refer to the tag php.
I run unsuccessfully getting nothing as an output
echo $tags_and_id[1]['tag'][0];
If you want to add more information about each question, you can simply add to $end_array[1].
This is the array my first foreach statement creates:
// The end result turns out to be something like this:
array(
1 => array(
'tags' => array(
0 => "php",
1 => "sql"),
)
);
<?php
$dbconn = pg_connect("host=localhost port=5432 dbname=noa user=noa password=123");
if( empty($_GET) ) {
// to get titles and question_ids
$result_titles_tags = pg_prepare( $dbconn, "query777",
"SELECT question_id, title
FROM questions
WHERE question_id IN
(
SELECT question_id
FROM questions
ORDER BY was_sent_at_time
DESC LIMIT 50
)
ORDER BY was_sent_at_time
DESC LIMIT 50;"
);
$result_titles = pg_execute( $dbconn, "query777", array());
// TAGS
$result_tags = pg_prepare( $dbconn, "query9",
"SELECT question_id, tag
FROM tags
WHERE question_id IN
( SELECT question_id
FROM questions
ORDER BY was_sent_at_time
DESC LIMIT 50
);"
);
$result_tags = pg_execute( $dbconn, "query9", array());
and the code in the question initially
// Go through each Tag
while( $tags_and_Qid = pg_fetch_array( $result_tags )) {
// Add the Tag to an array of tags for that question
$end_array [ $tags_and_Qid['question_id'] ] ['tag'] [] = $tags_and_Qid['tag'];
}
// First compile the Data
// Go through each question
while( $titles_and_Qid = pg_fetch_array( $result_titles ) ) {
echo ("<div class='question_summary'>"
. $titles_and_Qid['title']
// Problem here!
// How can you print the titles such that
// they are assigned to each tag -set?
);
$i = 0;
// Then Loop Through each question
foreach( $end_array as $tags_and_Qid['question_id'] => $tags_and_Qid['tag'] )
{
echo ("\n\nITERATION NUMBER IS " . $i); // The code is buggy here
// For instance, we get 9 iterations for 3 questions
// Create the starting HTML
echo ("<div class='tags'>");
// Go through each tag
// not sure about this
foreach( $end_array[$tags_and_Qid['question_id']] ['tag'] as $tag )
{
echo ( "<a class='post_tag' href='?tag="
. $tag
. "'>"
. $tag
. "</a>"
);
}
// end the html
echo '</div>';
$i++;
}
echo ("</div>");
}
// to end the list of questions
echo ("</div>"
);
}
?>
If print_r is failing, then something is wrong before that. Your data is probably not being structured in the way you think it is being structured.
And can I just recommend that if you only have the tag and the question name, you just store as a single level array that looks like the following:
array(
'php' => '7',
'sql' => '7',
'python' => '3'
)
If you have other things you're going to store then yeah, you'll have to do what you're doing. In that case, if you can't access the array with the keys in brackets, then your keys are probably not what you think they are, or there is something wrong with your code somewhere.
I looked at your code, and why are you accessing query results like $row[0], instead of $row['question_id'] ?
Also, you can't print_r($result_tags) , because data from a query is not actually stored by PHP, it is only referenced. therefore you have to use a while loop to go through it, as the script will call one row of results at a time.
You say: foreach( $result_tags as $question_id => $data ) This doesn't make sense, because there is no value for $result_tags except for a reference to the query that can be used to call one row of results at a time. Instead you want to do:
while( $row2 = pg_fetch_array( $result_tags )) {
$question_id = $row2['questions_question_id'];
$data = $row2['data'];
$end_array[$question_id]['tags'][] = $data;
// you can't have your $data['tag'] as that refers to the
// value of an array that doesn't exist
}