data is not inserting into database in codeigniter - json

actually i am having student records in $students array and there is another array within $students, whose name is skill[], which is a checkbox form field name, so pls tell me how to use json_encode and where.
input form
<td>ENTER SKILLS</td>
<td>
<input type="checkbox" name="skills[]" value="php">php<br>
<input type="checkbox" name="skills[]" value="dotnet">dotnet<br>
<input type="checkbox" name="skills[]" value="java">java<br>
<input type="checkbox" name="skills[]" value="ruby_on_rails">ruby_on_rails<br>
</td>
controller
<?php
public function insert(){
if ($this->input->post('add')==true)
{
$student = array( 'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'skills' => $this->input->post(json_encode(skills)),
'notes' => $this->input->post('notes'),
'gender' => $this->input->post('gender') );
$result = $this->Student_info_model->insertStudent($student);
if($result==true){
echo "inserted";
}
else {
echo "Not Inserted";
}
}
}
?>
model
function insertStudent($student){
$this->db->insert('student_info_table', $student); // insert data into "student_info_table" table`
if ($this->db->affected_rows() > 0) {
return true;
}
else {
return false;
}
}
error
Error Number: 1048
Column 'skills' cannot be null
INSERT INTO `student_info_table` (`name`, `email`, `skills`, `notes`, `gender`) VALUES ('gailyn', 'quentin#gmail.com', NULL, 'dsas', 'male')
Filename: C:/xampp/htdocs/codeigniter/system/database/DB_driver.php
Line Number: 691

