I am trying to save array value to variable so that I can insert that data/value into mysql using PHP for that I am using a pain taking long code so I want simple method to do it without writing it again and again.
Array shows data like this
Array
(
[0] => Array
(
[0] => a><p class="wp-caption-text">Pendant Heart Images</p></div>
[1] => a><p class="wp-caption-text">Pendant Heart Photos</p></div>
[2] => a><p class="wp-caption-text">Pendant Heart Photos</p></div>
)
[1] => Array
(
[0] => Pendant Heart Images
[1] => Pendant Heart Photos
[2] => Pendant Heart Photos
)
)
Code which I am using to save array value
$a = $g_img[1][0];
$b = $g_img[1][1];
$c = $g_img[1][2];
$a1 = $title[1][0];
$b1 = $title[1][1];
$c1 = $title[1][2];
Mysql query to save data
mysqli_query($con,"INSERT INTO data (Link, Title) VALUES ('$a','$a1')");
mysqli_query($con,"INSERT INTO data (Link, Title) VALUES ('$b','$b1')");
mysqli_query($con,"INSERT INTO data (Link, Title) VALUES ('$c','$c1')");
So If array data increases I have to assign each array value to different variable which is huge process I know there would be a shortcut
Plz Help
The query will not work because to start with, the number of field name are not equal to the number of values.
You could have passed your query in the following way:
for ($counter = 0; $counter <=2; $counter++){
$query = "INSERT INTO data (Link, Title) VALUES ('{$g_img[1][$counter]}', '{$title[1][$counter]}')";
$result = mysqli_query($con, $query);
}
Here I have assumed that $g_img and $title correspond to the array of links and titles respectively and the data connection is $con.
Related
I am developing an administration panel for my site locally. I would need to insert multiple rows with a single INSERT INTO query.
Initially I transform the string saved with commas into an array and then I try with a foreach loop to insert but it doesn't work ...
$aa = explode(',', $data['recipe_ingredient']);
<!-- Result Array ( [0] => one element [1] => second element [2] => third element ) -->
foreach($aa as $entry) {
$this->db->query('INSERT INTO recipes_ingredient (recipe_id, recipe_ingredient_name)
VALUES (:last_id, :name)'); <-- :name contain "n" result
$this->db->bind(':last_id', $this->db->lastId());
$this->db->bind(':name', $entry);
if($this->db->execute()) {
return true;
} else {
return false;
}
}
Anyone have any suggestions?
Thank you
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 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 have three arrays that look like this:
ingredientQTY is the first input box in each row, measurements is the select/dropdown in each row, and ingredientsNAME is the last input box in each row. As you can see, there can be infinite numbers of ingredientQTY's, ingredientNAME's, and measurements.
When I send them to my php script, the data is in arrays like:
IngredientQTY
(
[0] => 5 //The first row
[1] => 5 //The next rows value
)
Measurements
(
[0] => Bunch //The first row
[1] => Bunch //The next rows value
)
IngredientName
(
[0] => 5 //The first row
[1] => 5 //The next rows value
)
I'm trying to upload them to a table called ingredients that has 3 columns: ingredientNAME, ingredientQTY, and measurements.
In my php script, I'm combining them into a multidimensional array, which is assigned to $ingredientsROW:
foreach($_POST as $key => $value) {
$value = $this->input->post($key);
$ingredientQTY = $this->input->post('ingredientQTY');
$measurements = $this->input->post('measurements');
$ingredientNAME = $this->input->post('ingredientNAME');
$ingredientsROW[] = array($ingredientQTY, $measurements, $ingredientNAME);
break;
}
My question is: How can I get group all the first row of form elements (which means the first ingredientQTY, the first measurements dropdown and the first ingredientNAME and insert them into a row?
The only way I could think of is to have one insert where I insert ingredientQTY, then look up the id of the row I just inserted and use two mysql updates to enter for the same row, but I'm pretty sure there is more efficient ways of going about this.
Would something like this work?
foreach($_POST['IngredientQTY'] as $index=>$qty)
mysql_query("insert into ingredients ".
"set IngredientQTY='".addslashes($qty)."'".
", measurements ='".addslashes($_POST['measurements'][$index])."'".
", ingredientNAME ='".addslashes($_POST['ingredientNAME'][$index])."');
Iterate through the data and create an array like this:
for ($i = 0, $count = count($ingredientQTY); $i < $count; $i++) {
$rows[] = array(
'QTY' => $ingredientQTY[$i],
'measurement' => $measurements[$i],
'name' => $ingredientNAME[$i]
);
}
With this array you can create the insert quite easily and insert whole rows.
I've recently started working with PHP and SQLite and I'm having problems with PHP arrays (I think). This is the code I use:
<?php
$dbo = new SQLiteDatabase("rsc/db.sqlite");
$test = $dbo->arrayQuery("DROP TABLE users;");
$test = $dbo->arrayQuery("CREATE TABLE \"users\"(name text, avatar text);");
$test = $dbo->arrayQuery("INSERT INTO users(name, avatar) VALUES('zad0xsis', 'http://zad0xsis.net/');");
// get number of rows changed
$changes = $dbo->changes();
echo "<br />Rows changed: $changes<br />";
// Get and show inputted data
$tableArray = $dbo->arrayQuery("SELECT * FROM users;");
echo "Table Contents\n";
echo "<pre>\n";
print_r($tableArray);
echo "\n</pre>";
?>
And when showing the data (print_r($tableArray);) I get this array:
Array
(
[0] => Array
(
[0] => zad0xsis
[name] => zad0xsis
[1] => http://zad0xsis.net/
[avatar] => http://zad0xsis.net/
)
)
I don't know why the values are duplicated, like [0] and [name], but it shows the data. Now, when I try to do print_r($tableArray["name"]); I should get the value, but it doesn't prints anything :( What I'm doing wrong? Thanks!
it helps you to select both
$tableArray[0]
or
$tableArray['name'];
it's fine.
to your problem: You'll have to
print_r($tableArray[0]['name'])
or
print_r($tableArray[0][0])