Target machine actively refuses mysqli database connection - php

I'm in the process of implementing a system for database table replication. I'm aware of the latter MySQL technique but I couldn't get it working. What I have now is essentially a preliminary implementation.
This is the code I have thus far.
//This is where DBHandler is defined
$documentRoot=$_SERVER['DOCUMENT_ROOT'];
require_once($documentRoot."/Classes/DBHandler.php");
$src_controller = new DBHandler();
$query = "SELECT * FROM table";
$temp = $src_controller->select($query);
//Convert temporary database contents into usable result
while($rowObject=mysql_fetch_object($temp)){
$result[]=$rowObject;
}
//Create database handler to handle database
$dest_controller = new mysqli("ip address", "user", "password", "database name");
if($mysqli->connect_errno){
$errorMessage = sprintf("'%s'", $mysqli->connect_error);
echo $errorMessage;
}
else{
$dest_controller->query("DELETE * FROM table");
//Processing of data goes here
foreach($result as $item){
//Create query to insert individual records
$start = "INSERT INTO table(field1, field2...) VALUES (";
$end = sprintf("'%s', %d, %d, %f, %f)", field1, field2...);
$start .= $end;
//Database handler uses $start to insert record
$dest_controller->query($start);
}
$dest_controller->close();
}
The database being read from is on a different server from the one being written to. I tried checking the host for the target database with the command "SHOW VARIABLES WHERE Variable_name = 'hostname'" and wound up with a site that just gives a "sorry, wrong page or we've moved" page. What's more is that the port number I see in the URL doesn't match up with what the "SHOW VARIABLES WHERE Variable_name = 'port'" command gives me. The latter command says 3306.
I'm not really sure what to do. We use cPanel X to connect to the database and there's an option to allow select IPs remote access to this database. I'm positive I granted access to the right addresses but this accomplished nothing.
Is this some kind of issue with the host or did I not use the right IP address for connection when I created the mysqli object?

If the MySQL port open on that server? Check with this:
telnet yoursever.address.com 3306
If telnet doesn't connect, then the port is blocked and you will need your hosting provider to open it up.

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.

How to decrease connection count to mySql DB on a remote server? My system must send data every second or two

