How to connect to remote MYSQL database via php - php

I have to build an android app which connects to a remote MYSQL webserver and retrieve information for display purpose.
So I did research coz I had no idea where to start. I read an article it mentions the better approach for that is to use php script. And didn’t know anything about how server, database and php works, so I studied php from here “http://www.homeandlearn.co.uk/php/php12p1.html” to understand and downloaded WhampServer to do some testing. On local machine everything worked fine.
But main thing I don’t understand is “HOW TO CONNECT TO REMOTE SERVER/DATABASE”.
It’s obvious that I’m doing something really stupid, I just need help to find out what am I doing wrong.
When we test php script on local machine in webrowse we use "localhost/some.php." But when I want to test same php script on remoter server from my local machine then what and how should I do? Do I need to make some changes in configuration file on server side?
I have done more research before asking this question here to understand remote server connection in php but I still don’t understand. I have gone through almost all the pages within the link below:
https://www.google.co.uk/search?q=connect+to+remote+mysql+webserver+php&rlz=1C1AVSX_enGB447GB448&oq=connect+to+remote+mysql+webserver+php&aqs=chrome.0.69i57j69i62l3.19724j0&sourceid=chrome&ie=UTF-8#fp=5a2359cf96dc5f79&q=how+to+connect+to+remote+mysql+web+server+php
And help would be much appreciated.
If my question is not clear please let me know I'll try to explain more. or think of it as if you have to connect to a remote MySQL server how would you do , means what is the process and steps involved in that.
Thanks everyone.
Edit
I have created a database "dealt3_raj_test" on remote server. and when I type "examplewebserver.CO.UK/myphpscriptname" in my web browser.
It gives me error "An error occurred , You have reached the error page"
<?PHP
$user_name = "dealt3_raj";
$password = "5dN5nh&eMd(vCR$dzk";
$database = "dealt3_raj_test";
$server = "examplewebserver.CO.UK";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if($db_handle)
{
print "Connected";
}
else
{
print "Can not connect to server";
}
if ($db_found)
{
print "DataBase found";
}
else
{
print "DataBase not found";
}
?>

Adding onto #user4035's comment, after opening the connection, use JDBC in your Android/Java code to interact with the database.
That said, it is not good practice. Rather create a web service
Your application may experience latency/connectivity issues. This will impact performance.
Your MySQL server will have to be open to remote connections which is strongly advised against
If your Android App is intended for public usage, it means the database username and password of your MySQL server reside on everyone's phone using your app. Encrypted or not this makes your database server a "step less" secure
Well answered here on SO (JDBC vs Web Service for Android)

use this code to connect with data base
$username = "database user name";
$password = "DB password";
$hostname = "hostname";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("data base name",$dbhandle) or die("Could not select examples");

Related

What is servername

i just wanted to insert data into database from a form, with php. i ran the code below in my Localhost using XAMPP and everything was fine but where i upload it to my host it didn't work.
Question is What shold i put for $servername and when should i look for it ?
There is my codes:
Register.php (in localhost)
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$Name = $_POST['Name'];
$Username = $_POST['Username'];
$Password = $_POST['Password'];
$Email = $_POST['Email'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
header("Location:#");
}
//Inserting Data
try{
$sql = "INSERT INTO User (uName , uUsername , uPassword , uEmail) VALUES ('$Name' , '$Username' , '$Password' , '$Email')";
mysqli_query($conn, $sql);
}catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
$conn->close();
header("Location:#");
}
?>
If your MySQL database is on the SAME SERVER as your PHP script, then the usual logical approach is that your host is localhost. The same as you used on your local computer -- because they're on the same machine.
However, if your MySQL database is on ANOTHER SERVER seperate from your PHP scripts the you will need to access that server using a web address for your PHP to connect to yout MySQL.
We can't tell you what that is, and your server hosts (of your MySQL server) will be able to tell you and provide you with the correct login credentials.
I believe it would be more usual for MySQL and PHP to be on the same disk, especially for non-professional systems as your appears to be, so then the issue would be:
Are your login details set up correcty on your server? (same username/password)
Are there any MySQL errors or PDO errors (if you connect with PDO). Don't redirect on error, but instead output the error to a log file so you can read WHY the MySQL in your code didn't connect.
It is still possible for you to set your PHP to communicate with your localhost MySQL via a remote address (such as servername=$_SERVER['SERVER_NAME'];). (see note below)
Many online accounts (in things such as CPanel) will block you from accessing the MySQL as a root or at least will not give you the root MySQL password. Using root to access MySQL via PHP is NOT a good idea and you should instead set up a specific MySQL user for your PHP with only enough privileges that you need to read/write to the DB, and nothing more.
If your MySQL is remote (not localhost) then you may also need to supply a Port Number with the connection details. Usual port numbers are 3306 but this is something you'd need to know from your server hosts.
Immediately after a header(Location:); redirection instruction you should always set die(); or exit to stop PHP processing the rest of the script.
Your SQL insert data is highly suseptible to SQL injection and other SQL attacks and compromise. You should really, REALLY look into using MySQL Prepared Statements, you're already coding in OO style so you're almost there already.
Example remote connection from the manual
<?php
/***
* Remember 3306 is only the default port number, and it could be
* anything. Check with your server hosts.
***/
$conn = new mysqli('remote.addr.org.uk', 'username', 'my_password', 'my_databasa', '3306');
/***
* This is the "official" OO way to do it,
* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
***/
if ($conn->connect_error) {
error_log('MySQL Connect Error (' . $conn->connect_errno . ') '
. $conn->connect_error);
}
/***
* Upon failure, the above will output a connection error notice such as
* user not found or password incorrect. It won't explicity say these
* things but you should be able to deduce which from the notice
***/
echo "Success... \n" . $conn->host_info ;
$mysqli->close();
# : I seem to think that MySQL detects when the remote address given is the same as the server address and auto converts it to localhost, but I'm not sure on this.
The long and the short of it is that if your MySQL is on the same
server as your PHP it makes no sense to open up a network loop to send
data out just to get it back again. Use localhost instead.
I asked my host service providers about the "$servername" and they answered me that the "$serverneme" is localhost.

