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.
Related
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.
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);
}
I need to generate a mysql insert query with this array , where the column name are the field_name & values are field_values. i tried using implode, here its nested array & troubling me lot.
Array
(
[0] => Array
(
[field_name] => Date
[field_value] => 01/02/2013
)
[1] => Array
(
[field_name] => Time
[field_value] => 03:20 PM
)
[2] => Array
(
[field_name] => submitted_lat
[field_value] => 13.06114
)
[3] => Array
(
[field_name] => submitted_long
[field_value] => 80.2371547
)
[4] => Array
(
[field_name] => submitted_on
[field_value] => 2013-02-01 15:20:10
)
[5] => Array
(
[field_name] => submitted_by
[field_value] => superadmin#gmail.com
)
[6] => Array
(
[field_name] => pdf
[field_value] =>
)
)
Try this
$sql = "INSERT INTO `table_name` SET ";
$sql_fields='';
foreach($array_name as $k=>$v){
$sql_fields .= "`".$v['field_name']."`='".$v['field_value']."', ";
}
$sql_fields = substr($sql_fields,0,-2);
$sql .= $sql_fields;
echo $sql;
A very simple approch would be this :
$query = 'insert into table ';
foreach($inputs as $input) {
$query .= ' '.$input['field_name'].' = '.$input['field_value'];
}
echo $query;
$fields=array();
$values=array();
for($i=0;$i<count($array);$i++)
{
$fields[]=$array[$i]['field_name'];
$values[]=$array[$i]['field_value'];
}
if(count($array) > 0)
{
$query="Insert into tablename (".implode(",", $fields).") values (".implode(",", $values).")";
mysql_query($query);
}
You need to ensure that your values are correct and protected to avoid SQL Injection. Building dynamically your own SQL query and inserting directly in your database is not safe.
Anyway you can use array_map() to do something like this:
$arr = array(array("name" => "column1", "value" => "value1"),
array("name" => "column2", "value" => "value2"),
array("name" => "column3", "value" => "value3"));
$columns = array_map(function($item) { return $item['name'];}, $arr);
$values = array_map(function($item) { return "'". $item['value'] . "'";}, $arr);
$columnsList = implode(',', $columns);
$valuesList = implode(',', $values);
$sql = "INSERT INTO mytable($columnsList) VALUES ($valuesList)";
EDIT: As said in introduction this would not be safe and it would be better to use MySQLi or PDO. But you would also need to know the type of the column you want to insert into.
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.
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);
}