My first post, because I haven't found answer to this problem anywhere! And i looked way beyond Google.. :)
DESCRIPTION:
So I have a set-up where an arduino device is connected to a laptop via USB serial cable and the laptop is connected to internet.
Like this: http://postimg.org/image/cz1g0q2ib/
arduino ---USB---> laptop (transit.py) ---WWW---> server (insert.php)-> mysql DB
There is a python script (transit.py) on the pc running continuously and listening to the COM port, analyzing received data and forwarding it to a file (insert.php) on a remote server (a free hosting site)
See code to learn how that works...
Then there is the insert.php script that receives this data (still almost every second), analyzes it and stores it in the mySql database.
This, however, is not the only file that requires mySql connection, therefore i include connect.php at the beginning of every such file.
PROBLEM:
Warning: mysqli::mysqli() [mysqli.mysqli]: (42000/1226): User 'user' has exceeded the 'max_connections_per_hour' resource (current value: 1500) in /server/connect.php on line 8
As a result of all this data travel and it's frequency (and cheapness of the hosting) i run into a "maximum connections per hour exceeded" error. The limit is 1500 per hour and i can't change it (it's a remote server). And no, i don't want to pay for hosting to get a bigger allowance - that's not the point- the issue is inefficiency of my code. Can i have one, persistent connection? Like a service?
Sending data from python script straight to remote mysql is not an option, because i don't have access to this feature.
CODE:
transit.py:
try:
ser = serial.Serial('COM4',9600,timeout=4)
except:
print ('=== COULD NOT CONNECT TO BOARD ===')
value = ser.readline()
strValue = value.decode("utf-8")
if strValue:
mylist = strValue.split(',')
print(mylist[0] + '\t\t' + mylist[1]+ '\t\t' + mylist[2])
path = 'http://a-free-server.com/insert.php'
dataLine = {"table": mylist[0], "data": mylist[1], "value": mylist[2]}
toServer = requests.post(path, params=dataLine, timeout=2)
insert.php:
<?php
include 'connect.php';
//some irrelevant code here...
if (empty($_GET['type']) && isset($_GET['data'])) {
$table = $_GET['table'];
$data = $_GET['data'];
$value = $_GET['value'];
if($mysqli->connect_errno > 0){
die('Unable to connect to database [' . $mysqli->connect_error . ']');
}
else
{
date_default_timezone_set("Asia/Hong_Kong");
$clock = date(DATE_W3C);
if (isset($_GET['time'])) {
$time = $_GET['time'];
}
else{
$time = $clock;
}
echo "Received: ";
echo $table;
echo ",";
echo $data;
echo ",";
echo $value;
echo ",";
echo $time;
if ($stmt = $mysqli->prepare("INSERT INTO ".$table." (`id`, `data`, `value`, `time`) VALUES (NULL, ?, ?, ?) ON DUPLICATE KEY UPDATE time='".$time."'"))
{
$stmt->bind_param('sss', $data, $value, $time);
$stmt->execute();
$stmt->free_result();
$stmt->close();
}
else{
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
}
}else{
echo " | DATA NOT received!";
}
?>
connect.php:
<?php
define("HOST", "p:a-free-host.com"); // notice the p: for persistence
define("USER", "user");
define("PASSWORD", "strongpassword1"); // my password. don't look!
define("DATABASE", "databass");
$GLOBALS["mysqli"] = new mysqli(HOST, USER, PASSWORD, DATABASE, 3306);
$count = intval(file_get_contents('conns.txt'));
file_put_contents('conns.txt', ++$count); //just something i added to monitor connections
?>
P.S. Everything works fine and all data is handled in a rather desirable manner, except for exceeding the limit and perhaps some other hidden caveats.
Any suggestion on how to decrease the connection count but still receive data every second?
If I have understood your issue correctly, your web host sucks. If you are limited to 1500 connections / hour, and each page requires a connection, that means you can never exceed 1500 page views per hour; that's not very much.
Many programming languages support connection pooling; in this model, the server opens one or more connection at start-up, and individual page requests get one of those connections when they need them. This reduces the overhead of opening and closing connections. See here for a discussion of connection pooling and PHP. You may be able to use one of the answers without too much trouble.
The alternative - and probably better - solution is to batch up data in your Python scripts so you don't have to connect to the web server so often. The classic waty to do this for applications that aren't time critical is to use a message bus. I'm not a Pythonist, but this should do the job...
Did you try to create a script that is all the time alive(here you make the connection)(S1) and then the rest?
(S2)
In the script that you are doing the operations first check if the connection is alive and if is not redo connection.
Close the connection in S1 at the end of the script.

JSON decode to MySQL working on localhost but not Online Server

My code is as follows, I have changed the values of the Mysql login.
$json_url = "https://www.bitstamp.net/api/ticker/";
$json_data = file_get_contents($json_url);
$json_feed = json_decode($json_data);
$bitstamp_btc_low = $json_feed->low;
$bitstamp_btc_high = $json_feed->high;
$bitstamp_btc_ask = $json_feed->ask;
$bitstamp_btc_volume = $json_feed->volume;
$timestamp = date('Y-m-d H:i:s');
$connection = mysqli_connect("localhost",'username','password','database');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($connection,
"INSERT INTO `database` (Timestamp, Low, High,
Ask, Volume)
VALUES ('$timestamp', '$bitstamp_btc_low',
'$bitstamp_btc_high', '$bitstamp_btc_ask',
'$bitstamp_btc_volume')");
mysqli_close($connection);
When I execute the code on my localhost server it works fine, inserts the data in to the database, in the format i require and its great. When i upload it to my server though, it does not. The only column it enters data into is the '$timestamp' column. (I have set an independent request for the date, away from the default Mysql entry.) So it makes me believe that this information is being received from the script. Its just the low, high, ask and volume that is returning a 0 value.
I have contacted the API provider and they have confirmed that my host IP has not been black listed and all is well.
Im baffled as to why this is not working online, but it is offline, and just to confirm, even though its not entering the data into the cells, it is creating a new row just with 0 values.
I have just run through the error log and i am getting these errors PHP Notice: Trying to get property of non-object in /home/wpdhcskl/public_html/cron-jobs/cron_bitstamp.php on line #
# being the lines with;
$bitstamp_btc_low = $json_feed->low;
$bitstamp_btc_high = $json_feed->high;
$bitstamp_btc_ask = $json_feed->ask;
$bitstamp_btc_volume = $json_feed->volume;
Many thanks
You've got a database called database? Okay....
Anyways try putting ` around the field names as sometimes different environmens have different setups...
INSERT INTO `database` (`Timestamp`, `Low`, `High`, `Ask`, `Volume`)
Also you should really escape your values and use something like PDO.

WAMP MySQL PDO_extension error

I want to connect MySQL database using PDO Extension. I am using PHP 5.4
$db = new PDO('mysql:host=localhost:8080;dbname=films_db;charset=UTF-8', 'root', '');
$query = "SELECT * FROM employee";
$result = $db->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
print_r($row);
}
$result->closeCursor();
But, my WAMP server is not responding. I am not getting any result. Its "Waiting for localhost" state and getting server timeout error.
Pls help me to resolve this. Thanks.
Port 8080 is for http,
normally it does not used for mysql.
and the default mysql port is 3306.
You might need to check your mysql setting to "confirm" the actual port being used.
Beside this, you might need to check how many record in the table employee.
If millions of records, it might be the reason it takes time to load.

how i can Import data from Database ( My Sql) to another website

I need to show data from another website in my website,
i had control panel for tow site but i need it dynamic way to connect them
website 1 website 2
***** *****
* A * <<<< =Data== * B *
***** *****
so i write
$link = #mysql_connect("Ip Addres to another website","username for mysql 2","passowrd 2 ")or die("Couldn't make connection.");
#mysql_select_db("qatarlab_test",$link)or die("Couldn't select database");
$factorRes = #mysql_query("SELECT count(id) FROM `factor` ");
$factorRow = #mysql_fetch_array($factorRes);
echo $factorRow[0];
but nothing happen
Firstly, you must enable remote database connection in the original site so that the new site can connect to it. you can do this in the control panel->Database(Remote Database Connection) of the original site.
You could specify the IP or domain of the new site to that it allows only the new site to connect or you could just add wildcard (%) to allow any external connection to the database.
when this is done, run ur query again.
hope it helps
Hi Please try code given below,
$link = #mysql_connect("Ip Addres to another website","username for mysql 2","passowrd 2 ")or die("Couldn't make connection.") or die(mysql_error());
mysql_select_db("qatarlab_test",$link)or die("Couldn't select database", $link) or die(mysql_error());
$factorRes = #mysql_query("SELECT count(id) FROM `factor` " , $link) or die(mysql_error());
$factorRow = #mysql_fetch_array($factorRes);
echo "<pre>";
print_r($factorRow);
echo "</pre>";
Here $link will be for specific database connection and die(mysql_error()) for if any error in or query or database connection.
thanks
In your first line: mysql_connect you are passing the IP Address and Username for connecting the DB.
Make sure that the user has the privilege to connect to the DB remotely (i.e. via a machine other than the Localhost). In general, when a user is added in the DB its default access is for the localhost. Check out this link: http://dev.mysql.com/doc/refman/5.1/en/adding-users.html
You basically need to add user using: CREATE USER 'admin'#'IP Address of Website 1'; All the CPanel's have this provision in their interface as well.

Categories