As far as i understand you want to get the array of skills from the http request and then to encode it and save it to your database. For that please use json_encode($this->input->post('skills') instead of $this->input->post(json_encode(skills)), so you first get the data, and then apply the json encoding over it.

Try with this : json_encode($this->input->post('skills')) You need to get the value of skills using input post and then need to convert it using json_encode

Related

Tabulator - How can I delete a row from JSON file?

I am using Tabulator to create a table. I import information from JSON file using ajaxURL: "test.json". Data all loads fine. I have created a form to enter data into. When submitted, it goes to a PHP file that processes the data (decodes test.json, adds form data, encodes to json). Everything works fine until I try to implement a way of deleting. I have tried a few ways and none of them work. One way would create nested arrays within my json array and Tabulator will not read that. I want to be able to click the buttonCross in my Delete column and delete the row from the table and from the JSON file.
Is there anyway do delete JSON file elements without nesting arrays?
tabulator.html
<form action="process.php" method="POST">
Name:
<input type="text" name="name">
Description:
<input type="text" name="descript">
<br><br>
Latitude:
<input type="text" name="lat">
Longitude:
<input type="text" name="lon">
<br><br>
Start Date/Time:
<input type="date" name="startDate">
<input type="time" name="startTime">
<br><br>
End Date/Time:
<input type="date" name="endDate">
<input type="time" name="endTime">
<br><br>
<input type="hidden" name="deleteStatus" value="">
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
//later in the file
columns:[ //define the table columns
{title:"Delete", field:"deleteStatus", formatter:"buttonCross", width:50, align:"center", headerSort:false, cellClick:function(e, cell){
if(confirm('Are you sure you want to delete this entry?')) {
cell.setValue("delete");
var row = cell.getRow();
$.ajax({
url: 'process.php',
method: 'post',
data: {row},
});
}
}},
process.php
<?php
$myFile = "test.json";
$arr_data = array(); // create empty array
$time = date("YmdHis");
try
{
//Get form data
$formdata = array(
'id'=> $time,
'deleteStatus'=> $_POST['deleteStatus'],
'name'=> $_POST['name'],
'descript'=> $_POST['descript'],
'lat'=> $_POST['lat'],
'lon'=> $_POST['lon'],
'startDate'=> $_POST['startDate'],
'startTime'=> $_POST['startTime'],
'endDate'=> $_POST['endDate'],
'endTime'=> $_POST['endTime'],
);
//Get data from existing json file
$jsondata = file_get_contents($myFile);
// converts json data into array
$arr_data = json_decode($jsondata, true);
// Push user data to array
array_push($arr_data,$formdata);
foreach($arr_data as $elementKey => $element) {
foreach($element as $valueKey => $value) {
if($valueKey == 'deleteStatus' && $value == 'delete'){
//delete this particular object from the $array
unset($arr_data[$elementKey]);
}
}
}
//Convert updated array to JSON
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
//write json data into data.json file
if(file_put_contents($myFile, $jsondata)) {
header("Refresh:0; url = tabulator.html");
}
else
echo "error";
}
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
Check documentation you need to call an API ( like node.js) to which deletes form the json file
table.deleteRow(15)
.then(function(){
//Call your api to delete from JSON file
})
.catch(function(error){
//handle error deleting row
});
row.delete()
.then(function(){
//run code after row has been deleted
})
.catch(function(error){
//handle error deleting row
});

How can i solve my codeigniter batch update problem?

Hello guys I just want to ask in my project there are three tables product, color and product_color.I insert database using insert_batch then it work fine, when i update product_color table using update_batch then face some problems.Here's my sample code:
Database:
product:id,name,sku...
color:id,color_name
product_color:id,pro_id,color_id
Input Form:
<?php foreach($colors as $color): ?>
<input type="checkbox" class="form-check-input" name="color[]" value="<?php echo $color->color_id; ?>" <?php foreach ($productcolor as $key => $value){ $array[] = $value->color_id;} if(in_array($color->color_id,$array)) echo 'checked'; else ''; ?>>
<label class="form-check-label">
<?php echo $color->color_name; ?>
</label>
<?php endforeach; ?>
Actually i want to pass primary id from product_color table.Here i pass color_id.Have any way to pass primary id from input form;
Here Is my Controller:
$colorBatch = array();
foreach ($color as $colorvalue) {
$colorBatch[] = array(
'id'=>$id
'pro_id' =>$pid,
'color_id' => $colorvalue
);
}
$this->db->update_batch('product_color', $colorBatch,'pro_id');
Where $pid contains product_id;
Is it possible to pass product_color table primary id from input form or Have any better solution to solve this.Sorry for bad english.
Thanks
Please check below code as your array structure is wrong;
$colorBatch = array();
foreach ($color as $key => $colorvalue) {
$colorBatch[$key] = array(
'id'=>$id
'pro_id' =>$pid,
'color_id' => $colorvalue
);
}
$this->db->update_batch('product_color', $colorBatch,'pro_id');

How to display cakephp 2.5.3 model validation message.By default it shows html 5 validation message

How to display the validation message which is defined in CakePHP model.When I submit the form , CakePHP model validation works.But validation message for input field is not displayed. It shows HTML 5 validation Message. I want to display CakePHP model validation message. I am using CakePHP 2.5.3
Following is my code block:
Controller:
$this->User->set($this->request->data);
if ($this->User->validates()) {
if ($this->User->save($this->request->data)) {
$Email->send();
$this->Session->setFlash(__('The user has been created'));
if ($this->Auth->login()) {
$this->Session->setFlash(__('Welcome, ' . $this->Auth->user('username')));
$this->redirect($this->Auth->redirectUrl());
}
} else {
$this->Session->setFlash(__('The user could not be created. Please, try again.'));
}
}
Model:
public $validate = array(
'username' => array(
'nonEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required',
'allowEmpty' => false
),
'unique' => array(
'rule' => array('isUniqueUsername'),
'message' => 'This username is already in use'
),
'alphaNumericDashUnderscore' => array(
'rule' => array('alphaNumericDashUnderscore'),
'message' => 'Username can only be letters, numbers and underscores'
),
)
View:
<div id="divfirstname" class="input text required">
<label for="UserFirstname">First Name <span style="color:#FF0000">*</span></label>
<?php echo $this->Form->text('firstname');?>
</div>
<div id="divlastname" class="input text required">
<label for="UserLastname">Last Name <span style="color:#FF0000">*</span></label>
<?php echo $this->Form->text('lastname');?>
</div>
<div class="input text required">
<label for="UserUsername">Username <span style="color:#FF0000">*</span></label>
<?php echo $this->Form->text('username');?>
</div>
You don't need to wrap the validation-block around your save call.
So this is enough:
if ($this->User->save($this->request->data)) {
$Email->send();
$this->Session->setFlash(__('The user has been created'));
if ($this->Auth->login()) {
$this->Session->setFlash(__('Welcome, ' . $this->Auth->user('username')));
$this->redirect($this->Auth->redirectUrl());
}
} else {
$this->Session->setFlash(__('The user could not be created. Please, try again.'));
}
CakePHP handles automatically the validation when Model->save() is called and displays the error under your input fields. So if $this->save fails because of a validation error, cakephp adds <div class="error-message">Message Text from your model validation array</div> under the right input field.
You are left with 2 options :
Either dont use validation rule in cakePHP which validates on Client side.
On DOM ready , call $("#formId").removeAttr('novalidate'); Like
$(document).ready(function(){
$("#formId").removeAttr('novalidate');
});

Codeigniter - Input post array insert into mysql database

I dont understand how to exactly insert a row into a MySQL table. If I use my code, I add a new row for every post. Rather than that, I want only one row with all the values.
Here is the code sample.
HTML:
echo form_open('account/update');
echo "<p><label for='gender'>Gender</label>
<input type='text' name='gender' id='gender' value='".$gender."' />
</p>
<p>
<label for='age'>Age</label>
<input type='text' name='age' id='age' value='".$age."' />
</p>
<p>
<label for='bio'>Biografie</label>
<input type='text' name='bio' id='bio' value='".$bio."' />
</p>
<p>
<label for='skills'>Skills</label>
<input type='text' name='skills' id='skills' value='".$skills."' />
</p>
<p><input type='submit' value='Save' /></p>";
echo form_close();
Controller:
function update()
{
$userid = $this->session->userdata("userid");
$datanew = array(
'userid' => $this->session->userdata("userid"),
'gender' => $this->input->post('gender'),
'age' => $this->input->post('age'),
'bio' => $this->input->post('bio') ,
'skills' => $this->input->post('skills')
);
$this->session->set_userdata($data);
$this->load->model('model_account');
$this->load->model("model_user");
$this->model_account->profile_insert($datanew);
$this->load->view("change_avatar");
redirect("account/show/".$this->session->userdata("userid"));
}
Model:
function profile_insert($datanew)
{
$this->db->insert('profile', $datanew);
}
I get 5 rows if I submit the HTML form.
This works for me:
I Set the userid to unique and made a if statement in the controller ti switch between a insert and update function.
Controller:
function update()
{
$datanew = array(
'userid' => $this->session->userdata("userid"),
'gender' => $this->input->post('gender'),
'age' => $this->input->post('age'),
'bio' => $this->input->post('bio') ,
'skills' => $this->input->post('skills')
);
$exists = $this->db->select('profile')->where('userid', $this->session->userdata("userid"));
if($exists)
{
$this->session->set_userdata($datanew);
$this->load->model('model_account');
$this->load->model("model_user");
$this->model_account->profile_update($datanew);
$this->load->view("change_avatar");
redirect("account/show/".$this->session->userdata("userid"));
}
else
{
$this->session->set_userdata($datanew);
$this->load->model('model_account');
$this->load->model("model_user");
$this->model_account->profile_insert($datanew);
$this->load->view("change_avatar");
redirect("account/show/".$this->session->userdata("userid"));
}
}
model:
function profile_insert($datanew)
{
$this->db->insert('profile', $datanew);
}
function profile_update($datanew)
{
$this->db->update('profile', $datanew);
}
Thanks for helping me

sql 'shows' array on some columns

I have some basic code which collects chkbox & radio buttons yes/no answers etc. from a form and stores in mysql but some of the mysql submissions work (ie puts yes or no in the sql column) but some just show in sql column as 'array' - this is a sample of the code. $repeat shows as 'array' where as $inter shows as yes or no. The columns in mysql are identical in structure the form HTML is the same syntax for both, the $_POST arrays are comma separated as I also email the values and the email displays the answers correctly - this is just odd
<?php
$repeat = "";
foreach ($_POST['repeat'] as $key => $value) {
$repeat.= ",$value ";
}
$repeat = substr($repeat,1);
$inter = "";
foreach ($_POST['intermitant'] as $key => $value) {
$inter.= ",$value ";
}
$inter = substr($inter,1);
//other posts all looped though etc
//then the sql - log on etc
$sql="INSERT INTO faults (repeat_visit,intermitant) VALUES ('$repeat','$inter')";
This is the HTML - Nothing odd about it that I can see, I get what you describe above - but why does one work and the other not with the same code, the same method is applied to checkboxes and some wiork fine other put 'array' in sql
<label>Repeat Visit:</label>
<input type="radio" name="repeat[]" value="Yes" />Yes
<input type="radio" name="repeat[]" value="No" />No
<label>Intermitant Fault:</label>
<input type="radio" name="intermitant[]" value="Yes" />Yes
<input type="radio" name="intermitant[]" value="No" />No
As popnoodles stated, seeing the form's HTML would help, but this looks as if each element in $_POST['repeat'] & $_POST['intermitant'] is actually an array, and so the $value of the foreach() is returning "Array"
Check that the checkbox array is only 1 dimensional, and if it is not, does it have to be multi-dimensional?
If so, perhaps a recursive function or nested loop to implode the values is required
$repeat = "";
foreach ($_POST['repeat'] as $k => $v)
{
foreach ($v as $kInner => $vInner)
{
$repeat .= ",$vInner ";
}
}