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.
Related
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.
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 have an sql query which outputs an array the output looks like this
Array
(
[0] => Array
(
[customer_id] => 7
[language_id] => 1
[variableitem_id] => 13
[name] => QUESTION_HEADLINE
[value] => Bitte geben Sie Ihren Downloadkey ein:
)
[1] => Array
(
[customer_id] => 7
[language_id] => 1
[variableitem_id] => 15
[name] => QUESTION_BUTTON
[value] => Start!
)
[2] => Array
(
[customer_id] => 7
[language_id] => 1
[variableitem_id] => 6
[name] => PAGETITLE
[value] => Steigenberger Hotels and Resorts - Mediathek
)
)
In my controller I get it as
$data['variables_data'] = $this->Home_model->getVariables($customer_id, $language_id);
Now for different ids in the url like for
localhost/home/user/12 and localhost/home/user/14
the positions of the variable differs
for example in my view when I echo
$variable[0]['value']
it gives QUESTION_HEADLINE for one user and PAGE_TITLE for the other .
Is it possible to make them same for all of the user like if I echo
$variable[0]['value']
it should return me QUESTION_HEADLINE every time and for every user
Code for Home model get_variables function
function getVariables($customer_id, $language_id) {
$query = $this->db->query("SELECT customers_idcustomers AS customer_id,
languages_idlanguages AS language_id,
variableitems_idvariableitems AS variableitem_id,
variableitem AS name,
variabletext AS value
FROM variables v
LEFT JOIN variableitems vi ON v.variableitems_idvariableitems = vi.idvariableitems
WHERE v.customers_idcustomers ='" . $customer_id . "'
AND v.languages_idlanguages =" . $language_id
);
$var = $query->result_array();
return $var;
}
Thanks in advance
You can set it explicitly, like
foreach($outArray as $output)
{
$output['name']="Any thing you want";
}
So , as i understand you want to make reduce your output to one dimension. It can be done with MYSQL also. Here php version:
In your controller
$data = $this->Home_model->getVariables($customer_id, $language_id);
$data['variables'] = array(
'customer_id' => $data[0]['customer_id'],
'language_id' => $data[0]['language_id'],
'variableitem_id' => array(),
'name' => array(),
'value' => array()
);
foreach($data as $k => $v) {
$data['variables']['variableitem_id'][] = $v['variableitem_id'];
$data['variables']['name'][] = $v['name'];
$data['variables']['value'][] = $v['value'];
}
And in your view
echo $variables['value'][2].' '.$variables['value'][3];
//do whatever you want
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);
}