Connecting desktop app to online database via php - php

I've read a lot of posts on this general subject but I still can't seem to figure it out.
I'm building a Mac/PC desktop application. When a user first authorizes the app, I want to store their info in an online Mysql database. I'm using the JUCE library to call and handle a php file online which in turn handles the updating of the online database. On my desktop app:
String url = "http://www.syntorial.com/onlinePHPFileToCall.php?email=" + email + "&computer=" + SystemStats::getComputerName();
URL authURL(url);
InputStream *input = authURL.createInputStream(true);
String result = input->readString();
And the php file:
<?php
$result = "";
$mysqli = new mysqli('localhost','username','password','dbname');
if (mysqli_connect_errno())
{
$result = "connection failed";
}
else
{
$mysqli->select_db("UserInfo");
$email = $_GET['email'];
$computer = $_GET['computer'];
$query = "UPDATE UserInfo SET computer = '$computer' WHERE email = '$email'";
if ($queryResult = $mysqli->query($query))
{
$result = "true";
}
else
{
$result = "false";
}
}
echo $result;
?>
The result comes back "true" on my desktop app, but the information doesn't actually get saved into the database. If instead of
InputStream *input = authURL.createInputStream(true);
I use:
authURL.launchInDefaultBrowser();
it opens up the php file in a browser and everything works fine. Any ideas what I'm doing wrong?

Joe,
Seems like one of your first question on this forum. So Welcome. You mentioned you want to store information in an online database. But while connecting you added db information about your local via
mysqli('localhost',
. Update localhost to point to an online database by finding its ip address/servername, username and password. Also you will have to ensure the computer where you run this application can connect to that online db.
Here is what I am ran on my local and worked for me.
<?php
$result = "";
$mysqli = new mysqli('localhost','root','','test');
if (mysqli_connect_errno())
{
$result = "connection failed";
}
else
{
$email = "xyz#yahoo.com";
$computer = "1mycomp";
$query = "UPDATE so1 SET computer = '$computer' WHERE email = '$email'";
/*
Printing the query to check what is being executed.
Remove the below line after program works.
*/
echo $query;
if ($queryResult = $mysqli->query($query))
{
$result = "true";
}
else
{
$result = "false";
}
}
echo $result;

Turns out the "true" argument in CreateInputStream was telling it to use POST data instead of GET so the call was ignoring the GET data. Thanks the help.

Related

iTunes Search API: Update Notification

i'm using iTunes API Search and Advanced Custom Field WordPress plugin so the wp author can add a mac app id to a custom field and the implanted iTunes Search API above will add all the other information of app automatically in the wp post. and when app information updated my wp post will have the updated info like last verion number app size and ...
but the problem is my own wrote review and guide of any verion of any app inside my website and it need to be updated manually.
for example i have added a post for version 3.7.1 of "Things 3" mac app using method above to my WordPress and i have reviewed this version with my own description and hand-wrote in the post.
now i need to get notified when ever this app gets a new version or update so i can update my review and add some text for new version inside the post as well.
is there any way or method you guys can think of, so i can get notified when ever an app i have reviewed in my site gets an update ?
i really appreciate any way or taught !
Thanks.
There is no native API to do what you're asking.
However, with a little coding I believe you could use the RSS feed of the application to then create something to notify you on a change.
See Example for the App HomeScan
https://itunes.apple.com/lookup?id=1380025232
ID= YOURAPPID
I believe this should give you some general direction to do what you need.
This is a reply to our comment history in the other answer.
#erfanMHD, there are a number of ways to really do this. You don't have to do it in javascript. This isn't really something someone can give you an easy code snippet for since it requires a few additional things and is generally frowned upon in StackOverflow.
You'll need somewhere to store the localVersion of the application of the review you last wrote. In the example I wrote below I used a simple MySQL database to hold the local version. You'll also need to figure out how you want to display the data. I know you can add stuff to the wordpress dashboard but this isn't something we can show you how to do via StackOverflow.
However, below is a very simple (JUST FOR REFERENCE) purposes only on how one could achieve what you're trying to do. However this is just an example to guide you along the process.
For this demo, you'll need a MySQL database with a DBName of test and and a record created called application_version with 3 rows. ID, Name, Version.
<?php
$servername = "localhost"; // Your MySQL Server
$username = "root"; // Your MySQL Username
$password = "password"; // Your MySQL Password
$dbname = "test"; // The name of your MySQL database
$id = "904280696"; // The ID of the applicaiton you're wanting to check
function search($searchTerm){
// Construct our API / web services lookup URL.
$url = 'https://itunes.apple.com/lookup?id=' . urlencode($searchTerm);
// Use file_get_contents to get the contents of the URL.
$result = file_get_contents($url);
// If results are returned.
if($result !== false){
// Decode the JSON result into an associative array and return.
return json_decode($result, true);
}
// If we reach here, something went wrong.
return false;
}
function updateVersion($id, $name, $version) {
// Create MySQL connection
$conn = new mysqli($GLOBALS['servername'], $GLOBALS['username'], $GLOBALS['password'], $GLOBALS['dbname']);
// Check MySQL connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Save the Version information
$sql = "UPDATE application_version SET name='" . $name . "', version='" . $version . "' WHERE id='" . $id . "'";
echo $sql;
echo "<br>";
// Run the Insert into MySQL
if ($conn->query($sql) === TRUE) {
// Print On Success
echo "Record Updated Successfully";
echo "<br>";
} else {
// We dun goofed
echo "Error: " . $sql . "<br>" . $conn->error;
echo "<br>";
}
$conn->close();
}
function getLocalVersion($id) {
// Create MySQL connection
$conn = new mysqli($GLOBALS['servername'], $GLOBALS['username'], $GLOBALS['password'], $GLOBALS['dbname']);
// Check MySQL connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM application_version WHERE ID = " . $GLOBALS['id'];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "Found Application ID Entry in database";
echo "<br>";
echo "<table><tr><th>ID</th><th>Name</th><th>Version</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["name"]."</td><td>".$row["version"]."</td></tr>";
$GLOBALS['storedVersion'] = $row["version"];
}
echo "</table>";
echo "<br>";
} else {
echo "No Application ID Entry found in database";
echo "<br>";
}
$conn->close();
}
// Search for your requested ID
$searchResults = search($GLOBALS['id']);
$currentVersion = '0.0.0';
$storedVersion = '0.0.0';
$appName = 'null';
// Loop through the results.
foreach($searchResults['results'] as $result){
// Pass the current version to variable
$currentVersion = $result['version'];
$appName = $result['trackName'];
// Get the current version or what ever else information you need
echo 'Current Version: ' . $currentVersion;
echo "<br>";
echo "<br>";
}
// Get Local Version from database
getLocalVersion($id);
if ($currentVersion > $storedVersion) {
echo "You have an old version friend";
echo "<br>";
// Write what you want it to do here
updateVersion($id, $appName, $currentVersion);
} else {
echo "You're all up to date";
echo "<br>";
// Write what you don't want it to do here
}
?>
Again, this is just quick and dirty. You'd want to do a lot of additional checks and balances. One I see right off the bat would be in the check for inserting.

