Insert Array into MySQL Table - php

I am new to php and I am trying to figure out how to add the array below to a MYSQL table called "skus".
Each subarray is a sku.
each value in the subarray is an options id. (ie. blue, green, yellow, etc.)
So, I want my table to look like this.
skuid optionid
the sku id is the primary key for the table and will autoincrement when I add the optionid values.
Array
(
[0] => Array
(
[2] => 27
[3] => 17
)
[1] => Array
(
[2] => 28
[3] => 17
)
[2] => Array
(
[2] => 27
[3] => 18
)
[3] => Array
(
[2] => 28
[3] => 18
)
)

So your array is:
$skus=array(
[SKU] => Array(
'option' => 27,
'option2' => 17
)
);
Once you've created your mySQL table you can use the following to sort the array and input into a table:
$connect = mysql_connect(HOST,USER,PASS) or die(mysql_error());
$delim = ":";
$length = count($skus);
foreach ($skus as $sku => $opt_array) {
$i = 0;
$opts = '';
foreach ($opt_array as $option_id) {
if ($i == count($opt_array) {
$opts .= $option_id;
} else {
$opts .= $option_id . ",";
}
$i++;
}
$query = "INSERT INTO `skus` (sku,opt_id,opt_id2) VALUES ('" . $sku . "','" . $opts . "')";
mysql_query ($query, $connect) or die (mysql_error());
}
As you say you only have two columns in your table your Option ID's will have to live in the same field within your table. This is why I have declared $delim as the delimeter between option ID's.
Your actual query for the first loop through the array would be:
INSERT INTO `skus` (sku,opt_id,opt_id2) VALUES ('SKU','27', '17')
and so on.
Hope this helps.

Related

Insert/Update Array data if new or exist

I have a form which displays existing data that can be edited and also allows for adding new data. How can I update and, if data is new, insert?
On submit I'm sending data like this:
Array
(
['0'] => Array
(
[id] => 19
[sort_order] => Sort 1
)
[0] => Array
(
[name] => Name 1
)
['1'] => Array
(
[id] => 19
[sort_order] => Sort 2
)
[1] => Array
(
[name] => Name 2
)
['2'] => Array
(
[id] => 19
[sort_order] => Sort 2
)
[2] => Array
(
[name] => Name 3
)
My function for insert
public function addFilterDamask($data) {
foreach ($data['filter'] as $filter => $value) {
$query = $this->db->query("INSERT INTO `" . DB_PREFIX . "damask_name` SET name = '" . $value['name'] . "', sort_order = '" . (int)$value['sort_order'] . "', filter_id = '" . (int)$value['id'] . "'");
}
}
Simplest way would be to check if MySQL has given it an ID yet, with the assumption you're using AUTO_INCREMENT:
$values = [
[
'id' => 1,
'sort_order' => 1,
],
[
'sort_order' => 2,
],
];
foreach ($values as $i => $value) {
if (array_key_exists('id', $value)) {
// INSERT
$values[$i]['id'] == ""; // result from ^
} else {
// UPDATE WHERE id == $value['id']
}
}
Alternatively, if you're creating your IDs, you can look into REPLACE, which does what you'd like, but from MySQL's side.
FYI: Check out prepared statements - You should not be using the values directly like you are in PHP, as people can use SQL injection to change your intentions.

LAMP attendance system

i just cant get the right approach to this problem, i have two arrays .
first array $attendance which has the following keys and values
Array
(
[attendance] => Array
(
[1] => 1
[2] => 1
[3] => 0
[4] => 1
[5] => 1
[6] => 0
[7] => 0
)
This is coming from a checkbox if checked value is 1 else value is 0
The second array is $remark
[remark] => Array
(
[1] =>
[2] =>
[3] => 'sick'
[4] =>
[5] =>
[6] => 'leave'
[7] => 'On assignment'
)
Now this is what the key 1- 7 stands for, the script is for employee's attendance the key 1-7 is the employeeID in the employee table in my database.
Now what i want to achieve is concatenate the array in such a way to look like this
Array
(
[0] => Array
(
[employeeID] => 7
[attendance] => 0
[remark] => 'On assignment'
)
[1] => Array
(
[employeeID] => 6
[attendance] => 0
[remark] => 'leave'
)
[2] => Array
(
[employeeID] => 5
[attendance] => 1
[remark] =>
)
//and so on
)
I am using Codeigniter If i am able to concatenate it i will also love to know how i will insert the multiple data into the employee table which looks like this,
employee's table
employeeID | date | status | remarks
the date i planned using CURDATE() then status will hold either 0 or 1 from attendance
Again: the keys from 1- 7 both on the remark and attendance's array is the employeeID
update!!
this is what i tried but did not work.
$att = $_POST['attendance'];
$remarks = $_POST['remark'];
foreach($att as $employee_id=>$status)
{
$x=0;
$employee[$x]['employee_id']=$employee_id;
$employee[$x]['status']=$status;
foreach($remarks as $employee_id=>$remark)
{
$employee[$x]['remark']=$remark;
$x++;
}
}
$attendance = $_POST['attendance'];
$remarks = $_POST['remark'];
$collect = array();
foreach ($attendance as $employeeID => $attending) {
$collect[] = array(
"employeeID" => $employeeID,
"attendance" => $attending,
"remark" => isset($remarks[$employeeID]) ? $remarks[$employeeID] : ""
);
}
$values = array();
foreach ($collect as $entry) {
$values[] = "(" . ((int) $entry["employeeID"]) . ",
CURDATE(),
" . ((int) $entry["attendance"]) . ",
'" . sql_escape($entry["remark"]) . "'
)";
}
$query = "INSERT INTO `attendance`
(`employeeID`, `date`, `status`, `remarks`)
VALUES
(" . implode(",", $values) . ")";
Make sure you replace sql_escape by the appropriate escape function. If you're using PDO use that.
Easy enough, to be honest...
$numOfEmployees = 8;
$concatArray = array();
foreach($attendance as $k => $v)
{
$concatArray[] = array("employeeID" => $k, "attendance" => $v, "remark" => $remark[$k];
}
If your attendance table is in anything like SQL, you could go about it with foreach on the above mentioned concatArray:
foreach($concatArray as $key => $value)
{
$remark = $value['remark'];
// sanitize remark for database
$query = "INSERT INTO employees (ID, Date, Status, Remarks) VALUES ({$value['employeeID']}, NOW(), {$value['attendance']}, '{$value['remark']}');";
// perform the actual query
}
Keep in mind that this is a very general example, making a lot of assumptions about the database.
As Frits notes, the remark field should be sanitized, perhaps by using mysqli_real_escape_string for MySQLi or quote for PDO - depends on what you are using.

how to insert array values in the database that are called in the class as an object in php

i need to store the array value that are called in the class as an object in the database.
coding
<?php
echo "BEST SELECTED POPULATION";
debug(GA::select($ga->population,'total',3)); //The best
$asma[]=GA::select($ga->population,'total',3); //The best
}
print_r($asma);
?>
$array1 is the array in which i get the output value,this array is dynamic that is the number of values increases in it depend on the user input.
<?php
include('config.php');
//database connection
//query
$new_array = array($asma);
foreach($new_array as $key => $value) {
foreach ( $value as $ind => $data ) {
/*
You now have access to field values like this
$data['Voltage']
$data['Number']
$data['Duration']
*/
// query makes no sense 3 fields mentioned and 4 parameters given???
// you will have to decide which of the fields from $data[] you want to load
// to which fields in the database.
$sql = "INSERT INTO ga (gaid,fe,fe1,timestamp) VALUES ('', '$key', '$value', '".date("Y-m-d H:i:s")."')";
$stmt = mysql_query($sql) or die(mysql_error());
} // endforeach
} // endforeach
?>
if i used above code for insertion it display no error but it enter value in table ga like this
gaid fe fe1 timestamp
1 0 array -
the above code which i used for inserting in my table ga
the output of print_r($asma);
Array (
[0] => Array (
[0] => H Object (
[Voltage] => 12
[Number] => 1
[Duration] => 3
)
[1] => H Object (
[Voltage] => 26
[Number] => 4
[Duration] => 8
)
[2] => H Object (
[Voltage] => 26
[Number] => 4
[Duration] => 8
)
)
[1] => Array (
[0] => H Object (
[Voltage] => 18
[Number] => 1
[Duration] => 4
)
[1] => H Object (
[Voltage] => 38
[Number] => 4
[Duration] => 10
)
[2] => H Object (
[Voltage] => 36
[Number] => 2
[Duration] => 8
)
)
)
i need to store all values in the database in above output 6 values.
this is table ga
gaid fe fe1 fe2 timestamep
It does not help that you keep talking about array1 in your description but I dont see anything called array1 in your code.
But making the assumption that array1 = $new_array here is a suggestion.
<?php
include('config.php');
//database connection
//query
/*
* This achieves nothing other than adding an extra level of array
* Try removing it
*/
//$new_array = array_combine($asma,$asma);
foreach($asma as $key => $value) {
foreach ( $value as $ind => $hObject ) {
$q = "INSERT INTO ga (fe, fe1, f2, timestamp ) VALUES (%d, %d, %d, '%s' );
$qs = sprintf( $q, $hObject->Voltage,$hObject->Duration,
$hObject->Number, date("Y-m-d H:i:s") );
$result = mysql_query($qs);
if ( ! $result ) {
die( 'Insert failed ' . mysql_errno() . ' ' . mysql_error() );
}
} // endforeach
} // endforeach
?>

Processing array and inserting in mysql table

Array
(
[pid] => Array
(
[0] => 2
[1] => 3
)
[price] => Array
(
[0] => 20
[1] => 20
)
[qty] => Array
(
[0] => 2
[1] => 1
)
)
i have an outcome of the above array from some processing. with this i need to update to database like below table
pid price qty
2 20 2
3 20 1
$i = 0;
while( $i < count( $YourArray['pid']) ) {
$query = "INSERT INTO `tableName`(`pid`, `price`, `qty`) VALUES( ?, ?, ? )";
$stmt = $con->prepare( $query );
$stmt->execute(
array(
$YourArray['pid'][$i],
$YourArray['price'][$i],
$YourArray['qty'][$i]
)
);
$i++;
}
Where, I used the pdo method of insertion.
for(i=0;i<amount;i++){
echo $array['pid'][i];
echo $array['price'][i];
echo $array['qty'][i];
}
Where amount must be a count of the amount of rows you have
Try this :
$array = array("pid" => array(2,3),"price" => array(20,20),"qty" => array(2,1));
array_unshift($array, null);
$res = call_user_func_array('array_map', $array);
echo "<pre>";
print_r($res);
Output :
Array
(
[0] => Array
(
[0] => 2
[1] => 20
[2] => 2
)
[1] => Array
(
[0] => 3
[1] => 20
[2] => 1
)
)
loop this array and add to DB - So that you can add two entries in DB
this is a wrong way of doing it, i would use an indexed array, and then build a foreach loop that will handle each 1 separately, something like:
$values = array();
$values[] = array(
'pid' => 2,
'price' => 20,
'qty' => 2
);
$values[] = array(
'pid' => 3,
'price' => 20,
'qty' => 1
);
and from this then build a foreach loop and run each query there
foreach ($values as $value) {
$query = "insert into blah
set pid = " . $value['pid'] . ",
price = " . $value['price'] . ",
qty = " . $value['qty'] . ";";
mysql_query($query);
}

insert php array into mysql

I have an array $product_array, and when I use print_r($product_array);. The array shows like this
Array
(
[0] => Array
(
[ID] => P00100
[NAME] => Edina
[PRICE] => $20.00
)
[1] => Array
(
[ID] => P00101
[NAME] => Richfield
[PRICE] => $21.00
)
[2] => Array
(
[ID] => P00102
[NAME] => Bloomington
[PRICE] => $22.00
)
)
I set my database table in 4 columes, first one is mainid, and which is auto increment, following with ID, NAME, PRICE, as the keys showed above.
I would like to insert this array $product_array into mysql.
Can anyone help? Would be very much appreciated!
tks.
$sql = array();
foreach( $myarray as $row ) {
$sql[] = '('.$row['ID'].', "'.mysql_real_escape_string($row['NAME']).'",
"'.$row['PRICE'].'")';
}
mysql_query('INSERT INTO table (ID, NAME,PRICE) VALUES '.implode(',', $sql));
see more details :
insert multiple rows via a php array into mysql
You can try this code (quick 'n' dirty):
foreach($product_array as $v) {
$query = 'insert into tablename values (null, \'' . $v['id'] . '\', \'' . $v['name'] . '\', ' . $v['price'] . ');'
mysql_query($query);
}

Categories