how to insert multiple check box in web service codeigniter? - android

I've created a web service in codeigniter.
so here my controller:
public function insertsebab(){
$id=$this->input->post('id_konsultasi');
$sebab=$this->input->post('kd_sebab');
$data = array(
'id_konsultasi' =>$id,
'kd_sebab' => $sebab,
);
$konsultasi = $this->class_model->insertsebab($data);
if(count($konsultasi) > 0 ){
$json["STATUS"] = "SUCCESS";
$json["MESSAGE"] = "Data Berhasil Di Simpan";
$json["DATA"] = (object) array();
}
else{
$json["STATUS"] = "GAGAL";
$json["MESSAGE"] = "No data found in database";
$json["DATA"] = (object) array();
}
echo json_encode($json);
}
The code above explains how to insert data more than one in checkbox,but actually data save only one.
checkbox
so,how to create insert multiple check box in web service codeigniter?

I think u need to do a foreach with the post name.
here a same question :
Get multiple values of checkbox in codeigniter
I wish it helps you.

Related

Send Firebase Notification to multiple registered Android devices

I want to send firebase notification to all registered token in mysql database for android devices, am using the normal php way of creating array of recipient tokens so that i can send the notification, but when i send notification non of the registered devices receive it. I want to know if there is the need of adding some piece of php codes to work with the firebase so that the job get done, If so how and where should i use it based on my codes or what is wrong with my codes and how can i fix it?
// here is the code for sending notification
<?php
$message =$_POST['message'];
$title=$_POST['title'];
//firebase server url
$path_to_fcm='https://fcm.googleapis.com/fcm/send';
// Here is the server_key
$server_key="##########################";
$conn = mysqli_connect("localhost","db_username","password","database_name");
$sql = "select * from fcm_info";
$result = mysqli_query($conn,$sql);
//HERE IS THE TOKEN
$tokens = array();
if(mysqli_num_rows($result) > 0 ){
while ($row = mysqli_fetch_assoc($result)) {
$tokens[] = $row["fcm_token"];
}
}
/// HERE IS THE KEY SINGLE RECIPIENT IT WORKS FINE WHEN I INTRODUCE TO THE RECIPIENT FIELD("to" field)
$key="############";
$headers= array(
'Authorization:key='.$server_key,
'Content-Type:application/json'
);
// here use $tokens as the replace $key
$fields= array('to'=>$token,
'notification'=>array('title'=>$title,'body'=>$message,
'click_action'=>'com.jrcomjk.firebasemysql_TARGET_NOTIFICATION'
));
$payload= json_encode($fields);
$curl_session= curl_init();
curl_setopt($curl_session,CURLOPT_URL,$path_to_fcm);
curl_setopt($curl_session,CURLOPT_POST,true);
curl_setopt($curl_session,CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_session,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl_session,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($curl_session,CURLOPT_IPRESOLVE,CURL_IPRESOLVE_V4);
curl_setopt($curl_session,CURLOPT_POSTFIELDS,$payload);
$result =curl_exec($curl_session);
curl_close($curl_session);
mysqli_close($conn);
?>
I see that you declare :$tokens = array(); with "s" but you are using $token without "s" here :
$fields= array('to'=>$token'notification'=>array('title'=>$title,'body'=>$message,'click_action'=>'com.jrcomjk.firebasemysql_TARGET_NOTIFICATION'));
Your code should work, just make there you are configured the firebase project which on firebase console correctly and put the server key accordingly.

Session token right usage with API

Can anyone please explain -
I am writing a Php code that will allow a mobile app (Android) to get data from the DB.
I read about using a token but where do I save this token on the server side?
(I tried it, but the session token variable doesn't exist I assign it - for example, if I call it the second time.)
<?php
session_start();
$sql = "SELECT * FROM a_users WHERE a_mail = '".$_POST["mail"]."' AND a_pw = '".$_POST["pw"]."'";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
$value = $result->fetch_assoc();
$Token_API = encryptMyVar(date('Y-m-d H:i:s'));
$_SESSION["Token_API"] = $API_Token;
$value = array("login" => 1,"token_api" => $Token_API,"nickname" => $value["nickname"]);
$con->close();
exit(json_encode($value));
}
?>
should i save the token in a file on the server or something or am I doing something wrong?
Thank you!!!
So after looking at your code, it isn't a big problem. All you have is the variable your are setting the Session to is $API_Token, that variable doesn't exist. You should mean to set $_SESSION["Token_API"] to $Token_API. Your final code should look something like this:
<?php
session_start();
$sql = "SELECT * FROM a_users WHERE a_mail = '".$_POST["mail"]."' AND a_pw = '".$_POST["pw"]."'";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
$value = $result->fetch_assoc();
$Token_API = encryptMyVar(date('Y-m-d H:i:s'));
$_SESSION["Token_API"] = $Token_API; //Replaced $API_Token with $Token_API
$value = array("login" => 1,"token_api" => $Token_API,"nickname" => $value["nickname"]);
$con->close();
exit(json_encode($value));
}
?>
Please do tell me if this solves your problem ;).