Send a mysqli_query() to an intranet with a remote php-script

currently, I am programming an Android app that connects to a php-server. On that server are some php-scripts, which send mysqli_queries and receive responses of remote mysql databases.
<?php
error_reporting(0);
$db_host = $_POST["dbhost"];
$db_uid = $_POST["dbusername"];
$db_pass = $_POST["dbpassword"];
$db_name = $_POST["dbname"];
if ($db_host == "" || $db_uid == "" || $db_pass == "" || $db_name =="" )
echo "Missing information!";
else
{
$con = mysqli_connect($db_host,$db_uid, $db_pass, $db_name);
// Check connection
if (mysqli_connect_error())
die("Couldn't connect to the database!");
else
echo "Connection Successfull";
}
?>
That works without any problems, but now, I need to connect to an intranet first, to get access on a local database.
I thought about a php-script that connects to the intranet (via vpn) and if the connection is established it runs the mysql queries.
After the php-script received the response it disconnects and sends the result back to the Android app. Sadly I've never done that before and Google seems to not know an answer.
I don't want that the whole server connects to the intranet itself, just the scripts are allowed to establish a connection, because other mysqli_queries are executed at the same time.
My question, is that possible?
And if it isn't, is there another solution how to solve my problem?
Thank you pretty much in advance.
The best solution is that you created a web service on your intranet and you consume it from your android device you can enviyer gives them the get method of utl web service.
For the augulenter securiter your web service you can add a variable that you patage between the web service and the android application.
To solve this you have to setup a specific port that will communicate outside or an api and secure it via a public key. More exactly you can just forward a port what can work on http from the server in your intranet. Something like http://address:8888 and pull data through an API . That's the most secure way. Please take this answer into account only if you feel that I understood correctly. If now add a comment and I can still give you some ideas.

Remote Database Access

I need to access a remote database from my iPhone. I have an account on iPage, but as far as i know it does not support remoteMySql. I wrote a php script that will connect to the remote database. Currently i run it on localhost and this makes it of no use on the phone. Can someone tell me what is the best solution to my problem. Is there a way to use remote access on iPage, the database is on another server not iPage. Or can i write an api or something that will run on iPage ? The best thing would be if i can find a free webpage that can host my php script. Had one but its not working anymore. Any suggestions ?
<?php
$username = "qqqq";
$password = "qqqq";
$hostname = "qqq.qqq.qqq.qqq";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("ttbus",$dbhandle)
or die("Could not select examples");
$result = mysql_query("SELECT stations.name, stations.lon, stations.lat, station_display_rows.minutesToArrival,routes.number FROM stations,station_display_rows,routes WHERE stations.id = station_display_rows.stationId AND routes.routeId = station_display_rows.routeId");
while ($row = mysql_fetch_array($result)) {
echo "<h1>";
echo $row{'name'}."<h2>";
echo $row{'lon'}."<h3>";
echo $row{'lat'}."<h4>";
echo $row{'minutesToArrival'}."<p>";
echo $row{'number'};
}
mysql_close($dbhandle);
?>
I am not familiar with iPage, but if you want to access data from a web site, then you should create a REST endpoint that will return your data in JSON format. Your iOS app will then make this connection, grab the data and you can use it in your app. You can store this data in a a local database using Core Data, save it as a file or just use it in memory.
If you need help creating the REST endpoints in PHP, that should be directed to the PHP section or search for some tutorials, there are plenty.
To read the data from your iOS app, you should read this tutorial: NSUrlSession Tutorial DON'T try and use AFNetworking, its overkill for what you need to do.
If you are in shared hosting platform, remote MySQL is not supported in it. It is supported in their VPS/Dedi platform.

