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);
}
?>
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 add an <hr> tag between lines when a new name is encountered.
$conn = new mysqli("localhost", "root", "", "test");
$rs = $conn->query("SELECT * FROM usuarios");
$info = [];
$i = 0;
while($rows = $rs->fetch_array()) {
$info[$i]["pass"] = $rows["pass"];
$info[$i]["name"] = $rows["name_real"];
$i++;
}
// I want to print a line just after the last duplicated value
for($i = 0; $i < count($info) - 1; $i++) {
if($info[$i]["name"] !== $info[$i +1]["name"] && // some duplicate condition) {
$info[$i]["line"] = "<hr>";
};
}
This is the structure of my info array build from the resultset.
Array
(
[0] => Array
(
[pass] => 12
[name] => Martin
)
[1] => Array
(
[pass] => 20
[name] => Martin
)
[2] => Array
(
[pass] => 2
[name] => Martin
)
[3] => Array
(
[pass] => 2
[name] => Alberto
)
)
My desired result would be something like:
<p>Martin<p>
<p>Martin<p>
<p>Martin<p>
<hr>
<p>Alberto<p>
If you don't care what the duplicate names are or how many duplicates exist, and you just want to see whether or not there are any, it looks like it could be simpler code than some of the possible duplicate answers.
Get the names
$names = array_column($array, 'name');
Then check if the full list of names is equal to the unique list.
$has_duplicates = $names != array_unique($names);
Disclaimer: This answer looks odd now. It was provided for Revision 1 of the question. I seem to have misunderstood the question somewhat, and then Revision 2 transformed it to the extent that this answer no longer applies at all. Still, I think it's a useful way to do the thing that it seemed was trying to be done at first.
This solution would be handy:
$result = array();
$names = array_count_values(array_column($source, 'name'));
foreach($names as $key=>$val) {
$result[$key] = ($val == 1 ? false : true);
}
This can be achieved with just one loop. First, use your mysqli query to order the resultset by name_real. (If you are only going to use name_real, you can change the SELECT clause to reflect this. I have shown this in the commented query.) Then write a condition that checks for a new/unique name_real -- if so, echo <hr>.
Code: (Demo)
//$rs = $conn->query("SELECT `name_real` FROM usuarios ORDER BY `name_real`;");
$rs=[
['pass'=>2,'name_real'=>'Alberto'],
['pass'=>12,'name_real'=>'Martin'],
['pass'=>20,'name_real'=>'Martin'],
['pass'=>2,'name_real'=>'Martin']
];
$prev=NULL;
//while($rows = $rs->fetch_array()) {
foreach($rs as $rows){
if($prev && $rows['name_real']!=$prev){ // if not first iteration, and new name_real
echo "<hr>";
}
echo "<p>{$rows['name_real']}</p>";
$prev=$rows['name_real']; // preserve this value for next iteration's check
}
Output:
<p>Alberto</p>
<hr>
<p>Martin</p>
<p>Martin</p>
<p>Martin</p>
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
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
Hey guys i want to use two arrays in on mysql UPDATE query. So here is what i have:
For example:
$ergebnis:
Array ( [0] => 100 [1] => 200 [2] => 15 )
$Index:
Array ( [0] => 3 [1] => 8 [2] => 11 )
And this is what i tried:
UPDATE `lm_Artikel`
SET Bestand='".$ergebnis."'
WHERE `Index` = '".$Index."'
This query seems not to work. I don't know why i enabled php error reporting and there are no errors and when i run the query it doesn't change anything in my database. Can anyone see what i did wrong?
You need to do it for each element of your arrays, hence, you can use the foreach() function:
foreach($ergebnis as $key => $value){
$sql = "UPDATE lm_Artikel SET Bestand='".$value."' WHERE `Index` = '".$Index[$key]."'";
mysqli_query($sql);
}
P.S. There could well be a pure-sql alternative but I'm not too SQL-hot, so I'll leave it to someone who has more expertise.
Also, please note that it may be easier for you to set the index as the array keys:
$ergebnis = Array(3=>100, 8=>200, 11=>15);
And then the foreach() would look a little better:
foreach($ergebnis as $key => $value){
$sql = "UPDATE lm_Artikel SET Bestand='".$value."' WHERE `Index` = '".$key."'";
mysqli_query($sql);
}
Fellow,
it looks like that your database field is an int value so you can try doing it value by value, like this:
foreach( $Index as $key => $i ) :
$query = "UPDATE lm_Artikel SET Bestand=".$ergebnis[$key]." WHERE Index = " . $i;
mysqli_query($query);
endforeach;
Try it.
You are susceptible to SQL injections
You cannot use arrays in queries. A query is a string, arrays are not.
You either need to use a loop or use a CASE statement:
UPDATE `lm_Artikel`
SET `Bestandteil` = CASE `Index`
WHEN <insert id> THEN <insert value>
WHEN <insert other id> THEN <insert other value>
<etc>
END
$data_db = array( '3' => 100,
'8' => 200,
'11' => 15);
foreach($data_db as $key=>$value) {
$q = 'UPDATE lm_Artikel SET Bestand=' . $value . ' WHERE `Index` = ' . $key;
mysqli_query($sql);
}
Assuming these are value pairs, i.e. $ergebnis[0] is for $Index[0] and so forth.
foreach ($ergebnis as $key => $value) {
$sql = 'UPDATE lm_Artikel SET Bestand=' . (int)$value . ' WHERE `Index` = ' . (int)$Index[$key];
// execute query...
}
A few notes:
You are open to SQL Injection. I used (int) as a quick patch.
I would encourage you to look into Prepared Statements.
You should avoid naming your columns SQL keywords, e.g. Index.