How to submit form data to my database when port forwarding

I'm developing a simple registration form. I was able to have it functional locally via localhost. I am able to receive the data placed in the inputs and store into my phpmyadmin.
Here's my PHP code:
if($boolen){
$dbname = "regdb";
$con = mysqli_connect("localhost","root","",$dbname);
if(!$con){
die("Connection Failed :" + mysqli_connect_error());
}
function NewUser(){
$sql = "INSERT INTO regi (urname,email,passwd,fname,gender) VALUES ('$_POST[urname]','$_POST[email]','$_POST[passwd]','$_POST[fname]','$_POST[gender]')";
$query = mysqli_query($GLOBALS['con'],$sql);
if($query){
echo "<script>
alert ('Record Inserted Successfully...!');
</script>";
}
}
function SignUP(){
$sql = "SELECT * FROM regi WHERE urname = '$_POST[urname]' AND email = '$_POST[email]'";
$result = mysqli_query($GLOBALS['con'],$sql);
if(!$row = mysqli_fetch_array($result)){
NewUser();
}else{
echo "<script>
alert ('You Are Already Registered User......!');
</script>";
}
}
if(isset($_POST["submit"])){
SignUp();
mysqli_close($GLOBALS["con"]);
$boolen = false;
}
}
Once I port forwarded my html/php files everything seemed fine until I tried submitting the data in the inputs. It only receives the data in the inputs locally, but when I port forward it doesn't receive nothing. I get no errors.
What can I do to solve this?

Error in JSON response from PHP file when hosted online

if($tag == 'signin'){
// check for user
$email = mysql_real_escape_string(trim($_POST['username']));
$password = mysql_real_escape_string(trim($_POST['password']));
if(isset($email) && !empty($email) && isset($password) && !empty($password)){
$result = getUserByEmailAndPassword($email, $password);
if ($result != false) {
// user found
$response["error"] = FALSE;
$response['uid'] = $result['uid'];
$response['email'] = $result['email'];
$response['username'] = $result['username'];
$response['password'] = $result['password'];
$response['endyear'] = $result['endyear'];
$response['phone'] = $result['phone'];
$response['currentyear'] = $result['currentyear'];
$response['currentsem'] = $result['currentsem'];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = TRUE;
$response["error_msg"] = "Incorrect email or password!";
header('Content-Type: application/x-www-form-urlencoded');
echo json_encode($response);
}
}else{
$response["error"] = TRUE;
$response["error_msg"] = "Required parameter 'username' or 'password' is missing!";
echo json_encode($response);
}
}
I am using the above php code for my API
am I using header('Content-Type: application/x-www-form-urlencoded'); in the right place?
Also, when I check this request on my Advanced REST client in chrome, the request is just fine. the response is below:
{"tag":"signin","error":false,"uid":"10","email":"example#exmaple.com","username":"jammy","password":"40be4e59b9a2a2b5dffb918c0e86b3d7","endyear":null,"phone":null,"currentyear":null,"currentsem":null}
However, when I run the same thing on any online response checker, the response is all garbage HTML. Same with my application hosted online
I noticed that the chrome extension by default sets the Content-Type to application/x-www-form-urlencoded
The same code used to work fine when I was running my application on xampp on localhost, however, after I uploaded this online, I am facing this issue
Could someone pls help me figure what I am doing wrong
It is not mandatory but if you plan to return JSON, the right header should be
header('Content-Type: application/json');
Otherwise, the receiver of the response may or may not interpret the body response as JSON.
I was able to locate the root cause of the problem. I made a lot of changes to the code only to realize later that this was due to MySQL DB tables
The tables I created on my local used InnoDB engine whereas my hosting provider provided on MyISAM engine.
All the tables created by importing the SQL file had engine set to MyISAM. I hosted the tables on a different provider with InnoDB engine and everything seemed to work fine.
Thank you everyone for trying to help