Creating new plugin for webservice

I wrote this code to connect to a database, make some queries and send them by json like web api.
I want to create plugin that will work like a WEB API. Then upload it on WP modules on internet and people may install them on their sites to connect my android App. Anywhere.
This is my php code (include db_connect and sending json and respond to my Android App)
<?php
if(!isset($_REQUEST ['id']))
echo "id is not set";
if (isset ( $_REQUEST ['id'] )) {
$id = $_REQUEST ['id'];
$response = array ();
mysql_connect('localhost','db_admin','password') or die(mysql_error());
mysql_select_db('db_name') or die(mysql_error());
$sql= "select * from employee";
$run=mysql_query($sql);
if (mysql_num_rows ($run) > 0) {
while ($row= mysql_fetch_array($run)){
$product = array ();
$product ["id"] = $row [0];
$product ["name"] = $row [1];
$product ["salary"] = $row [2];
$response [] = $product;
}
echo json_encode ( $response );
}
}
?>
My manager wants me not to use the default Woocommerse WORDPRESS API,so I have to create new plugin. and want to know how can I convert it to standard module?
Is it possible at all ?
If I was you I will created like this:
First off would create handler for the request, either via ajax (im not sure if this way is supported in android ) like this;
function get_some_information(){
$user_id = $_REQUEST['id'];
if(!isset($user_id) || empty($user_id)){
return json_encode([
'success' => false,
'message' => 'Empty Request'
]);
}
$data = get_info_from_data($user_id);
if(!empty($data)){
echo json_encode($data);
exit;
}else{
echo json_encode([
'success' => false,
'message' => 'Error while processing data'
]);
exit;
}
}
add_action('wp_ajax_get_some_information', 'get_some_information'); //for auth users
add_action( 'wp_ajax_nopriv_get_some_information', '_get_some_information' ); //for the rest
Note: there is an exit; you always need to terminate the application to be able to get the json, otherwise the output it will be 0
With this now we have an access point to data and validation; and it looks a bit more clean.
function get_some_information($id){
$result = [];
// do all things and added to the array
return $result;
}

Nusoap webservice doesn't comunicate with Xamarin Android app