ibase_connect: local computer host, can't figure out working path

I may be dumb. Not sure yet.
Trying to do something that should be simple:
$database = '10.10.10.81:?????';
$username = 'admin';
$password = 'pw';
$conn = ibase_connect($database, $username, $password);
if (!$conn)
{
echo "Error while connecting: ".ibase_errmsg();
exit();
}
echo 'workan';
We hit the error: connection rejected by remote interface. From another question here I read that this comes from various things: Could be a user/password problem, could be a host ($database) problem, something else that I forget.
I believe my host string is terribly wrong and can't figure out how I should be going about this. Perhaps my google-fu is not up to par.
Trying to get to
E:\fishbowl\database\data\base.fdb
on 10.10.10.81, a separate local computer
Tried a bunch of combinations but can't seem to make anything work.
Edit: Just a heads up, this is a firebird database. Not sure if that changes things
For windows, it should look like this:
localhost/10095:C:/Data/SKLADFD.FDB.
See how port (in this case 10095) is specified.
In your case:
10.10.10.81/3050:E:/fishbowl/database/data/base.fdb
Path to the file must be local file on server, not windows share on connecting machine.

Cannot connect to my hosting service's MySql database. NB

I am EXTREMELY new to the html/php scene but I have been working at this for hours. I am stumped.
I am trying to connect to a sql database that will store username and password information. I use fortune city for hosting and I have already used their phpAdmin to setup up all of the necessary stuff (db, tables, etc..).
I am using Eclipse with Zend on the side. I am also running Sql Server and Apache 2.2.
I believe my issue is the following:
I have a db located at a certain ip address (remote fortunecity server) and I am testing my project on the local server. Fortune city offers two different host names, one for internal connections and one for external connections. I get different results from each one:
If I connect to the internal site it doesn't make any connection, I know this because of my die statement. If I connect to the external host it connects, but doesn't allow me to connect to the database. (see cases below code)
Currently my process is as follows. (PLEASSSSE TELL ME A BETTER WAY IF I'M DOING THINGS THE INEFFICIENTLY, I feel dirty every time I do it!!)
Create or edit my index.php, login.php, etc... in eclipse.
Copy the files that I edit into my Apache root.
Go back to eclipse and run the project in a browser "firefox."
repeat n to the n times.
Keep in mind my sql database is located on the net
Can this be done? Testing locally while accessing a db on the net?
Here is the code:
<?php
if (!isset($_POST['username']) || !isset($_POST['password'])) {
header( "Location: http://localhost/index.php" );
}
elseif (empty($_POST['username']) || empty($_POST['password'])) {
header( "Location: http://localhost/index.php" );
}
else{
$user = addslashes($_POST['username']);
$pass = md5($_POST['password']);
$dbHost = "mysql3341.dotsterhost.com";
$dbUser = "*********";
$dbPass = "******";
$dbDatabase = "**********";
$db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database.");
mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database.");
$result=mysql_query("select * from userInfo where username='$user' AND password='$pass'", $db);
$rowCheck = mysql_num_rows($result);
if($rowCheck > 0){
while($row = mysql_fetch_array($result)){
session_start();
session_register('username');
echo 'Success!';
header( "Location: checkLogin.php" );
}
}
else {
echo 'Incorrect login name or password. Please try again.';
}
}
?>
Again, I have never made it past
Case :1 $db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database.");
Case :2 mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database.");
Thanks for reading my novel!
Can this be done? Testing locally while accessing a db on the net?
Yes you can, but be aware if you are storing anything sensitive in your database you probably wouldn't want to be sending that data unencrypted over the net. (Unless you are connecting over a VPN or another type of secure network connection.)
Usually you'd want to setup a development environment on your local box or you can edit your files locally in something like Aptana (http://www.aptana.com/) and have it automatically deploy your files to the server every time you save.
Also, as suggested in the comments, using a framework to develop on usually give you a powerful database library without the need to reinvent it on your own. (That is unless you feel like wrapping your own!)

Categories