Get and operate with answer from other server in php

I'm trying to make some sort of communication between two servers(can be called license verification).
Already got this:
index.php
if ($verification == 1) {
echo "license validated";
}
else {
echo "this license key does not exist.";
}
validate.php
$license_key = mysql_real_escape_string($_GET['license_key']);
$query = "SELECT license_key FROM users WHERE license_key = '$license_key'";
$mysqli = new mysqli();
$mysqli->connect($db_hostname, $db_username, $db_password, $db_name);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
}
$result = $mysqli->query($query);
$row_cnt = $result->num_rows;
if ($row_cnt == 1) {
return true;
}
else {
return false;
}
What I can't figure out is how to send that request from index.php to validate.php ( this 2 files are not in same server ) and how to get back to index.php information what it returns (true or false).
Use file_get_contents:
$verify_result = file_get_contents("http://validation.domain.com/validate.php?license_key=$key");
if ($verify_result == 'license validated') {
...
}
Probably the easiest way would be to setup a service. Here's one of numerous tutorials out there.
For example, let's say that the validation server's hostname is val.com. You could setup a service there that looks like:
val.com/validation/validate?dataToValidae=<validationString>
Be sure to send the request over SSL if you don't want it to be intercepted.
You could then have the service return whether or not the validation succeeded, and then check for that in your code.

PHP seems to be refusing to connect to MySQL

<?php
function redirect_to_index_with_error(){
echo '<meta http-equiv="refresh" content="0;url=index.php">';
}
function go_to_home(){
echo '<meta http-equiv="refresh" content="0;url=home.php">';
}
$email = mysql_real_escape_string($_POST['username']); echo $email;
$pwd = mysql_real_escape_string($_POST['password']);
echo $pwd;
$query = "SELECT * FROM users WHERE email='$email' AND password=MD5('$pwd')";
echo "query variable created.";
mysql_connect("localhost","root","") or die(mysql_error());
echo "connected."; //nothing
mysql_select_db("mcp") or die(mysql_error());
$results = mysql_query($query) or die(mysql_error());
if(mysql_num_rows($results) == 0){
redirect_to_index_with_error();
exit();
}
$userID = null;
$name = null;
$school = null;
$mod = null;
while($user = mysql_fetch_array($results)){
$userID = $user['ID'];
$name = $user['Name'];
$school = $user['School'];
if($user['Mod'] == '1')
$mod = true;
else
$mod = false;
}
if(!isset($_SESSION))
session_start();
//set session variables
$_SESSION["userID"] = $userID;
$_SESSION["name"] = $name;
$_SESSION["school"] = $school;
$_SESSION["mod?"] = $mod;
go_to_home();
exit();
?>
PHP echos everything up until "connected". It's not even showing a mysql error. I've had this code work flawlessly on Windows with WAMP, but not on Mac with MAMP. I've verified that the servers are running, so I can't tell what the problem is. I'm using PHP 5.3.6.
Your connection needs to be established before you call mysql_real_escape_string()
So move mysql_connect("localhost","root","") or die(mysql_error()); to the top.
Move the mysql_connect() statement above everything else.
// put this at the TOP
mysql_connect("localhost:3306","root","") or die(mysql_error());
Just as everyone else mentioned, see this note:
http://php.net/mysql_real_escape_string#refsect1-function.mysql-real-escape-string-notes
Also, you should see errors, in development, at least.
See: error_reporting()
you have to call mysql_real_escape_string() after connect.
otherwise this function returns an empty string and your query fails.
though it raises an error but it seems you haven't seen that.
So, you ought to either turn displaying errors on or peek error logs - it's impossible to program without ability to see error messages
Also, you have to improve your formal logic.
To make a statement like "PHP seems to be refusing to connect to MySQL" youi have to verify it first. Connect is just a single line and returns a value.
You can verify this value and make a certain conclusion.
But running whole code of several dozens of lines and making statements about just one makes no sense.

Categories