display all data in select form in cakephp - php

i am using cakephp. and want to display all data in database in dropdown list. but it returns only last item. there is some problem in loop. my code is below.
foreach ($origions as $or);
$id = $or["origions"]["id"];
$orgn = $or["origions"]["origion"];
$options = array($id=>$orgn);
echo $this->Form->select('origions.origion', $options);
this display only last record in dropdown list. please help what to do that all data in table display over here.

Change it to,
$options = array();
foreach ($origions as $or){
$id = $or["origions"]["id"];
$orgn = $or["origions"]["origion"];
$options[$id] = $orgn;
}
echo $this->Form->select('origions.origion', $options);
For selected,
echo $this->Form->select('origions.origion', $options, array('value' => 'your_default_id'));
Reference.

OTHER WAY (more optimized code)...
You can set Your data $this->set from the controller.
From controller You can combine / extract / merge / sort / etc... multidimensional arrays like:
$result = Set::combine($origions, '{n}.origions.id', '{n}.origions.origion');
Read more about Cakephp SET::array functions http://book.cakephp.org/2.0/en/core-utility-libraries/set.html

Related

Looping through multi-dimensional array to pre-populate dynamically generated form

I am trying to create an ecommerce site. I have products that have different attributes (e.g. colour) and each of these needs to have their own model number and price etc,.
I have generated a form to gather this information and save it. However, I want to be able to save this info as a $_SESSION variable while users are adding products, so that they can come back to the price section and the form will be pre-populated with what they previously entered even though they haven't actually saved the product to the DB yet.
To do this I have a string that I treat as an array of items stored as a $_SESSION variable in PHP in the following format:
'item-test,100,20,20,20,20,£,1,item-test,100,20,20,20,20,£,2'
I parse this into an actual array I can deal with like so (when it gets to actually saving the product my SQL query is inside this foreach() loop):
if(isset($_SESSION['price_array'])){
$price_array = $_SESSION['price_array'];
$result = explode("item-",$price_array);
foreach($result as $item){
if(isset($item) && $item!=""){
$itemValue = explode(",",$item);
$product_model_no = $itemValue[0];
$product_value = $itemValue[1];
$product_discount = $itemValue[2];
$product_margin = $itemValue[3];
$product_shipping_domestic = $itemValue[4];
$product_shipping_other = $itemValue[5];
$product_currency = $itemValue[6];
$product_attribute = $itemValue[7];
}
}
}
So to generate this form I've another loop that goes through all of the possible attributes (not all products might come in all colours so only the ones stored in the $_SESSION apply). If I try to pre-populate this as it is my variables above only have the values for the last item in the array.
However if I nest this inside the other loop it will get the correct data but it will generate the form a number of times depending on how many items are in the array, with each iteration of the form having the values for that item in the array.
I know this is very convoluted to try explain and I can't really provide all my code because it is very complex and most of it is generated in PHP from other information in other locations.
Edit
The basics of how the form is being generated inside the other loop is as follows:
$params = [$attribute];
$sql = "SELECT * FROM attributes WHERE id=?";
$attributeResult = DB::run($sql,$params);
foreach ($attributeResult as $value) {
for ($i = 1; $i <= 15; $i++) {
//generate form here
if($i == $product_attribute){
// pre-populate form here
}
}
}

Update One JSON Field in Database - CodeIgniter

I have a JSON field called 'spec' and there are about 10 other items in this in JSON format. I need to only update the quantity.
Although when I try this method, it deletes everything else in it and just sets spec = quantity.
Heres what I have so far.
$pass_coupon_id = $this->pass_coupon_id();
$coupon_array = $this->db->query("SELECT * FROM coupon WHERE coupon_id='$pass_coupon_id'")->result_array();
foreach ($coupon_array as $row) {
$spec = json_decode($row['spec'], true);
}
$quantity_new = $spec['quantity'] - 1;
$data2 = array(
'spec' => json_encode(array(
'quantity'=> $quantity_new
)));
$this->db->where('coupon_id', $pass_coupon_id);
$this->db->update('coupon', $data2);
You need to overrite only this one field and update whole field in query.
<?php
$pass_coupon_id = $this->pass_coupon_id();
$coupon_array = $this->db->query("SELECT * FROM coupon WHERE coupon_id='$pass_coupon_id'")->result_array();
// i don't know what you're using, but using foreach to extract single row isn't good solution. Look for sth like result_row() maybe.
$coupon = $coupon_array[0];
$spec = json_decode($coupon, true);
$new_quantity = $spec['quantity'] - 1;
$spec['quantity'] = $new_quantity;
$new_spec = json_encode($spec);
$this->db->where('coupon_id', $pass_coupon_id);
$this->db->update('coupon', $new_spec);
Depending on the database, the best solution would be using specific function to ommit updating whole structure - https://stackoverflow.com/a/34987329/2926214

how to add , edit and delete comma separated value of database .?

