How can I insert a new item into an array on any position, for example in the middle of array?
php
arrays
insert
Answers
2
I would say just build it yourself. You can set it up like this:
$query = "INSERT INTO x (a,b,c) VALUES ";
foreach ($arr as $item) {
$query .= "('".$item[0]."','".$item[1]."','".$item[2]."'),";
}
$query = rtrim($query,",");//remove the extra comma
//execute query
Don't forget to escape quotes if it's necessary.
Also, be careful that there's not too much data being sent at once. You may have to execute it in chunks instead of all at once.
Saturday, November 5, 2022
4
Your main issue is, declaring $query
outside the loop.
It makes it a constant, and that too, takes values $a
and $b
which are that time, undefined, so results in invalid syntax for SQL.
foreach($Cust_PN as $a => $b) {
$query1 = "INSERT INTO SO_Items (Timestamp, SO_Num, SO_Rev, SO_Line_Item, Cust_PN, Cust_PN_Rev, My_PN, My_PN_Rev, Description, Qty, Sale_Price, UOM, Program, Required_Date) VALUES (NOW(), '$SO_Num', '$SO_Rev', '$SO_Line_Item[$a]', '$Cust_PN[$a]', '$Cust_PN_Rev[$a]', '$My_PN[$a]', '$My_PN_Rev[$a]', '$Description[$a]', '$Qty[$a]', '$Sale_Price[$a]', '$UOM[$a]', '$Program[$a]', '$Required_Date[$a]');";
$q = mysql_query($query1) or die ('Error posting data');
}
Try that. Fixed your SQL query too. Correct syntax is
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
You had put SELECT
in place of VALUES
Let me know if it works, and otherwise please tell what error it ives exactly.
Sunday, November 27, 2022
4
<input type="number" name="unos[]">
<input type="number" name="unos[]">
<input type="number" name="unos[]">
etc.
The above is standard for pulling form values into an array, but, given your update:
// Assuming "," separated values
$unos = explode(",", $_POST['unos']);
foreach ($unos as $item) {
echo $item; // Do something with item
}
Saturday, October 1, 2022
1
you could indeed use PHP's array_map() to do this
function cb($obj) { return $obj->myMethod(); }
.
.
$data = array_map(cb, $objects);
Tuesday, November 29, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
php
arrays
insert
You may find this a little more intuitive. It only requires one function call to
array_splice
: