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;
}
Related
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.
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.
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 ;).
I am using codeigniter email, to send an email to the client who has registerd him self into the system, and after that I echo a json code that syas an email has been sent to you.
this proccess is working when i am using web browser, but it is not working in android application.
my code is below:
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'smtp.1and1.com',
'smtp_port' => 587,
'smtp_user' => $from_email,
'smtp_pass' => $this->config->item('email_password'),
'mailtype' => 'html',
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);
$this->load->library('email', $config);
$this->email->from($from_email, "something");
$this->email->reply_to($from_email, "something");
$this->email->to($to_email);
$this->email->subject("Account Verification");
$this->email->set_mailtype("html");
$this->email->message($email_body);
if($this->email->send()){
$rsp['error'] = 0;
$rsp['data'] = $user;
echo json_encode($rsp);}else{do some thing...}
but if i remove the $this->email->send() from code, then the echo json code works fine, but not emil sendig.
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'smtp.1and1.com',
'smtp_port' => 587,
'smtp_user' => $from_email,
'smtp_pass' => $this->config->item('email_password'),
'mailtype' => 'html',
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);
$this->load->library('email', $config);
$this->email->from($from_email, "something");
$this->email->reply_to($from_email, "something");
$this->email->to($to_email);
$this->email->subject("Account Verification");
$this->email->set_mailtype("html");
$this->email->message($email_body);
$this->email->send();
$rsp['error'] = 0;
$rsp['data'] = $user;
echo json_encode($rsp);
like this try once
Your code:
if ($this->email->send()) {
echo json_encode($rsp);
} else {
// do some thing...
}
means that JSON will be printed only if send() function return true. If it returns false, then the logic will go to else section and no JSON will be printed (unless you modify // do some thing to print JSON also).
I'm pretty sure that mail() return false. You are using CI, don't forget to check application/logs/*.log to see the error detail.
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.