i have created one table called role and the fields are like (roleid,role,prohibitedprocess,prohibitedports) here roleid is unique. and i have a comma separated value for "prohibitedprocess" field .(ex: prohibitedprocess---> skype,teamviwer,notepad).
the problem is how to add and edit and delete that comma separated value of prohibitedprocess .is it possible ?
i have fetch the code form the data base .code is
<?php
$sql = "SELECT roleid, prohibitedprocess, prohibitedports FROM role WHERE role='Basic'";
$option='';
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result))
{
$pro_proc = $row['prohibitedprocess'];
$lst = explode(",",$pro_proc);
//Print in Option Box
foreach($lst as $exp)
{?>
<tr>
<td><?php echo $exp;?></td>
<td>Edit</td>
<td>Delete</td></tr>
<?php
}
}
?>
How to do this please help me
You can edit the whole string . .
I mean just using str_replace function
e.g
$string = "skype,teamviwer,notepad";
$old_value = "skype";
$new_value = "facebook";
$new_string = str_replace($old_value,$new_value,$string);
Then simply update this new string into database table. .
One way would be to retrieve all of 'keywords' in an input element and edit them like a sentence. However, for what you want to do, you may wanna add a new table called prohibitedprocess and use roleid as a foreign key. Then retrieve from that table according the roleid.
eg: SELECT item FROM prohibitedprocess p, role r WHERE p.roleid = r.roleid
It may be better to make another table for that relation, then you could edit it normally. Otherwise you can take your comma separated list and do something in javascript.
var commaSeparatedList = <?php echo $commaSeparatedList;?>
var realData = commaSeparatedList.split(',');
// when the user adds something you can add to the array or delete
// from the array
var newCommaList = readData.join([separator = ',']);
// some kind of get/post request that sends the new comma list
<?php
$newList = GET_REQUEST_PARAMS["newCommaList"];
// sql update query that updates the comma list
?>
I haven't used php in a while so I know GET_REQUEST_PARAMS isn't a thing but i'm sure you know how to get the parameters.
Or without javascript you can use a form that posts back all the names of prohibited things
<?php
$newList = ""
//foreach through the get params which contain the names
foreach()
{
$newList += getParam + ",";
}
// some code to remove that last comma
// sql update
?>

Passing multiple checkbox values to different columns of database

I am pretty new to PHP, but have tried searching for other questions similar to mine and been unable to find anything that is close enough to my situation to help me solve this.
I am trying to code a web page that allows users to select as many or as few items as they would like to order. The item values are identical to their Primary Key in the Item table.
Once submitted, each different item value should be input into the same row of a database table based on the date{pk}. Within that row, there are numerous columns: Item1ID, Item2ID, Item3ID, etc.
So far, the value of each item selected is assigned to a new array. However, I cannot simply input the array values into a column -- I need each array index to be placed into a sequential column. The code is below:
$date = new DateTime();
$td = $date->format('Y-m-d');
$x = 1;
$checkedItems = $_POST['Item'];
$count = count($checkedItems);
echo $count;
$foodID = "Item".$x."ID";
While($x<=$count){
if(isset($_POST['Item'])){
if (is_array($_POST['Item'])) {
foreach($_POST['Item'] as $values){
$selectedFoods = substr($values,0,4);
$addFoodOrderQuery= sprintf("UPDATE WeeklyBasketFoodOrder SET '%s' = %s WHERE `foodOrderDate` = '%s'",
$foodID, $selectedFoods, $td);
$result= mysqli_query($db, $addFoodOrderQuery);
}
}
} else {
$values = $_POST['Item'];
echo "You have not selected any items to order.";
}
$x++;
}
If you need any further clarification, please let me know. After submitting the code, the database item#ID tables are different, but they are now empty instead of "NULL."

How to iterate through a mysql array and append corresponding text from an PHP array

I am making a pricing table to upgrade membership.
In mySQL I have a table with limits on what each membership can allow see picture
I grab the info from the table and try to iterate through it and append some text to it from another array. I have tried thoroughly looking online for an answer but I'm probably not even searching for the right terms. For the purpose of this question i'm using 2 fields but in reality i will be iterating and appending many columns.
Here's my code:
$sql = "SELECT maxProducts,maxImages FROM memproducts_membership_settings WHERE useThis='1'";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs,MYSQL_ASSOC))
{
foreach($row as $field)
{
$append = array('Product Slots','Images per product');
print $field.' '.$append.'<br>';
}
}
All i get is:
5 Array
2 Array
and not what i need which would be:
5 Product Slots
2 Images per product
I'm sure there is a way to do this but i just cannot figure it out, please anyone give me some pointers? Many regards :)
This is pretty basic stuff...
while($row = mysql_fetch_array($rs,MYSQL_ASSOC))
{
echo $row['maxProducts'] . ' Product Slots<br>';
echo $row['maxImages'] . ' Images per product<br>';
}
Or if you are needing to do this with dynamic fields in whatever order you return from database like your question suggests, perhaps you might consider providing a mapping of database column names to the appropriate label content like this:
$labels = array(
'maxProducts' => 'Product Slots',
'maxImages' => 'Images per product',
...
);
...
while($row = mysql_fetch_array($rs,MYSQL_ASSOC)) {
foreach ($row as $key => $value) {
echo $value . ' ' . $labels[$key] . '<br>';
}
}
Note if you are just learning PHP, you REALLY should NOT learn mysql_* functions. They are deprecated and need to die. Please learn to use PDO or mysqli.
To append values to the end of an array use array_push()
http://php.net/manual/en/function.array-push.php
There's plenty about your code and your approach that I don't like at all, but the most immediate solution to your current problem would be to iterate the array of strings from within the foreach loop, using each():
$strings = array('Product Slots','Images per product');
while($row = mysql_fetch_array($rs,MYSQL_ASSOC))
{
reset($strings);
foreach($row as $field)
{
$append = each($strings);
print $field.' '.$append[1].'<br>';
}
}
You should at very least make yourself aware of:
the deprecation of ext/mysql (use either mysqli or PDO); and
the risk of XSS attacks (escape any HTML in values from your database before returning them to the browser).
It's doing what it should... You have created an array and asked it to print its name. As print can't automatically iterate an array it just tells you what the variable type is.

Categories