Post data using php - php

I made a API to fetch and store data, I can fetch data without problem, but everything changes when I try to store data, when I send the data it returns [{"success":"0"}]. In the beginning it worked well, used accepted to store data, but suddenly everything changed. I've tried everything, compare the new with the old, changed the code, tables, but even so it always returns [{"success":"0"}] after comparing both (old and new) code I couldn't see much difference. What could I be doing wrong?
Insert data:
function insertloin()
{
if(isset($_POST["loincode"]))
{
$form_data = array(
':loincode' => $_POST["loincode"],
':code' => $_POST["code"],
':specie' => $_POST["specie"],
':grade' => $_POST["grade"],
':vesselname' => $_POST["vesselname"],
':type' => $_POST["type"],
':productformat' => $_POST["productformat"],
':dateprocessed' => $_POST["dateprocessed"],
':datebb' => $_POST["datebb"],
':projectcode' => $_POST["projectcode"],
':netweight' => $_POST["netweight"],
':producttype' => $_POST["producttype"],
':oldoc' => $_POST["oldoc"]
);
$query = "
INSERT INTO loins
(loincode, code, specie, grade, vesselname, type, productformat, dateprocessed, datebb, projectcode, netweight, producttype, oldoc) VALUES
(:loincode, :code, :specie, :grade, :vesselname, :type, :productformat, :dateprocessed, :datebb, :projectcode, :netweight, :producttype, :oldoc)
";
$statement = $this->connect->prepare($query);
if($statement->execute($form_data))
{
$data[] = array(
'success' => '1'
);
}
else
{
$data[] = array(
'success' => '0'
);
}
}
else
{
$data[] = array(
'success' => '0'
);
}
return $data;
}
Test:
if($_GET["action"] == 'insertloin')
{
$data = $api_object->insertloin();
}
Action:
if(isset($_POST["action"]))
{
if($_POST["action"] == 'insertloin')
{
$form_data = array(
'loincode' => $_POST["loincode"],
'code' => $_POST["code"],
'specie' => $_POST["specie"],
'grade' => $_POST["grade"],
'vesselname' => $_POST["vesselname"],
'type' => $_POST["type"],
'productformat' => $_POST["productformat"],
'dateprocessed' => $_POST["dateprocessed"],
'datebb' => $_POST["datebb"],
'projectcode' => $_POST["projectcode"],
'netweight' => $_POST["netweight"],
'producttype' => $_POST["producttype"],
'oldoc' => $_POST["oldoc"]
);
$api_url = "http://192.168.85.160/API/v2/api/test_api.php?action=insertloin";
$client = curl_init($api_url);
curl_setopt($client, CURLOPT_POST, true);
curl_setopt($client, CURLOPT_POSTFIELDS, $form_data);
curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($client);
curl_close($client);
$result = json_decode($response, true);
foreach($result as $keys => $values)
{
if($result[$keys]['success'] == '1')
{
echo 'insert';
}
else
{
echo 'error';
}
}
}
Please, help me find the bug.
Kind regards,
Abd

When $statement->execute() returns a false value it means your SQL had some sort of error. But you ignore that false value and instead return the same success status in both your if and your else clause.
To see your error codes try something like this:
if($statement->execute($form_data))
{
$data[] = array(
'success' => '1'
);
}
else
{
echo $statement->errorInfo();
print_r ( $statement->errorInfo() );
die(1);
}
You'll need to look at the error codes you get to see what's wrong and then do something smarter than echo / print_r / die.

Related

getting multiple customer details In codeigniter

i have written this code to receive data from the Android device. it was inserted just one customer data I need to receive multiple customer details if app goes offline. but it was inserting one data into DB in offline mode also.how can i change this for multiple customer data insertions.
function index_post($customerID = false) {
if ($customerID) {
//update the record
$updateData = array();
$allowedparams = array('streetid' => 'streetid', 'name' => 'name', 'mobile' => 'mobile', 'adhaar' => 'adhaar', 'profession' => 'profession', 'address' => 'address', 'pincode' => 'pincode', 'nearby' => 'nearby', 'paddress' => 'paddress', 'isOwned' => 'isOwned');
foreach ($allowedparams as $k => $v) {
if (!$this->IsNullOrEmptyString($this->post($k, true))) {
$updateData[$v] = $this->post($k, true);
}
}
if ($this->model_customer->update($customerID, $updateData)) {
$data = array('status' => true, 'messsage' => 'cusotmer updated succesfully');
$http_code = REST_Controller::HTTP_OK;
} else {
$data = array('status' => false, 'messsage' => 'cusotmer failed to update.');
$http_code = REST_Controller::HTTP_INTERNAL_SERVER_ERROR;
}
} else {
//insert the record
$allowedparams = array('streetid' => 'streetid', 'name' => 'name', 'mobile' => 'mobile', 'adhaar' => 'adhaar', 'profession' => 'profession', 'address' => 'address', 'pincode' => 'pincode', 'cycle' => 'cycle', 'nearby' => 'nearby', 'paddress' => 'paddress', 'isOwned' => 'isOwned');
$requiredParam = array('streetid', 'name', 'mobile', 'cycle');
$insertdata = array();
foreach ($allowedparams as $k => $v) {
if (in_array($k, $requiredParam)) {
//check if its not null
if ($this->post($k) == null || trim($this->post($k)) == '') {
$data = array('status' => false, 'message' => $k . ' parameter missing or empty');
$http_code = REST_Controller::HTTP_BAD_REQUEST;
break;
}
}
$insertData[$v] = $this->post($k, true);
}
if ($customerID = $this->model_customer->create($insertData)) {
$data['customerID'] = $this->_frameCustomer2($this->model_customer->get($customerID)); //you need to put
$http_code = REST_Controller::HTTP_OK;
} else {
$data = array('status' => false, 'message' => 'unable to create customer');
$http_code = REST_Controller::HTTP_INTERNAL_SERVER_ERROR;
}
}
$this->response($data, $http_code);
}
private function _frameCustomer2($c) { //get value from index_get
$data = array();
$data['id'] = $c->id;
$data['name'] = $c->name;
$data['street'] = array('id' => $c->streetid);
$data['creationDate'] = $c->creationdate;
$data['mobile'] = $c->mobile;
$data['adhaar'] = $c->adhaar;
$data['profession'] = $c->profession;
$data['isOwned'] = ($c->isOwned == 1) ? true : false;
$data['address'] = $c->address;
$data['pincode'] = $c->pincode;
$data['status'] = $c->status;
$data['cycle'] = $c->cycle;
$data['balance'] = $c->balance;
$data['creditAvailable'] = $c->creditbalance;
$data['nearby'] = $c->nearby;
$data['accountNumber'] = $c->accountnumber;
$data['permanentAddress'] = $c->paddress;
$data['lastVisit'] = $this->model_customer->lastVisit($c->id);
return $data;
}
and my part of model function is
function create($insertdata = array()) { //new customer insert
if ($this->db->insert('customer', $insertdata)) {
return $this->db->insert_id();
} else {
return false;
}
}
function update($customerID = 0, $updateData = array()) {
$this->db->where('id', $customerID);
if ($this->db->update('customer', $updateData) && $this->db->affected_rows() == 1) {
return true;
} else {
return false;
}
Instead of customer Id, you can ask the mobile developers to send data in the form of array. In both online and offline. In case of online there will be just one element in the request array.
function index_post() {
$request_data = $this->request->body;
foreach($request_data as $key => $value)
{
//Check if customer id is present
if(Customer present)
{
Update the record
} else {
Insert the record
}
}
}

Magento select query not looping properly using a foreach loop

I have written following code:
try {
$json = array('success' => true);
$read = $this->read;
$readresult = $read->fetchAll("SELECT * FROM brand");
foreach($readresult as $r) {
$json['brands'][] = array(
'id' => $r['brand_id'],
'name' => $r['name'],
'description' => $r['description'],
);
}
return $json;
} catch (Exception $e) {
$message = $e->getMessage();
echo json_encode(array("status" => "500", "error" => $message));
}
In this code I am trying to display all the brand records from the database table.
But the problem is when I am trying to output the result the it is only displaying one record.
Can anyone please check what is the problem.
The output of the code above is:
{
"success":true,
"products":[
{
"id":"4",
"name":"Test",
"href":"http:\/\/localhost:8‌​1\/magento\/index.php\/catalog\/product\/view\/id\/4\/",
"thumb":"http:\/\/localho‌​st:81\/magento\/media\/catalog\/product\/cache\/0\/thumbnail\/9df78eab33525d08d6e‌​5fb8d27136e95\/images\/catalog\/product\/placeholder\/thumbnail.jpg",
"pirce":"$11‌​1,111.00"
}
]}
try like this,
$json['brands'] = array();
foreach($readresult as $r) {
$brand = array(
'id' => $r['brand_id'],
'name' => $r['name'],
'description' => $r['description'],
);
array_push($json['brands'],$brand);
}

Zabbix Reading the Api

I'm getting Informations from the Zabbix Api with a PHP library. At the moment I get the "lastvalue" from the json Array:
try {
// connect to Zabbix-API
$api = new ZabbixApi($api_url, $username, $password);
$params = array(
'groupids' => '2',
'real_items' =>TRUE,
'monitored_items' =>TRUE,
'search' => array('name' => 'Disk root used p'),
'selectFunctions' => 'extend',
'output' => 'extend',
'sortfield' => 'name',
'limit' => '1'
);
$trends = $api->itemGet($params); // get data from api
$names = array();
foreach($trends as $trend) { // loop through the returned data
$names[] = $trend->lastvalue;
}
//print_r($names);
} catch(Exception $e) {
// Exception in ZabbixApi catched
echo $e->getMessage();
}
But now I want to get the "lastvalue" plus the "name" of the Item in this Array for example like that: "name"+"lastvalue". How can I get both of them into my array $names[]?
Here is my answer from my comments, hope its what you are looking for!
$trends = $api->itemGet($params);
$names = array();
foreach($trends as $trendKey => $trendValue)
{
$names[$trendKey] = $trendValue;
}
#Test the names array
foreach ($names as $nameKey => $nameValue)
{
print("{$nameKey} = {$nameValue}<br />");
}
Return value:
groupids = 2
real_items = TRUE
...
sortfield = name
limit = 1

Solr FieldCollapsing for More Like This queries

I want to use a "More Like This" query to find similar documents and collapse those that have the same value for the field 'image'. I tried to use the Field Collapsing parameters however they do not seem to work for "More like this".
Below is a snippet of my code. Can you tell me how to collapse results using the "More Like This" query?
$url = "http://{$host}:{$port}/solr/{$core}/mlt";
$data = [
'stream.body' => $content,
'fl' => 'image,content,title,signature',
'start' => 0,
'order' => "score desc",
'wt' => 'json',
'mlt.fl' => 'content,title',
// these lines do nothing ---v
'group' => 'true',
'group.field' => 'image',
'group.sort' => 'impressions desc',
'group.main' => 'true'
];
$curlHandle = curl_init($url);
$options = array (
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $data
);
curl_setopt_array($curlHandle , $options);
$result = json_decode(curl_exec($curlHandle));
General answer
I could not collapse results using Field Collapsing paramaters. However, I was able to achieve the desired result using CollapsingQParserPlugin.
The following filter query collapses documents on the field 'image' and selects the one with the highest value for the field 'impressions': {!collapse field=image max=impressions}
Implementation
For some reason I was not able to combine this filter query with my other filter queries under a single key as follows:
$filterQueries = [
"-signature:{$signature}",
...
"{!collapse field=image max=impressions}"
];
$data = [
...
'fq' => implode(' AND ', $filterQueries),
...
];
This produced the error: Query does not implement createWeight
My fix was to do a GET request (instead of a POST, which was done in the question above). With the GET request it is possible to have a key for each filter query: http://solr-url/mtl?...&fq=-signature%3A0&...&fq=%7B!collapse+field%3Dimage+max%3Dimpressions%7D
Below is the php solution for the snippet in the question:
$url = "http://{$host}:{$port}/solr/{$core}/mlt?"; // Note the added question mark
$data = [
'stream.body' => $content,
'fl' => 'image,content,title,signature',
'fq' => $filterQueries,
'start' => 0,
'order' => "score desc",
'wt' => 'json',
'mlt.fl' => 'content,title'
];
$params = [];
foreach ($data as $key=>$value) {
if (is_array($value)) {
foreach ($value as $subvalue) {
$subvalue = urlencode($subvalue);
$params[] = "{$key}={$subvalue}";
}
} else {
$value = urlencode($value);
$params[] = "{$key}={$value}";
}
}
$url .= implode('&', $params);
$curlHandle = curl_init($url);
$options = array ();
curl_setopt_array($curlHandle , $options);
$result = json_decode(curl_exec($curlHandle));

How to use PHP function parameter inside array?

I am trying to declare a function parameter inside my array, but I'm having trouble getting it to work. I've trimmed it down for simplicity purposes, and I have something like:
function taken_value($value, $table, $row, $desc) {
$value = trim($value);
$response = array();
if (!$value) {
$response = array(
'ok' => false,
'msg' => "This can not be blank."
);
} else if (mysql_num_rows(
mysql_query(
"SELECT * FROM $table WHERE $row = '$value'"))) {
$response = array(
'ok' => false,
'msg' => $desc." is already taken."
);
} else {
$response = array(
'ok' => true,
'msg' => ""
);
}
echo json_encode($response);
}
Notice the function parameter $desc trying to be used in the array here:
'msg' => $desc." is already taken.");
The whole function works fine EXCEPT when I try to add the $desc to the array results.
How could this be done?
Do you have an open resource handle to your database? You are not passing one to the query function.

Categories