I have a form having 6 fields with same nameLike - feature[],
I want to save multiple input fields value into mysql 1 column in JSON format:
<form method="post" action="<?php echo base_url();?>product/save/">
<input type="text" class="form-control" name="feature[]" placeholder="fetaure 1">
<input type="text" class="form-control" name="feature[]" placeholder="fetaure 2">
<input type="text" class="form-control" name="feature[]" placeholder="fetaure 3">
<input type="text" class="form-control" name="feature[]" placeholder="fetaure 4">
<?php ?>
I have column feature in mysql table, i want to save input field value into feature column as json data. i am using codeigniter 3.
ex for codeignitor
function save()
{
$feature = $this->input->post('feature');
$json = json_encode($feature);
$this->Your_model_Name->save($json);
}
You simply need to get the INPUTS based on the form method. Save the inputs in a variable based on form method post/get.
POST:
$features=$_POST["feature"];
GET:
$features=$_GET["feature"];
$features will be a PHP Array and you can use json_encode() to encode the PHP Array to JSON String. Like this,
$features_json=json_encode($features);
Now use this variable $features_json to save JSON String in MySQL Database.
Your JSON String after encoding will look like this: http://json-parser.com/67c07feb
Since it is an array, you need a foreach loop. your function must look like this
Controller
function save()
{
foreach($this->input->post('feature') as $f)
{
$f = trim($f);
$data = json_encode($f);
$this->YOUR_MODEL->insert_to_table($data);
}
}
Model
function insert_to_table($data)
{
$this->db->insert('table_name',$data);
}
This way, you post every input you have
hope this helps
controller (product)
function save() {
$features = $this->input->post('feature');
$feature_json = json_encode($features);
//send to model
$this->load->model('your_model');
$this->your_model->insert($feature_json);
}
model
function insert($feature_json) {
$data = array(
'features' => $feature_json
);
$this->db->insert($data);
}
update
Add trim and xss clean using form validation
$this->form_validation->set_rules('feature[]',"Feature", "trim|xss_clean");
Related
Started learning PHP today so forgive me for being a noob. I have a simple HTML form where the user inputs 4 strings and then submits.
HTML form
<html>
<head>
<title>EMS</title>
</head>
<body>
<h1>EMS - Add New Employees</h1>
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
<table>
<tr><td>Enter a NAME:</td><td> <input type="text" name="name"></td></tr>
<tr><td>Enter a PPSN:</td><td> <input type="text" name="ppsn"></td></tr>
<tr><td>Enter a PIN :</td><td> <input type="text" name="pin"></td></tr>
<tr><td>Enter a DOB:</td><td> <input type="text" name="dob"></td></tr>
<tr><td></td><td><input type="submit" value="Add New Employee" name="data_submitted"></td></tr>
</table>
</form>
</html>
I want to implode the 4 elements in the $_POST["data submitted"] array to a string.
PHP
<?php
if (isset($_POST['data_submitted'])){
$employee = implode(",",$_POST['data_submitted']);
echo "employee = ".$employee;
}
?>
Why is it that when I run the project, Input the 4 strings into the form and submit that there is nothing contained within the employee string when its outputed? There is however a value in the employee string when I just implode the $_POST array like so without 'data_submitted'.
$employee = implode(",",$_POST);
The output of the $employee string is now - employee = will,03044,0303,27/5/6,Add New Employee
It contains the name,pps,pin,dob and this ADD New Employee value?
How do I just get the $employee string to contain just the name,pps,pin and dob from the $POST_[data_submitted] array?
If you wish to implode the submitted data, then you need to refer to the specific items, as follows:
<?php
$clean = [];
if (isset($_POST['data_submitted'])){
// one way to deal with possibly tainted data
$clean['name'] = htmlentities($_POST['name']);
$clean['ppsn'] = htmlentities($_POST['ppsn']);
$clean['pin'] = htmlentities($_POST['pin']);
$clean['dob'] = htmlentites($_POST['dob']);
$employee = implode(",",$clean);
echo "employee = $employee";
}
Never use submitted data without first checking to make sure that it is safe to do so. You need to validate it. Since the OP doesn't specify what kind of data the named inputs "ppsn", "pin", "dob" pertain to, this example does a minimum of validation. Each input might require more or something different.
Whether you're new or familiar with PHP, it is a good idea to frequently read the online Manual.
First, you need to know that php will treat value in the format: value="value here" as string.
So, calling implode(",",$_POST['data_submitted']); will return Add New Employee as declared here: <input type="submit" value="Add New Employee" name="data_submitted">.
From your question:
How do I just get the $employee string to contain just the name, pps, pin and dob from the $_POST[data_submitted] array?
Solution
1. Unset the <code>$_POST['data_submitted']</code> index in the $_POST super global variable
2. Implode it
// Unset the $_POST['data_submitted'] index
$post_data = unset( $_POST['data_submitted'] );
// Format the post data now
$format_post_data = implode( ",", $post_data );
// Escape and display the formatted data
echo htmlentities( $format_post_data, ENT_QUOTES );
I've setup a form with a table which includes rows from a database. I've used a variable to represent the database record ID as the name for one of the rows like this:
<td><input type="text" name= "<?php echo $recordID; ?>" class="form-control" placeholder="User Notes"></td>
which is working fine and ends up appearing like this in the browser:
<td><input type="text" name= "TSL1406" class="form-control" placeholder="User Notes"></td>
I'm having trouble retrieving the value when the form is submitted. I would normally use something like this:
$input = $_POST['userNotes']
which I've updated to handle the dynamic naming of the inputs like this:
$input = $_POST['.$recordID.'];
but this is returning an empty variable and I can't work out the correct syntax to retrieve the input from the $_POST array with a dynamically named input field?
single quote " ' " means literal, it won't display your variable name just literally .$recordID.. Try using double quotation instead.
$input = $_POST[".$recordID."];
Only $input = $_POST[$recordID]; without quotes?
or you use arrays like:
<input type="text" name= "form[<?php echo $recordID; ?>]" class="form-control" placeholder="User Notes"></td>
and save everything at once
$input = $_POST['form'];
Why don't you just simply use $_POST[$recordID]? However there is a better way to get POST variable using filter_input(INPUT_POST, $recordID)
I am trying to save the values from html checkboxes in a MySQL database table but I am not doing it right. I need your suggestions here.
This is my html
#foreach($sql as $sql)
<div class="form-group">
<label class="control-label mb-10" for="">{{$sql->name}}</label>
<div class="input-group">
<input type="hidden" name="resource[]" value="{{$sql->id}}">
<input type="checkbox" name="resources[]" value="c">Create
<input type="checkbox" name="resources[]" value="r">Read
<input type="checkbox" name="resources[]" value="u">Update
<input type="checkbox" name="resources[]" value="d">Delete
</div>
</div>
#endforeach
This is my controller where I am trying to save into a DB table
public function store(Request $request) {
foreach ($request->resource as $resource) {
# code...
foreach ($request->resources as $resources) {
$res[] = $resources;
$options = implode(',', $res); // Get selected options
$resource = $resource; // Get value of the resource
}
}
}
This does not work as it only shows just one 'selected checkbox field'.
Please what am I doing wrong?
Looking at your HTML code, it appears you're going to be looping over possibly more than one SQL statement to make the checkboxes. The server won't be able to tell these apart. You should change your checkbox names to be more like:
<input type="checkbox" name="resources[{{$sql->id}}][]" value="c">Create
<input type="checkbox" name="resources[{{$sql->id}}][]" value="r">Read
Then your PHP code could look something like this:
foreach ($request->input('resources') as $id => $resources) {
$options[$id] = implode(',', $resources);
}
Each SQL statement will be in the $options array keyed by the SQL id. The array value will be the checked checkboxes values separated by a comma.
print_r($options)
[
1 => "c,r,u,d",
2 => "c,r,d"
]
If you are trying to save the selected values separated by comma, for ex: if user has selected by c and d, then you are saving in database as c,d ?. if so then you can get all selected values in single line.
public function store(Request $request) {
// get all values separated by comma
$selectedValues = implode(",", $request->input('resources'));
// save values in database here
}
remember the your checkbox is an array !
for your understating better what sent to your controller just write
print_r($_POST);exit();
to see what arriving exactly after that write it in your framework method like :
foreach($_POST['resources'] as $resources){
...
}
I'm building a calculator for a mmo guild. At this moment I'm looking for a way to make data more easy to access for calcules.
Basically, I have a form with 5 text fields (just for test, there will be a lot more), and a select list (for choose the proper equation).
Example code:
<input type="text" id="strength" name="strength" value="0">
<input type="text" id="dexterity" name="dexterity" value="0">
<select name="equation" id="equation">
<option name="damage" id="damage">Damage</option>
<option name="defense" id="defense">Defense</option>
</select>
So this form will be procesed through a php file.
<form action="file.php" method="post">
//inputs here
<input type="submit" value="calculate">
</form>
At this moment I'm receiving all data in php file with vars:
$strength = (int)$_POST['strength'];
$dexterity = (int)$_POST['dexterity'];
For start is ok, but when my script is complete there will be more than 20 fields... so I wanna store all data in an array, something like this:
$strength = array(
'fuerza' => 125,
'dexterity ' => 125,
//and more fields...
);
And use this data in various different functions for equations:
function equation1()
{
$damage = $stats['dexterity'] + $stats['strength'];
}
I have read several posts and tutorials about use name value from inputs for create an array somethin like this: name="name[]". But doesn't work for me how I want. This calculator will receive just 1 value for each "stat", and I need have all these values in an array so I can access them from different fuctions in my script.
Please ask me if my question is not clear, and sorry if my english is bad.
EDIT AFTER SOLVE
I let here my code after solve:
.html example:
<input type="text" id="strength" name="stats[strength]" value="0">
<input type="text" id="dexterity" name="stats[dexterity]" value="0">
<select name="operation" id="operation">
<option name="damage" id="damage">Damage</option>
<option name="defense" id="defense">Defense</option>
</select>
.php example:
function critOp($stat)
{
$result = $stat * 0.00725;
return $result;
}
switch($_POST['operation']){
case 'damage' :
$critical = critOp($_POST["stats"]["dexterity"]);
break;
//more case...
You can use brackets in the name field to direct PHP to stick them in an array. If you use [] it will form a numerical array, but you can specify an associative key in the brackets like [dexterity]
<input type="text" id="dexterity" name="strength[dexterity]" value="125">
<input type="text" id="fuerza" name="strength[fuerza]" value="125">
This will result in
$_POST['strength'] = array(
'dexterity' => 125,
'fuerza ' => 125,
);
Bonus points
You can continue to enforce integer values by using array_map:
$_POST['strength'] = array_map('intval', $_POST['strength']);
This will make sure all values are integers.
Well I am Stuck some where here in Array conversion:
My Controller:
$username = $this->input->post('FirstName');
$countryval= $this->input->post('country');
var_dump($countryval);
My View:
<input type="text" name="FirstName" id="Name" >
<?php
foreach ($countryDetails as $row )
{
echo '<input id="country" type="checkbox" name="country[]" class="unique" value="'.$row->country_id.'">'.$row->country_name.'<br/>';
}
?>
<script>
$('input.unique').click(function() {
$('input.unique:checked').not(this).removeAttr('checked');
});
</script>
I am getting the value from checkbox in an array and I need to pass that value as a string further.
I am not able to convert value from array to string i.e if I var_dump($countryval) I get value in array ! Please Help. Thank you
That is because you have used "country[]" as the name in input field
Please try this incase you need a single value to be returned (Edit made here coz I put type="checkbox" instead of "radio".. I have corrected it) Trust radios for single values.
echo '<input id="country" type="radio" name="country" class="unique" value="'.$row->country_id.'">'.$row->country_name.'<br/>';
hope that helps
You need "country[ ]" as name only if it has multiple values. Eg., For a multiple select
<select name="country[]" multiple>
<option></option> <!-- Your options go here-->
</select>
You can use input-checkbox too.. But with your question, I believe you need just a single value to be returned.
Ok.. Now From Your comments I kind of get what you want. Here is my suggestion
1) When you are having multiple checkboxes with the same name, the values are sent as an array.
2) If you would need a single value at a time and definitely need a checkbox, You can make a radio look like a checkbox like this.
3) If you really want to proceed with your javascript allowing only one checkbox at a time, you can do this.
// Load the 'array' helper
$this->load->helper('array');
// Use the 'element' function to return an element from the array
$countryval = element('0', $this->input->post('country')); //should work
Have a try..!!