I have json input as mentioned below am decoding the the json response and inserting it into the mysql database,Now am converting this into Codeigniter I am not able to understand how to write the controller and the model for the below code,Please let me know how to write the controller and model, also am providing the controller and model which is written by me
PHP Code
<?php
include ('config.php');
// read json file
date_default_timezone_set('Asia/Kolkata');
$timestamp = time();
$date_time = date("Y-m-d H:i:s", $timestamp);
$createdon = $date_time;
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// $filename = 'employee.json';
// $json_data = file_get_contents($filename);
$json_data = $_POST['QUESTION'];
//convert json object to php associative array
$data = json_decode($json_data, true);
// print_r($data);
if (is_array($data) || is_object($data)) {
$jsonData = $data['DATA'];
$jsonAnswers = $data['ANSWERS'];
$drcode = $data['DATA']['DRCODE'];
$divcode = $data['DATA']['DIVCODE'];
$brdcode = $data['DATA']['BRDCODE'];
$prdcode = $data['DATA']['PRDCODE'];
// echo $drmobile." -- ";
for ($i = 0;$i < sizeof($data['ANSWERS']);$i++) {
$quecode[$i] = $data['ANSWERS'][$i]['ADCODE'];
$answer[$i] = $data['ANSWERS'][$i]['ANSWER'];
$quecodes = $quecode[$i];
$answers = $answer[$i];
// echo $quecode[$i]." <--> ".$answer[$i]."<br/>";
$sql = "INSERT INTO ANSWERS(DRCODE,ADCODE,DIVCODE,BRDCODE,PRDCODE,ANSWERS,CREATEDON)VALUES ('$drcode', '$quecode[$i]', '$divcode', '$brdcode', '$prdcode', '$answer[$i]', '$createdon')";
$qur = mysql_query($sql);
if ($qur) {
$json = array("status" => 1, "msg" => "Data added Successfully!");
} else {
$json = array("status" => 2, "msg" => "Already Submitted");
}
}
// echo "<br/>-----------<br/>";
}
} else {
$json = array("status" => 0, "msg" => "Request method not accepted");
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
//close connection
?>
Json Input
{
"DATA": {
"DRCODE": "D40504",
"DIVCODE": 1,
"BRDCODE": 5,
"PRDCODE": 5
},
"ANSWERS": [{
"ADCODE": 1,
"ANSWER": "VERY GOOD"
}, {
"ADCODE": 2,
"ANSWER": "GOOD"
}, {
"ADCODE": 3,
"ANSWER": "SGH"
}, {
"ADCODE": 4,
"ANSWER": "NO"
}, {
"ADCODE": 5,
"ANSWER": "NO"
}, {
"ADCODE": 6,
"ANSWER": "CGHJ"
}]
}
Controller
public function feedback_post() {
$json_data = $this->post('QUESTION');
$data = $this->json_decode($json_data, true);
if (is_array($data) || is_object($data)) {
$jsonData = $this->$data['DATA'];
$jsonAnswers = $this->$data['ANSWERS'];
$drcode = $this->$data['DATA']['DRCODE'];
$divcode = $this->$data['DATA']['DIVCODE'];
$brdcode = $this->$data['DATA']['BRDCODE'];
$prdcode = $this->$data['DATA']['PRDCODE'];
for ($i = 0;$i < sizeof($data['ANSWERS']);$i++) {
$quecode[$i] = $this->$data['ANSWERS'][$i]['ADCODE'];
$answer[$i] = $this->$data['ANSWERS'][$i]['ANSWER'];
$quecodes = $this->$quecode[$i];
$answers = $this->$answer[$i];
}
$insert_array = array('DRCODE' => $drcode, 'DIVCODE' => $divcode, 'BRDCODE' => $speciality, 'PRDCODE' => $prdcode, 'ANSWER' => $answers, 'ADCODE' => $quecodes);
$feedback_data = $this->Rest_user_model->feedbacksubmission($insert_array);
if ($feedback_data) {
$message = ['status' => 1,
// 'result' => array(),
'message' => 'Feedback Submitted Successfully'];
} else {
$message = ['status' => 2,
// 'result' => array(),
'message' => 'Feedback Submitted Successfully'];
}
$this->set_response($message, REST_Controller::HTTP_OK);
}
}
try this
public function feedback_post()
{
$objDate = new DateTime();
$data = json_decode($this->input->post('QUESTION'), true);
if (is_array($data))
{
foreach($data['ANSWERS'] AS $arrAnswer)
{
$arrInsertData =
[
'DRCODE' => $data['DATA']['DRCODE'],
'DIVCODE' => $data['DATA']['DIVCODE'],
'BRDCODE' => $data['DATA']['BRDCODE'],
'PRDCODE' => $data['DATA']['PRDCODE'],
'ADCODE' => $arrAnswer['ADCODE'],
'ANSWERS' => $arrAnswer['ANSWER'],
'CREATEDON' => $objDate->format('Y-m-d H:i:s'),
];
$feedback_data = $this->Rest_user_model->feedbacksubmission($arrInsertData);
$message = ($feedback_data) ? ['status' => 1, 'message' => 'Feedback Submitted Successfully'] : ['status' => 2, 'message' => 'Already Submitted'];
}
}
else
{
$message = ["status" => 0, "msg" => "Request method not accepted"];
}
$this->set_response($message, REST_Controller::HTTP_OK);
}
this is pretty much basic understanding of php - but you've to ask yourself - if you've multiple answers - what happens if one fails and one is successful ?
Because your sample php code is simply wrong...
Related
Have a nice day. I have created the following basics:
{
"1111": {
"h264": {
"url": "TEST",
"expire": 1649453177
}
}
}
I need to add the following lines to the same key:
{
"1111": {
"h264": {
"url": "TEST",
"expire": 1649453177
},
"h265": {
"url": "TEST",
"expire": 1649456380
}
}
}
But whatever I try, it does this to me:
{
"1111": {
"h264": {
"url": "TEST",
"expire": 1649453177
},
"0": {
"h265": {
"url": "TEST",
"expire": 1649456380
}
}
}
}
Here is some sample code:
$time = time();
$codec = "h265";
$url = "TEST";
$id = "1111";
$data = json_decode(file_get_contents('./data.json'), true);
$post_data = array($codec => array('url' => $last_line,'expire' => $time));
array_push($data[$id], $post_data);
$data = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
file_put_contents('./data.json', $data);
Can someone advise me not to add the 0 key to me there
Change:
$post_data = array($codec => array('url' => $last_line,'expire' => $time));
array_push($data[$id], $post_data);
To:
$post_data = array($codec => array('url' => $last_line,'expire' => $time));
$data[$id]['h265'] = $post_data;
I'm decoding a json file using php.
In foreach statement I check if my cd_driver is in the array coming from the json file content. If it's in the array the script updates its month as expected. If not, the script writes the new driver into the json file.
Everything works fine but it's also executing the else condition after updating its month and adding the same driver to the json file. Why is this happening?
$dados[] = array('cd_driver' => $cd_driver, 'Driver' => $RSx["ds_name"], 'month' => $cd_month, 'bsaldo' => $saldoToJson);
$dados2 = array('cd_driver' => $cd_driver, 'Driver' => $RSx["ds_name"], 'month' => $cd_month, 'bsaldo' => $saldoToJson);
$jsonString = file_get_contents('bsaldo.json');
$data = json_decode($jsonString, true);
if($data == ""){
$newString = json_encode($dados);
file_put_contents('bsaldo.json', $newString);
}else {
foreach ($data as $key => $value) {
$mot = $value['cd_driver'];
$array = array();
array_push($array, $mot);
if(in_array($cd_driver, $array)){
$data[$key]['month'] = $cd_month;
$newString = json_encode($data);
file_put_contents('bsaldo.json', $newString);
}else {
array_push($data, $dados2);
$finalString = json_encode($data);
file_put_contents('bsaldo.json', $finalString);
}
}
}
json:
[
{
"cd_driver": "11831",
"Driver": "ADENILSON RODRIGUES DE SOUZA",
"month": "02",
"bsaldo": -903
},
{
"cd_driver": "11835",
"Driver": "EDIVAN DE CASTRO VASSALO",
"month": "01",
"bsaldo": -7670
},
{
"cd_driver": "11831",
"Driver": "ADENILSON RODRIGUES DE SOUZA",
"month": "02",
"bsaldo": -903
},
{
"cd_driver": "11831",
"Driver": "ADENILSON RODRIGUES DE SOUZA",
"month": "02",
"bsaldo": -903
}
]
I had to adapt some things to work with php 5.1.
Your problem is that you are resetting the array on each iteration of the loop. Move it outside of the foreach, like so:
$dados[] = array('cd_driver' => $cd_driver, 'Driver' => $RSx["ds_name"], 'month' => $cd_month, 'bsaldo' => $saldoToJson);
$dados2 = array('cd_driver' => $cd_driver, 'Driver' => $RSx["ds_name"], 'month' => $cd_month, 'bsaldo' => $saldoToJson);
$jsonString = file_get_contents('bsaldo.json');
$data = json_decode($jsonString, true);
if($data == ""){
$newString = json_encode($dados);
file_put_contents('bsaldo.json', $newString);
}else {
$array = array(); # here it won't be continually reset and can accumulate values as intended.
foreach ($data as $key => $value) {
$mot = $value['cd_driver'];
array_push($array, $mot);
if(in_array($cd_driver, $array)){
$data[$key]['month'] = $cd_month;
$newString = json_encode($data);
file_put_contents('bsaldo.json', $newString);
}else {
array_push($data, $dados2);
$finalString = json_encode($data);
file_put_contents('bsaldo.json', $finalString);
}
}
}
I want import an List in csv format, with seperator, from an Textarea to my MySQL Database.
But it always failed, also if its in the correct format.
Input Text:
Thomas|Maier|5778011152|Bahnweg|232
PHP Code:
<?php
if(isset($_POST["base_name"]) && isset($_POST["new_entry"])) {
$myList = preg_replace("/\r|\n/", "", preg_split("/$\R?^/m", $_POST["new_entry"]));
foreach($myList as $info) $csv[] = explode($_POST["separator"], $info);
$csvParams = $csv[0];
array_shift($csv);
$success = 0;
$total = 0;
foreach($csv as $info) {
$sqlInsert = array_combine($csvParams, $info);
$sqlInsert["base"] = $_POST["base_name"];
$sqlInsert["info"] = "unbenutzt";
$p = softwareInsertArray($softwareSqlLink, $sqlInsert, "person");
if($p) $success++;
$total++;
}
$q = softwareRunQuery($softwareSqlLink, false, "INSERT INTO statistics (`key`, `val`) VALUES ('".$_POST["base_name"]."|profit', '0');");
}
if(isset($total)) {
if($total == $success && $total > 0 && $q) {
$alert = array("type" => "success", "header" => "Erfolgreich!", "text" => "Success.");
softwareSqlLog($softwareSqlLink, "person", array("status" => 1, "info" => array("base" => $_POST["base_name"], "text" => $success." person added successfully")));
} else {
$alert = array("type" => "danger", "header" => "Fehler!", "text" => $success."/".$total." sucess.");
softwareSqlLog($softwareSqlLink, "person", array("status" => 0, "info" => array("base" => $_POST["base_name"], "text" => $success."/".$total." added.")));
}
}
?>
If comes always 0 added = Nothing Uploaded. Anyone an Idea?
Thanks
I want import an input List in csv format, with separator (|), from an Textarea to my MySQL Database.
But it always failed, also if its in the correct format.
It comes the message: Error, 0 added successfully.
My format:
Thomas|Maier|5778011152|Bahnweg|232
Any one an Idea?
if(isset($_POST["base_name"]) && isset($_POST["new_entry"])) {
$myList = preg_replace("/\r|\n/", "", preg_split("/$\R?^/m", $_POST["new_entry"]));
foreach($myList as $info) $csv[] = explode($_POST["separator"], $info);
$csvParams = $csv[0];
array_shift($csv);
$success = 0;
$total = 0;
foreach($csv as $info) {
$sqlInsert = array_combine($csvParams, $info);
$sqlInsert["base"] = $_POST["base_name"];
$sqlInsert["info"] = "unbenutzt";
$p = softwareInsertArray($softwareSqlLink, $sqlInsert, "person");
if($p) $success++;
$total++;
}
$q = softwareRunQuery($softwareSqlLink, false, "INSERT INTO statistics (`key`, `val`) VALUES ('".$_POST["base_name"]."|profit', '0');");
}
if(isset($total)) {
if($total == $success && $total > 0 && $q) {
$alert = array("type" => "success", "header" => "Erfolgreich!", "text" => "Success.");
softwareSqlLog($softwareSqlLink, "person", array("status" => 1, "info" => array("base" => $_POST["base_name"], "text" => $success." person added successfully")));
} else {
$alert = array("type" => "danger", "header" => "Fehler!", "text" => $success."/".$total." sucess.");
softwareSqlLog($softwareSqlLink, "person", array("status" => 0, "info" => array("base" => $_POST["base_name"], "text" => $success."/".$total." added.")));
}
}
softwareInsertArray code: pastebin.com/raw/vUnQTpxU
Do you just want to replace the pipes with commas?
IE SELECT replace('Thomas|Maier|5778011152|Bahnweg|232','|', ',' )
I have two tables order and orderDetail. i have multiple delivery address in order detail table based on id of order table
i want to display id from order table and deliveryAddress from order detail table.i am getting below output when i print..
but unable to display delivery_address.please anyone can suggest how i display delivery_address..
{
"responseData": {
"status": 1,
"message": "",
"result": [
{
"Order": {
"id": "677",
"detail_location_instructions": "Near Inox"
},
"OrderDetail": [
{
"order_id": "677",
"delivery_address": "Smart Club Gimnasio - Avenida Álvarez Thomas, Buenos Aires, Autonomous City of Buenos Aires, Argentina"
},
{
"order_id": "677",
"delivery_address": "Lower Fort Street, Dawes Point, New South Wales, Australia"
}
]
},
{
"Order": {
"id": "680"
},
"OrderDetail": []
},
{
"Order": {
"id": "684"
},
"OrderDetail": [
{
"order_id": "684",
"delivery_address": "Four Seasons - Posadas"
}
]
}
]
}
}
below is my code
public function getOrderlist(){
if($this->processRequest){
$err = false;
if(empty($this->requestData['id'])){
$this->responceData['message'] = "Please provide User ID";
$err = true;
}
if(!$err){
$id = trim($this->requestData['id']);
$conditions = array('Order.user_id'=>$id);
$data = $this->Order->find('all',array('conditions'=>$conditions));
if(!empty($data)){
$c = array();
foreach ($data as $key => $value) {
$c[] = array(
'Id' => $value['Order']['id'],
'deliveryAddress' => $value['OrderDetail']['delivery_address']
);
}
}
$this->responceData['result'] = $c;
$this->responceData['status'] = 1;
}
}
}
You have to put the deliveryAddress in array
$c = array();
foreach ($data as $key => $value) {
$myOrders = [
'Id'=>$value['Order']['id'],
'deliveryAddress'=>[]
];
foreach($value['OrderDetail'] as $address){
$myOrders['deliveryAddress'][] = $address['delivery_address'];
}
$c[] = $myOrders;
}
Hope this will help
can you trying below code.
foreach ($data as $key => $value) {
$c[] = array(
'Order' => array(
'id'=>$value['Order']['id'],
'detail_location_instructions' => $value['Order']['detail_location_instructions'],
),
'OrderDetail' => array(
'order_id'=>$value['Order']['id'],
'deliveryAddress' => $value['OrderDetail']['delivery_address'],
),
)
}
There is cases where you dont get the delivery address, in that case, you need to check if it exists first. use the Hash utility for that purpose.
I transformed the data to an array, in order for the class Hash to work.
public function getOrderlist(){
if($this->processRequest){
$err = false;
if(empty($this->requestData['id'])){
$this->responceData['message'] = "Please provide User ID";
$err = true;
}
if(!$err){
$id = trim($this->requestData['id']);
$conditions = array('Order.user_id'=>$id);
$data =(array) $this->Order->find('all',array('conditions'=>$conditions));
if(!empty($data)){
$c = array();
foreach ($data as $key => $value) {
$c[] = array(
'Id' => Hash::get($value, 'Order.id'),
'deliveryAddress' => current(Hash::extract($value, 'OrderDetail.{n}.delivery_address', array()))
);
}
}
$this->responceData['result'] = $c;
$this->responceData['status'] = 1;
}
}
}