Connecting to MySQL database from a different network? - php

I've created a database using Microsoft Azure Portal (MySQL Database).
Currently I'm using PHP to connect to the database.
$servername = "server.mysql.database.azure.com";
$username = "username#server";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname, 3306);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
SQL queries to populate data in JSON format.
$sql = "SELECT id, username, score FROM ScoreTable";
$result = $conn->query($sql);
$dbdata = array();
while ( $row = $result->fetch_assoc()) {
$dbdata[]=$row;
}
echo json_encode($dbdata);
Result (localhost/jubakee.php OR http://192.168.1.7/jubakee.php (local IP) both produce the same results).
[{"id":"1","username":"Stacey","score":"500"},
{"id":"2","username":"SJ","score":"600"}]
The issue I am having is that I want to be able to access this database from different networks e.g on 3G/4G or my friend's house.
When trying to load http://192.168.1.7/jubakee.php on my android device it will only produce the results if I'm on the same network as my PC (Same Wi-Fi Network).
When I switch my network from Wi-Fi to Mobile Data (3G) I can no longer access the database and http://192.168.1.7/jubakee.php will not load.
The purpose of this is so I can create an online database which will interact with my C# android application. The database will store the scores of the users.
How can I allow users using different networks to connect to my database?
Thank you.

You can't not access the xamp server from your cellular data or different wifi networks. You have to upload your database and files in a live server like 000webhost then you will have a url like http://YOURWEBSITE.000webhost.com/jubakee.php. Now you can access this url from anywhere, anytime and in any applications.

Related

How to connect Firebase database to Php scripts?

I am making an android app with Firebase database, and I am stuck at point when I want to connect that Firebase database with my own hosted Php scripts in which I want to perform some action on specific date , on that date it should delete some data from Firebase. FIrebase data on schedule(On specific date) so I am stuck at how to perform this how can be make this connection to firebase database with Php.
Using connection of php, I want to made connection with firebase DB and want to retrieve and also delete some data from Firebase DB.
<?php
define('HOST','localhost');
define('USERNAME', 'root');
define('PASSWORD','');
define('DB','insert2');
$con = mysqli_connect(HOST,USERNAME,PASSWORD,DB);
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "insert into users (username, password) values ('$username','$password')";
if(mysqli_query($con, $sql)){
echo 'success';
}
?>
Please guide me. thanks
You can't connect to Firebase Database with the same way as MySQL.
You need to use one of these lib :
kreait/firebase-php
ktamas77/firebase-php
Or use the REST API.
Or create a Firebase Cloud Function which delete your wanted data and call it from the php with an HTTP trigger.
You can use this php code
$db = 'IP:C:/folders/files.FDB'; // Computer IP:Database file in drive and folders
$username = 'user';
$password = 'pass';
// Connect to database
$dbh = ibase_connect($db,$username,$password);
$sql = 'SELECT * FROM TABLE';
// Execute query
$rc = ibase_query($dbh, $sql);
// Get the result row by row as object
while ($row = ibase_fetch_object($rc)) {
echo $row->table_column;
}
// Release the handle associated with the result of the query
ibase_free_result($rc);
// Release the handle associated with the connection
ibase_close($dbh);
*And don't forget to install firebase extension to Web Server because it is not enabled by default.

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.

Setting up MySQL database for website

I am making a website that will use a MySQL database on a friend's web hosting service. It supports PHP and MySQL but I'm not sure what file I am meant to create the database and table in. I understand the syntax so I just need to know where and which files to do it in. I guess you don't put it in the website's html files because it only needs to be created once.
I have the following code:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = mysqli_connect($servername, $username, $password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "CREATE DATABASE LeagueData";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
You don't have to create a file. You have to create the DB and structure from within MySQL (or you can load a .sql file into MySQL).
If he has phpMyAdmin use that. It's much easier.
Creating a table from within MySQL: http://dev.mysql.com/doc/refman/5.7/en/creating-tables.html
Importing an .sql file from the commandline: mysql -u username -p database_name < file.sql
Adding on to Patrick's answer:
You need to create your database first, and not through PHP. mysqli allows you to connect to a particular database (which you need to specify in your code), and then execute queries on that database.
First, create a database. You should consult your web-hosting provider on how to do this. Most web-hosts allow you to create a database through one of the CPanel modules. (You'll also have to create a "user", and assign that user to the newly created database.)
Once you have created the database, you will be able to connect to it via PHP. Your code to connect to the database should look like:
$conn = mysqli_connect($servername, $username, $password, $database_name);

php connecting to two databases on diff servers and using insert select

hi I need some help what I am trying to do is using insert select statement like this where databases are on diff servers.
insert into db1.copy2 (c1,c2) select c1,c2 from db2.copy2;
db1 is on amazon web service relation database and db2 is on local host(wamp) how can i make a PHP script that can accommodate two databases like that and that will allow me to execute a query like that. this script will execute on local host
thanks..
There are many pieces of software for syncronising or copying data between to database servers, maybe you should use one of those. Otherwise you could just do it in 2 steps
in pseudo code
$sql = "select c1,c2 from db2.copy2";
$Results = pdofetchall($sql);
foreach ($Results as $row){
$c1 = $row['c1'];
$c2 = $row['c2'];
$InsertSQL = "insert into db1.copy2 VALUES($c1,$c2) ";
executesql($InsertSQL);
}
Note this is pseudo code and defintitely cannot be copied and pasted, but give you the gist of what you need to do.
You have 3 options:
If you can connect the 2 servers via a vpn network or ssh connection so that the 2 servers can directly see each other, then you can use federated table engine:
The FEDERATED storage engine lets you access data from a remote MySQL
database without using replication or cluster technology. Querying a
local FEDERATED table automatically pulls the data from the remote
(federated) tables. No data is stored on the local tables.
This solution would enable the syntax you used in the question.
Again, you have to enable direct connection between the 2 servers and you set up replication between the 2 servers, essentialky making sure that the data available on the localhost is copied to the amazon server. The query would run on the amazon server and would query the copied data.
You combine data within php from the 2 data sources either by directly connecting to both instances or by setting up a web-based api on local server that can be used to transfer data from the local server to amazon.
you can do this easily if your 2 database on the same server, just make a connection to one database and pass your query easily:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "insert into db1.copy2 (c1,c2) select c1,c2 from db2.copy2;";
this will work for you

Can't select database table even though the code is right

I am trying to display a list of my vbulliten threads on a non-vbulliten portion of my site. However I can't select the vbulliten database:
<?php
$host = "localhost";
$user = "my username";
$pass = "my password";
$dbname = "tableprefix_forum";
mysql_connect($host, $user, $pass) or die ("Could not connect to database server.");
mysql_select_db($dbname) or die ("Could not select database.");
?>
I am substituting some things here in this example but all my credentials are correct including my db server username, password and forum db name. So what is the problem? Is it due to some internal security feature in vbulliten, does this system not allow you to connect to it's db if the page trying to connect to it is a non-vbulliten page?
Vbulletin has NO control over the permissions given by the server. But you do need to make sure that the user/pass you are using has been granted permission to access the database you are requesting.

Categories