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 :)
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);
}
?>
Im using this DOMXpath query to retrieve some columns from another page.
$html = file_get_contents("http://localhost:8888/stockPrices.php");
libxml_use_internal_errors(true);
$doc = new \DOMDocument();
if($doc->loadHTML($html))
{
$result = new \DOMDocument();
$result->formatOutput = true;
$table = $result->appendChild($result->createElement("table"));
$thead = $table->appendChild($result->createElement("thead"));
$tbody = $table->appendChild($result->createElement("tbody"));
$table->setAttribute('class', 'table table-hover');
$xpath = new \DOMXPath($doc);
$newRow = $thead->appendChild($result->createElement("tr"));
foreach($xpath->query("//table[#id='kurstabell']/thead/tr/th[position()=2 or position()=3 or position()=8 or position()=9 or position()=10]") as $header)
{
$newRow->appendChild($result->createElement("th", trim($header->nodeValue)));
}
foreach($xpath->query("//table[#id='kurstabell']/tbody/tr") as $row)
{
$newRow = $tbody->appendChild($result->createElement("tr"));
foreach($xpath->query("./td[position()=2 or position()=3 or position()=8 or position()=9 or position()=10]", $row) as $cell)
{
$newRow->appendChild($result->createElement("td", trim(htmlentities($cell->nodeValue))));
}
}
echo $result->saveXML($result->documentElement);
}
This generates four columns, aktier, senaste, högst, lägst and omsatt. But i dont know how to insert this to a MySQL table. Im thinking to first generate a array of the result, like:
Array
(
[1] => stdClass Object
(
[aktie] => AAK AB
[senaste] => 634,50
[högst] => 638,50
[lägst] => 622,50
[omsatt] => 32 094 048
)
[2] => stdClass Object
(
[aktie] => ABB Ltd
[senaste] => 162,80
[högst] => 163,30
[lägst] => 161,90
[omsatt] => 167 481 268
)
(you get the hang of it..)
)
According to this image:
And then loop the array into the table. Something like this?
$sql = "INSERT INTO stock_list (`aktie`, `senaste`, `högst`, `lägst`, `omsatt`, `timestamp`) VALUES
(:aktie, :senaste, :högst, :lägst, :omsatt)";
$query = $database->prepare($sql);
foreach($data as $stock){
$query->execute(array(':aktie' => $stock->stock,
':senaste' => $stock->prevclose,
':högst' => $stock->high,
':lägst' => $stock->low,
':omsatt' => $stock->volume
));
}
My question:
How do i populate the array with data?
How do i loop the result in a mysql query?
Don't know if this is a work around. But it is currently doing what I'm asking for.
// build query...
$sql = "INSERT INTO stocks";
// columns to insert into...
$sql .="(`name`, `closing`, `high`, `low`, `turn`, `timestamp`)";
// implode values of $array...
// notice array_chunk, this functions splits a big array into multi.
$str = NULL;
foreach (array_chunk($a, 5) as $row) {
$str .= '("'. implode('","',$row).'",NOW()),';
}
// Remove last ',' (comma) from string
// We added commas in the previous step
$str = rtrim($str,',');
$sql .= 'VALUES '. $str ;
// execute query...
$app = new Connection();
$query = $app->getConnection()->prepare($sql);
$query->execute();
if ($query->rowCount() <= 0) {
echo "Something went wrong.";
return false;
}
return true;
My guess is that what you really want is something along the lines of:
$query = 'INSERT INTO stock_list
(`aktie`, `senaste`, `högst`, `lägst`, `omsatt`, `timestamp`)
VALUES
(:aktie, :senaste, :högst, :lägst, :omsatt, NOW())';
$stmt = $app->getConnection()->prepare($query);
foreach ($data as $stock) {
$stmt->execute(
[
':aktie' => $stock->aktie,
':senaste' => $stock->senaste,
':högst' => $stock->{'högst'},
':lägst' => $stock->{'lägst'},
':omsatt' => $stock->omsatt,
]
);
$stmt->closeCursor();//might be required depending on DB driver, not for MySQL, though
}
Note that I call NOW() in the query string, and I don't bind that SQL function call to the parameters I execute the prepared statement with. All in all though, a timestamp field is best set by the DB itself (with a DEFAULT CURRENT_TIMESTAMP in the field definition). Then you can just leave the timestamp field out of your INSERT query, and it'll be set correctly for you.
I've also changed the way you're using the objects stock. From the var_dump I can see the properties aren't called stock, high, low and all that. The problem is, some of these property names (lägst for example) are a bit dodgy. You'll probably have to access those using a string, which can be done, like I did, by writing $objVar->{'property name as string'}.
If I were you, though, I'd look into ways of changing what $data actually looks like, and change the property names if at all possible.
Hello i have a JSon array like this
Array
(
[NTAy] => ALFA ROMEO
[NTA0] => AUDI
[NTEx] => BMW
[NjAy] => CHEVROLET
[NTEz] => CHRYSLER
[NTE0] => CITROËN
[NjAz] => DACIA
[NjQ5] => DAEWOO
[NTE3] => DAIHATSU
)
and I have to insert it in a database row by row, I used
foreach ($mata as $marca_id => $marca_name){
$line = $line. "','" . $marca_id . "','". $marca_name . "','". $marca_name;
}
$line = substr($line, 0, strlen($line)-1);
$values[$i] = $line;
++$i;
$values =implode ( $values);
echo $values;
echo "<br />";
but at the mysql insert
$data = mysql_query(" INSERT INTO jos_virtuemart_categories_ro_ro (virtuemart_category_id, category_name, slug)
VALUES " .$values)
I get an error and can't get it to work. Can someone help me please?
foreach ($mata as $marca_id => $marca_name) {
$id = intval($marca_id);
$name = mysql_real_escape_string($marca_name);
$values = "$id, '$name', '$name'";
mysql_query("INSERT INTO jos_virtuemart_categories_ro_ro (virtuemart_category_id, category_name, slug) VALUES ($values)");
}
Why not use prepared statements? Especially if you're taking user generated data and entering it into your database.
That and it looks like you're final SQL query will look like this
INSERT INTO jos_virtuemart_categories_ro_ro (virtuemart_category_id, category_name, slug)
VALUES 'NTAy','ALFA ROMEO','ALFA ROMEO','NTA0','AUDI','AUDI' etc
You would have to break this up into multiple queries
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.
I have the array $student[]
<?php
$student['id'] = "10402";
$student['hnumber'] = "H030502";
$student['name'] = "Larry Wayne";
print_r($student);
?>
It prints out:
Array ( [id] => 10402 [hnumber] => H030502 [name] => Larry Wayne )
What I want to accomplish is storing values into an array, that will then be inserted into a database table.
So the insert statement would be:
$q = "insert into table (id, hnumber, name) VALUES ('10401', 'H030502', 'Larry Wayne')";
I want to use an array to store all the values into it, labeling each value by their table field name, because it will be about 25 fields I will be inserting data into.
If there is a better way of accomplishing that, I am all ears.
Thanks in advance.
Assuming you are building an array of students from another source, how about something like this?
// data from an external source
$students = array(
// student 1
array(
123,
'h123',
'John Smith',
),
// student 2
array(
456,
'h456',
'Jane Smith',
),
// ... and so on
);
$values = array();
foreach ( $students as $student )
{
// #todo, make sure to sanitize values!!!
$values[] = sprintf('(%s)', implode(', ', $student));
}
// build query
$query = 'INSERT INTO `table` (`id`, `hnumber`, `name`) VALUES '.implode(', ', $values);
Please note, above code is "pseudo" or an idea if you want. Make sure to sanitize the values :)
EDIT: One more thing. Above code is good if you want a simple fix, preferably for some sort of simple data import. Better way is to create a class Student handling all this logic.
I wanted to simply comment on David's example as it's pretty much the same thing I was going to suggest, but I can't add code to comments, unfortunately. One thing David forgot from your original question was that you wanted to use the table fields as part of your array - in this example, as the key fields. In the foreach, you can split the array in to key/value pairs, and then use them later on in your code itself.
<?php
$student['id'] = "10402";
$student['hnumber'] = "H030502";
$student['name'] = "Larry Wayne";
$queryFields = array();
$queryValues = array();
$queryString = '';
foreach($student as $key => $value){
$queryFields[] = '`'.$key.'`';
$queryValues[] = $value;
}
$queryString = 'INSERT INTO `table` ('.implode(',', $queryFields).') VALUES ('.implode(',', $queryValues).')';
//run_query($queryString)
?>
Since I'm not 100% familiar with CodeIgniter, it's very possible that there might be a way to map arrays and/or objects to some sort of ActiveRecord implementation. However, since you're just looking for a way to generate a query string itself, this would do the trick.