I developed a web service using nusoap, seems that the web service works fine, in fact is very simple, I put here the code:
<?php
// Pull in the NuSOAP
require_once('lib/nusoap.php');
// Create the server instance
$server = new soap_server();
// Initialize WSDL support
//(MyService is name of our service)
$server->configureWSDL('WebService', 'urn:WebService');
// Character encoding
$server->soap_defencoding = 'utf-8';
//Register Insert user function
$server->register(
'InsertData', //Name of function
array('Id' => 'xsd:int',
'userName' => 'xsd:string',
'Pass' => 'xsd:string',
'Mail' => 'xsd:string'), //Insert Values
array('return' =>'xsd:boolean'), //return Values
'urn:ServiceWsdl', //Namespace
'urn:ServiceWsdl#InsertData', //SoapAction
'rpc', //style
'literal', //can be encoded but it doesn't work with silverlight
'Insert function to register users'
);
//Register GetData function
$server->register(
'GetData',
array('Id' => 'xsd:int'),
array('Id' => 'xsd:int',
'userName' => 'xsd:string',
'Pass' => 'xsd:string',
'Mail' => 'xsd:string'), //return values
'urn:ServiceWsdl',
'urn:ServiceWsdl#GetData',
'rpc',
'literal',
'Get all users function'
);
function InsertData($id, $userName, $Pass, $Mail) {
$connect = mysql_connect("server","userDB","passDB");
if ($connect) {
if(mysql_select_db("database", $connect)) {
mysql_query( "INSERT INTO `Users`(`Id`, `UserName`, `Pass`, `Mail`) VALUES (`".$id."`,`".$userName."`,`".$Pass."ยด,`".$Mail."`);");
return true;
}
}
return false;
}
function GetData($Id) {
$connect = mysql_connect("server","userDB","passDB");
if ($connect) {
if(mysql_select_db("database", $connect)) {
$sql = "SELECT * FROM Users";
$result = mysql_fetch_array(mysql_query($sql));
return $result['Id']."-".$result['UserName']."-".$result['Pass']."-".$result['Mail'];
}
}
return false;
}
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
And my code on the Android Xamarin project (working from Visual Studio 2013) is very simple too:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
Button button = (Button) FindViewById<Button>(Resource.Id.MyButton);
TextView labelText = (TextView)FindViewById<TextView>(Resource.Id.editTextUserName);
button.Click += delegate
{
//showMessageWithName(labelText.Text);
AvitecWS service = new AvitecWS();
if (service.InsertData(69, "AnUser", "anUserPassword", "anUser#mail.com"))
{
//the following method just show a message :)
showMessageWithName("Message has been send!");
}
else
{
showMessageWithName("Upss... something was wrong :(");
}
};
}
Then, when I click the button and the app should to do the insert I 've got the following exception:
I think that it is happening because the format of the SOAP object is not correct, but I can't view where is error :(
I REALLY appreciate any help.
Thanks in advance.
This exception throws when the client side cannot establish a connection with the server. In this case (I'm using Hostinger) I changed the numeric server IP for mysql.hostinger.com, the translated domain name, in fact is the same... but for a reason that I don't know it's just works using the translated domain name.
My code:
<?php
// Pull in the NuSOAP
require_once('lib/nusoap.php');
// Create the server instance
$server = new soap_server();
// Initialize WSDL support
//(MyService is name of our service)
$server->configureWSDL('AWebService', 'urn:AWebService');
// Character encoding
$server->soap_defencoding = 'utf-8';
//Register Insert user function
$server->register(
'InsertData', //Name of function
array('userName' => 'xsd:string',
'Pass' => 'xsd:string',
'Mail' => 'xsd:string'), //Insert Values
array('return' =>'xsd:boolean'), //return Values
'urn:AwebServiceWsdl', //Namespace
'urn:AwebServiceWsdl#InsertData', //SoapAction
'rpc', //style
'literal', //can be encoded but it doesn't work with silverlight
'Insert function to register users'
);
function InsertData($userName, $Pass, $Mail) {
$connect = mysqli_connect("mysql.hostinger.es", [USER], [PASSWORD], [DATABASE]);
if ($connect) {
mysqli_query($connect, "INSERT INTO `Users`(`UserName`, `Pass`, `Mail`) VALUES ('".$userName."','".$Pass."','".$Mail."')");
return true;
}
return false;
}
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
By the way, I changed the mysql_connect() method to mysqli_connect() method, because the first is deprecated. Another mysql methods are changed too.
More info here:
Deprecated: mysql_connect()

Titanium Alloy Android Login

I am having an issue with a Titanium App, the issue is only with Android, iOS is fine.
So I have a login form that queries the database, pretty straightforward. But for some reason it is not passing the params to the login script.
My JS function in app, have set the alert on the else statement to print out the $.email.value and password values which read fine. But with the current $response which is just a json it shows the values as being blank? The php form is also below. As I have said this is working fine on iOS
function login(e) {
//function to use HTTP to connect to a web server and transfer the data.
var sendit = Ti.Network.createHTTPClient({
onerror : function(e) {
Ti.API.debug(e.error);
alert('There was an error during the connection');
},
timeout : 100000,
});
//Here you have to change it for your local ip
sendit.open('GET', 'http://soyo.taylorhoganit.co.uk/post_auth.php');
var params = {
email : $.email.value,
password : $.password.value,
};
sendit.send(params);
//Function to be called upon a successful response
sendit.onload = function() {
var json = this.responseText;
var response = JSON.parse(json);
if (response.logged == true)
{
var landing = Alloy.createController("landing").getView();
$.index.close();
landing.open();
// Ti.App.Properties.setString('email', $.email.value);
// Ti.App.Properties.setString('password', $.password.value);
//alert("Username: " + response.username);
}
else
{
alert($response);
}
};
};
PHP Script
<?php
// Connect to the database(host, username, password)
$con = mysql_connect('replaced values');
if (!$con)
{
echo "Failed to make connection.";
exit;
}
$db = mysql_select_db('soyo');
if (!$db)
{
echo "Failed to select db.";
exit;
}
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE email = '" . $email . "' AND password = '" . $password . "'";
$query = mysql_query($sql);
// If we find a match, create an array of data, json_encode it and echo it out
if (mysql_num_rows($query) > 0)
{
$row = mysql_fetch_array($query);
$response = array(
'logged' => true,
'email' => $row['email']
);
echo json_encode($response);
}
else
{
// Else the username and/or password was invalid! Create an array, json_encode it and echo it out
$response = array(
'logged' => false,
'message' => $email + $password
);
echo json_encode($response);
}
?>
You did a mistake by using $response in the alert. It is a PHP variable not JS.
var response = JSON.parse(json);
// ...
alert($response); // Here should be just `response`
Edit: The another problem is that you are sending GET request while in PHP you accept POST ,so you can't get any params...
There is a mistake when you want to show alert.
You are using now is alert($response);
Remove $ from $response and use alert(response);, it will work properly.

Categories

Resources