How to send query from iOS to PHP code - mysql

I am kinda new to Obj-C and Stack Overflow, so bear with me here (:D). I newly found out how to send queries from PHP to the MySQL database, but I'm not really sure how to send the query from my iOS app to PHP. Any help would be much appreciated. Thanks.

We don't pass queries from objective C to PHP. What we do is pass data to the server and let the server process the data and respond accordingly.
JSON is popular method to exchange data between server and a mobile device.
For example: You want to get all the fields of the database which has column name, address , contact of table person. You can't do direct database query from the device. like SELECT * from person;.
What we do is send HTTP request to an API like e.g getPersonDetails.php.
Now it's server's responsibility to verify an authorized app is sending HTTP request to it. And after verification it will respond back the data to the application in JSON format or could be XML whatever you feel comfortable. JSON is the preferred way though.
The server response would be this in JSON format:
[
{
name:John,
address:US,
contact:1234
},
{
name:David,
address:UK,
contact:1234
}
]
Now after app receives this JSON object and it needs to decode the JSON into the the suitable form.
Refer to documentation of AFNetworking here:
https://github.com/AFNetworking/AFNetworking
AFNetworking is a popular library for making HTTP request to the server for Objective-C.
Addition 1:
HTTP POST Request from iOS application in Objective C using AFNetworking:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"name": #"Andy",
#"address": #"UK",
#"contact": #"1234",};
[manager POST:#"http://example.com/addToDataBase.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Server side code to handle the POST request
http://example.com/addToDataBase.php
<?php
header('Content-type: application/JSON');
$name = $_POST['name'];
$address = $_POST['address'];
$contact = $_POST['contact'];
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO person VALUES (?, ?, ?)");
$stmt->bind_param('sssd', $name, $address, $contact);
$stmt->execute();
$stmt->close();
$mysqli->close();
$result = array( "result" => "Successfully Inserted Data");
$output= json_encode($result);
echo $output;
?>

have IOS output something like:
$run_var = '$varName="variable value"';
then run it through eval like so
eval($run_var);
see for referencehttp://php.net/manual/en/function.eval.php

Related

GuzzleHttp - Get JSON encoded body

I created an API client for my company to fetch orders from our distributors. I need to acknowledge download of orders back to them with a PUT. The PUT is working properly but I get an error on their confirmation of my acknowledgement.
Using Postman, I get a JSON body message back.
When I PUT a acknowledgement back, I get the following error:
Type error: Argument 1 passed to GuzzleHttp\Client::send() must
implement interface Psr\Http\Message\RequestInterface, instance of
GuzzleHttp\Psr7\Response given, called in
/var/www/orders/app/Http/Controllers/edi/OrderController.php on line 86
This is line 86:
$response = $client->send($apirequest);
The relevant code:
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client as GuzzleHttpClient;
use GuzzleHttp\Psr7\Stream;
use Illuminate\Support\Facades\Input;
use Response;
use XmlParser;
use Psr\Http\Message\RequestInterface;
public function orderConfirm()
{
$uri = config('services.orders.orderack');
$formdata = Input::all();
$orders = Input::get('orders');
try {
$client = new GuzzleHttpClient([
'headers'=> [
'Authorization' => '$user',
'ContractID' => '$contract',
'Content-Type' => 'application/json']
]);
$apirequest = $client->request('PUT', $uri,
['body' => json_encode(
[
$orders
]
)]
);
$response = $client->send($apirequest);
$contents = (string) $response->getBody();
return $contents;
}
catch (RequestException $ex) {
//Exception Handling
echo $ex;
}
Output from Postman was:
"Number of Orders Acknowledged: 1"
from other posts on SO, this:
$contents = (string) $response->getBody();
is the way to get the body and other people fixed their problems, but it's not working for me.
Obviously I'm still missing something here!
Calling $client->request() actually does the request (which is why it's returning an instance of GuzzleHttp\Psr7\Response) instead of building a request object to send later. You don't need to tell the client to send anything because it's already been sent; you just need to set the $response variable to the value of the call to $client->request().
This can be seen in the Body example in their PSR7 documentation.
$response = $client->request('GET', 'http://httpbin.org/get');
To build a request object manually, you will have to create an instance of GuzzleHttp\Psr7\Request using its constructor, as documented under Requests.
// Create a request using a completely custom HTTP method
$request = new \GuzzleHttp\Psr7\Request('MOVE', 'http://httpbin.org/move');
echo $request->getMethod();
// MOVE

POST-Request with JSON Data over HTTPS Connection with Qt5

I'm trying to send a POST request over an HTTPS-Connection via Qt5 to a Web-API, but I keep getting the following error-message:
Failure "Error downloading https://.../login - server replied: BAD REQUEST"
Reply:"{"error_tag": "ARGUMENT_MISSING", "error_code": 19, "error_extra": {"argument": "email"}, "error": "Required argument is missing"}"
It seems like the HTTPS Connection works, but the POST request is faulty...
void connection::sendLoginData(){
QUrl url = QString("https://.../login");
QNetworkRequest req(url);
//Creating the JSON-Data
QJsonDocument json;
QJsonObject data;
data["email"] = QString("a#g.com");
data["password"] = QString("---");
json.setObject(data);
QByteArray jsonPost = QJsonDocument(data).toJson();
req.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json; charset=utf-8"));
req.setHeader(QNetworkRequest::ContentLengthHeader, QByteArray::number(jsonPost.size()));
//Sending the Request
QNetworkReply *reply = manager->post(req,jsonPost);
// Connection via HTTPS
QFile certFile(SSLCERTIFICATE);
certFile.open(QIODevice::ReadOnly);
QSslCertificate cert(&certFile, QSsl::Pem);
QSslSocket * sslSocket = new QSslSocket(this);
sslSocket->addCaCertificate(cert);
QSslConfiguration configuration = sslSocket->sslConfiguration();
configuration.setProtocol(QSsl::TlsV1_2);
sslSocket->setSslConfiguration(configuration);
reply->setSslConfiguration(configuration);
}
this is the Slot which is called when QNetworkReply gets a reply:
void connection::onFinished(QNetworkReply *reply){
if (reply->error() == QNetworkReply::NoError) {
//success
qDebug() << "Success" <<reply->readAll();
delete reply;
}
else {
//failure
qDebug() << "Failure" <<reply->errorString();
qDebug() << "Reply: " << reply->readAll();
delete reply;
}
}
The Signal "finished" of QNetworkReply is of course connected to the "onFinished"-Slot
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
manager = new QNetworkAccessManager;
ui->setupUi(this);
Connector = new connection(ui,manager);
connect(manager,SIGNAL(finished(QNetworkReply*)),Connector,SLOT(onFinished(QNetworkReply*)));
}
Maybe someone of you could tell me what's wrong with the POST-Request? Looking at the Reply of the Server it seems like the JSON-Data is never sent, or somehow formatted in a wrong way...
As you didn't provide the exact URL, I'd suggest you to try to check url.isValid() and url.errorString().
I just had an issue, the code worked fine in Qt 4.8, but in Qt 5.4 all my POST requests got 400 Bad Request reply.
I looked into the TCP dump via Wireshark and found out that the URL was wrong.
In my case url.setPath("api/register"); was the line that caused the problem. It should have been url.setPath("/api/register");
Hope it helps.

Mail exception handling in zend framework 2

I am trying to send an email in zend framework 2 using Mail\Transport\Sendmail().
It is showing a runtime exception on invalid email id.
error message is "Unable to send mail: mail(): SMTP server response: 550 5.1.1 ... User unknown"
Zend\Mail\Exception\RuntimeException
$options = new Mail\Transport\SmtpOptions($config_setting);
// render Email Content
$this->renderer = $this->getServiceLocator()->get('ViewRenderer');
$content = $this->renderer->render($config['mail']['templates']. $messageTemplate, $messageParam);
// make a header as html
$html = new MimePart($content);
$html->type = $config['mail']['content_type'];
$body = new MimeMessage();
$body->setParts(array($html,));
// instance mail
$mail = new Mail\Message();
$mail->setBody($body); // will generate our code html from template.phtml
$mail->setFrom($config['mail']['from_email'],$config['mail']['from_name']);
$mail->setTo($mailTo);
$mail->setSubject($subject);
//$transport = new Mail\Transport\Smtp($options);
$transport = new Mail\Transport\Sendmail();
try{
$response = #$transport->send($mail);
return $response;
}
catch(Zend\Mail\Exception\RuntimeException $ex)
{
$ex->getMessage();
$response = array('error' => 1, 'msg' => $ex->getMessage());
//return $response;
}
i want to ignore this exception message.
You have two transports, one Sendmail and one SMTP. Sendmail is an internal mail server on your pc, which should work fine. SMTP is a protocol to let an (possible external) mail server send emails. You can use your own SMPT server, or connect to e.g. Google or Hotmail for sending mails over SMTP.
You have this in your code:
//$transport = new Mail\Transport\Smtp($options);
$transport = new Mail\Transport\Sendmail();
So you are using in your code the Sendmail transport, but the exception is from SMTP:
Unable to send mail: mail(): SMTP server response: 550 5.1.1 ... User unknown
So it seems to me you are using the SMTP in your code somewhere accidentally. Switch to the Sendmail and it should work fine, or check your question again with the code you posted.

Yii Restful API will create on POST but not populate any variables

Hello I am currently trying to use POSTMAN to test an early API that is based of of this post
http://www.yiiframework.com/wiki/175/how-to-create-a-rest-api/
I am having an error when trying to either submit variables via POST in php url style or even sending an object. The response from the API comes back 200 and it creates a new entry into the database, but unfortunately it will not take any info from the post variables or jason object, it just comes up null. It seems now that that code is just looking through $_POST variables to and trying to match them to a model variable and if so, it should update it save it, However when i try to send through url parameters in POSTMAN or even change content type json and send raw json object I seem to have no luck with it.
Also I really only need it to decode a jason object and not post parameters so maybe that is where I will start by removing the $post loop and working on retrieving a JSON object instead. Thanks for any help!
public function actionCreate()
{
switch($_GET['model'])
{
// Get an instance of the respective model
case 'event':
$model = new Event;
break;
case 'media':
$model = new Media;
break;
case 'comment':
$model = new Comment;
break;
default:
$this->_sendResponse(501,
sprintf('Mode <b>create</b> is not implemented for model <b>%s</b>',
$_GET['model']) );
Yii::app()->end();
}
// Try to assign POST values to attributes
foreach($_POST as $var=>$value) {
// Does the model have this attribute? If not raise an error
if($model->hasAttribute($var))
$model->$var = $value;
else
$this->_sendResponse(500,
sprintf('Parameter <b>%s</b> is not allowed for model <b>%s</b>', $var,
$_GET['model']) );
}
// Try to save the model
if($model->save())
$this->_sendResponse(200, CJSON::encode($model));
else {
// Errors occurred
$msg = "<h1>Error</h1>";
$msg .= sprintf("Couldn't create model <b>%s</b>", $_GET['model']);
$msg .= "<ul>";
foreach($model->errors as $attribute=>$attr_errors) {
$msg .= "<li>Attribute: $attribute</li>";
$msg .= "<ul>";
foreach($attr_errors as $attr_error)
$msg .= "<li>$attr_error</li>";
$msg .= "</ul>";
}
$msg .= "</ul>";
$this->_sendResponse(500, $msg );
}
}
Fixed by removing $POST loop and changing to a JSON object scheme only. Here is the code if anyone happens to find themselves in this situation.
//read the post input (use this technique if you have no post variable name):
$post = file_get_contents("php://input");
//decode json post input as php array:
$data = CJSON::decode($post, true);
//load json data into model:
$model->attributes = $data;
Used that instead of the foreach loop through $_POST variables. Now it accepts a json object instead. Happy Coding all!
Honestly, I'm not sure what your problem is. If you can see the values POSTed in $_POST but not assigned to $model, it's probably because you did not specify the validation rules for those fields in the model. If you do not need to validate the fields, simply mark them as 'safe' in the model's rules() function like below.
public function rules() {
return array(
array('fieldName1,fieldName2', 'safe'),
);
}

Laravel 4 JSON Response with Cookie

How can I set a cookie with a json response?
I noticed, for me at least, the following command is the only thing working that sets a cookie:
return Redirect::to('/')
->withCookie(Cookie::make('blog', $cookie_values, 1000));
Of course if it was an ajax request it would return the target of the redirect.
How could I translate this to an ajax request and return a json response with the cookie?
I was able to set a cookie with a json response with the following code:
$cookie_values = array(
'name' => Input::get('name'),
'id' => Auth::user()->id,
'login_success' => 1);
if(Request::ajax())
{
$cookie = Cookie::make('blog', $cookie_values, 1000);
$response = Response::json($cookie_values);
$response->headers->setCookie($cookie);
return $response;
}
Great hint!
Having a look at Symfony\Component\HttpFoundation\ResponseHeaderBag also revealed how to set headers for a json response when having problems with HTTP access control:
$response->headers->set('Access-Control-Allow-Origin', '/* your subdomain */');