Reputation: 27
i have been trying to write a program to insert the array values in multiple rows of a column in a database table. After lot of trial I couldn't get the proper output I wanted.
My database table looks like this
id | values |
1 | |
2 | |
4 | |
5 | |
6 | |
and I have 2nd column values as an array and I want to enter those values in the second column.
The output should look like this:-
id | values |
1 | 2 |
2 | 3 |
4 | 7 |
5 | 9 |
6 | 10 |
So, I have two array values $id
and $values
...So, I want to fill $values
in each row of the column for each respective $id
values
NOTE : $id
is already filled in the database
Upvotes: 0
Views: 3998
Reputation: 1488
Traverse the array values in a loop and on each iteration of the loop make and execute a query. The sample code will look something like this, change it as according to your variables and need.
foreach ($array as $id => $values) {
$query = "INSERT INTO table (id ,values) VALUES ($id , $values)";
$result = mysql_query($query);
}
Upvotes: 0
Reputation: 6545
I am assuming that you have an array with the id values in it.
You may try something like this:
foreach($XArray as $key => $value){
$sql = "UPDATE TABLENEAME ".
"SET value = $value ".
"WHERE id = $key" ;
$retval = mysql_query( $sql, $conn );
}
I haven't checked the code, its just a sample.
With respect to the updated question:
$count=sizeof($value);
for($counter=0;$counter<$count;$counter++){
$sql = "UPDATE TABLENEAME ".
"SET value = $value[$counter]".
"WHERE id = $id[$counter]" ;
$retval = mysql_query( $sql, $conn ) or die ("Error in query: $sql");
}
Upvotes: 1
Reputation: 1490
Try this :
foreach ( $array as $key => $value )
{
$query = "INSERT INTO table
SET values = $value,
id = $key
ON DUPLICATE KEY UPDATE values = $value";
}
I do not know what sort of database you are using, this example is for MySQL.
And I also don't know how you insert information in the DB ( simple mysql_query, pdo, frameworks, ... ), so you should use the function you need and pass that query string and, if needed, don't forget to properly sanitize the array.
EDIT : I also assume that id is a primary key or unique index
Upvotes: 1
Reputation:
foreach($yourArray as $key => $value){
// <INSERT QUERY LINE HERE > ( you have to insert $value insite 'values' )
}
Upvotes: 0