I have situation . I want to insert one array element to another array element but could not find the exact method.
This is my function
public function get_applicants($sort_array = array('apply_id DESC'))
{
global $wpdb;
$sql = 'SELECT * FROM ' . $this->tableac . " ORDER BY " . implode(',', $sort_array);
//$sql = 'SELECT c. * , p. * FROM wp_apply c, wp_apply_files p WHERE c.apply_id = p.apply_id';
$educations = $wpdb->get_results($sql);
$getid=array();
foreach($educations as $education){
//print_r($education);
$sqlfile = 'SELECT * FROM wp_apply_files WHERE apply_id = '.$education->apply_id;
$getalls = $wpdb->get_results($sqlfile);
$allvalues="";
foreach($getalls as $getall){
$allvalues= $getall->uploaded_file.", ";
$getid[]=$getall->uploaded_file;
}
$allvaluesnew=rtrim($allvalues,", ");
// echo "<br>";
// Here I want to insert getid into educations array
}
echo "<pre>";print_r($educations);
die();
//return array($educations,$getid);
}
print_r result show this.
Array
(
[0] => stdClass Object
(
[apply_id] => 44
[choose_position] => HR Manager
[title] => testr
[first_name] => waqas
[last_name] => aamer
[current_job] => developer
print_r get id show like this.
Array
(
[0] => a75d138911c55df639fdd09fade511151-23.pdf
[1] => newone3.pdf
[2] => a75d138911c55df639fdd09fade511151-22.pdf
[3] => newone2.pdf
[4] => a75d138911c55df639fdd09fade511151 (2).pdf
[5] => newone.pdf
)
I want to insert these these elements iteration wise. When in the educations first iteration comes than it should insert all the elements at one index of second array separated by comma.
If I understand your question correctly then following might help.
It will insert comma separated values from $getid into new key called "getid" in $educations array.
public function get_applicants($sort_array = array('apply_id DESC'))
{
global $wpdb;
$sql = 'SELECT * FROM ' . $this->tableac . " ORDER BY " . implode(',', $sort_array);
//$sql = 'SELECT c. * , p. * FROM wp_apply c, wp_apply_files p WHERE c.apply_id = p.apply_id';
$educations = $wpdb->get_results($sql);
$getid=array();
foreach($educations as $key => $education){
//print_r($education);
$sqlfile = 'SELECT * FROM wp_apply_files WHERE apply_id = '.$education->apply_id;
$getalls = $wpdb->get_results($sqlfile);
foreach($getalls as $getall){
$getid[]=$getall->uploaded_file;
}
// echo "<br>";
// Here I want to insert getid into educations array
$educations[$key]["getid"] = implode(",", $getid);
}
echo "<pre>";print_r($educations);
die();
//return array($educations,$getid);
}
Hope this helps and this is what you want
Related
I have a list of serialized data that I unserialize and store into an array.
$employee_data = unserialize($entry, '63');
Which results in an expected output:
Array ( [0] =>
Array ( [First] => Joe
[Last] => Test
[Birth Date] => 01/01/2011
)
[1] =>
Array ( [First] => Mike
[Last] => Miller
[Birth Date] => 01/01/1980
)
)
Ive been trying, unsuccessfully, to insert these records into a table in MySQL using foreach() or something like:
$employee_array = array();
$k = 1;
for($n=0; $n<count($employee_data); $n++ ){
$employee_array['employee_first_name'.$k] = $employee_data[$n]['First'];
$employee_array['employee_last_name'.$k] = $employee_data[$n]['Last'];
$employee_array['employee_birthdate'.$k] = $employee_data[$n]['Birth Date'];
$SQL = "INSERT INTO employee_test (
employee_first_name,
employee_last_name,
employee_birthdate
)
VALUES (
'$employee_first_name.$k',
'$employee_last_name.$k',
'$employee_birthdate.$k'
)"
$k++;
};
Each employee in the array needs to be entered into a new row in the table, however the number of employees will vary from 1 to 10+
We've tried
foreach($employee_array as $key => $value)
with the same results.
The actual results we're hoping for is the SQL Statement to be:
insert into employee_test(
employee_first_name,
employee_last_name,
employee_birthdate)
VALUES(
'Joe',
'Test',
'01/01/2011');
insert into employee_test(
employee_first_name,
employee_last_name,
employee_birthdate)
VALUES(
'Mike',
'Miller',
'01/01/1980');
Keep in mind that your sql statement is not escaped. For example, a name with an apostrophe like "0'neil" will break your sql. I would also familiarise yourself with php's foreach: https://www.php.net/manual/en/control-structures.foreach.php.
I'm not sure exactly what you're trying to accomplish by adding the index to the name and sql value, but I would do something like this:
foreach($employee_data as $key => $value){
// $employee_array is not necessary
$employee_array[$key]['employee_first_name'] = $value['First'];
$employee_array[$key]['employee_last_name'] = $value['Last'];
$employee_array[$key]['employee_birthdate'] = $value['Birth Date'];
// Needs escaping
$SQL = "INSERT INTO employee_test (
employee_first_name,
employee_last_name,
employee_birthdate
)
VALUES (
'{$value['First']}',
'{$value['Last']}',
'{$value['Birth Date']}'
)";
echo $SQL;
};
The first implementation wont work as your calling a variable rather than the key in your array.
'$employee_first_name.$k',
Should be
$employee_array['employee_first_name'.$k]
You are also creating the SQL statement every iteration of the for loop, so in this implementation only the last employee will save.
Also I don't see the reasoning in doing it that way anyway you may as well just use the employee_data array and the $k variable can also be made redundant.
$SQL = "";
for($n=0; $n<count($employee_data); $n++ ){
$SQL .= "INSERT INTO employee_test (
employee_first_name,
employee_last_name,
employee_birthdate
) VALUES (";
$SQL .= "'".$employee_data[$n]['First']."',";
$SQL .= "'".$employee_data[$n]['Last']."',";
$SQL .= "'".$employee_data[$n]['Birth Date']."'";
$SQL .= ");";
};
Ive not tested but it should give you an idea.
You will also have issues with the date formatted that way, Your database would likely require the date in yyyy/mm/dd format
Finally I would not recommend inserting values like this, look at the PDO library for placeholders.
I think I understand what you're trying to do here. You are using the = operator, effectively setting $SQL to a new value each time your loop iterates. If you adapt your code, you will be able to append to $SQL variable each time.
//I used this array for testing. Comment this out
$employee_data = array(
0 => array(
"first" => "test",
"last" => "tester",
"birth date" => "01/01/1970"
),
1 => array(
"first" => "bob",
"last" => "david",
"birth date" => "02/02/1972"
),
);
//Start SQL as a blank string
$SQL = "";
//Do your iteration
foreach( $employee_data as $key=>$value ){
$first = $value['first'];
$last = $value['last'];
$birthDate = $value['birth date'];
//append this query to the $SQL variable. Note I use `.=` instead of `=`
$SQL .= "INSERT INTO employee_test(
`employee_first_name`,
`employee_last_name`,
`employee_birthdate`)
VALUES(
'$first',
'$last',
'$birthDate'
);";
}
//output the query
echo $SQL;
There are much easier ways of doing this though. Look into prepared statements :)
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]);
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 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'm trying to convert an array (key/value) to be an SQL statement.
I'm using MYSQLi like such:
if(!$result = $mysqli->query($sql)){throw new Exception("SQL Failed ".__file__." on line ".__line__.":\n".$sql);}
I have an array like such:
Array
(
[database] => Array
(
[cms_network] => Array
(
[network_id] => 61
[network_name] =>
[network_server_mac_address] => 00:1b:eb:21:38:f4
[network_description] => network
[network_thermostat_reporting_rate] => 5
[network_server_reporting_rate] => 5
[network_data_poll_rate] => 5
[network_created_by] => 38
[network_modified_by] => 1
[network_network_id] => 8012
[network_language] => en
[network_hotel_id] => 68
[network_channel] => 0
[network_deleted] => 0
[network_reported_network_id] => 8012
[network_rooms] => 4
)
)
)
How can I convert [cms_network] to look like this:
$sql = "UPDATE cms_network set network_id='61', network_name='',
network_server_mac_address = '00:1b:eb:21:38:f4', .... WHERE network_id='61'"
I'm more interested in knowing how to concatenate the key=>value pair of the array to be key='value' in my select statement.
Thanks for the help!
If you use the VALUES syntax, you could do it in one fell swoop.
mysql_query("
UPDATE MyTable
( . implode(',', array_keys($array['database']['cms_network'])) . ")
VALUES ('" . implode("','", $array['database']['cms_network']) . "')
");
This, of course, assumes that the data is already escaped.
EDIT: Tidier version that's easier to read and maintain:
$fields = implode(',', array_keys($array['database']['cms_network']));
$values = implode("','", $array['database']['cms_network']);
mysql_query("UPDATE MyTable ($fields) VALUES ('$values')");
I suggest you populate an array with formatted key/value pairs, then implode them at the end. This is an easy way to add the required , between each key/value:
$fields = array();
foreach($array['database']['cms_network'] as $key => $value) {
// add formatted key/value pair to fields array
// e.g. format: network_id = '26'
$fields[] = $key . " = '" . $value . "'";
}
$fields = implode(', ', $fields);
// build your query
$query = "UPDATE cms_network SET " . $fields . " WHERE network_id = " . $array['database']['cms_network']['network_id'] . " LIMIT 1";
// process it...
This will (SQL wise) be inserting every value as a string, which is obviously incorrect with integer columns etc. It should still work anyway, but if not you'll need to put in a conditional statement for whether to wrap the value in quotes or not, like this:
foreach(...) {
if(is_numeric($value))
$fields[] = $key . ' = ' . $value;
else
$fields[] = $key . " = '$value'";
}
Although this should probably relate to your database column type rather than the PHP variable type. Up to you, they should work fine with quotes around integers.
This should work.
$update_query = "UPDATE `cms_network` SET ";
$count = 0;
foreach($array['database']['cms_network'] as $key => $value) {
if ($count != 0) {
$update_query = $update_query.",".$key."=".$value;
} else {
$update_query = $update_query.$key."=".$value;
}
$count++;
}
$update_query = $update_query." WHERE ".cms_network."=".$array['database']['cms_network'];
mysql_query($update_query);