I want to connect to a remote MySQL instance (a Google Cloud SQL one) by using its IPv6 address.
I'm using PHP PDO like that:
$db = new \PDO('mysql:host=<ipv6-address>;port=3306;dbname=<database-name>',
'<username>',
'<password>'
);
But it always fails with the following exception message:
PDOException: SQLSTATE[HY000] [2002] No route to host
From the terminal I can connect to the MySQL instance, without any issue, like this:
mysql --host=<ipv6-address> --user=<username> --<password>
Any help will be really appreciated.
Thanks
In case anyone else stumbles over the same problem, and to save them 2 hours delving through PHP source, PDO MySQL IPv6 connections work if you put square brackets around the address.
See: https://github.com/php/php-src/blob/master/main/streams/xp_socket.c#L568
e.g.
$pdo = new PDO("mysql:host=[1234:5678::42];port=3306;dbname=foo", ...);
Reading this https://www.saotn.org/php-mysql-and-ipv6-still-slow/ gives the following idea:
Knowing that, normally, IPv6 takes precedence over IPv4 (which is configurable), users are left with a slow responding website and database operations, only because connecting to an IPv6 address in PHP is refused, and the connection refused isn’t handled correctly, making the fallback to IPv4 slow. It takes mysql.connect_timeout seconds
Note: the source does seem credible
Also, this is a good read: http://dev.mysql.com/worklog/task/?id=798
Support should be added for MySQL to work over IPv6
("Internet Protocol Version 6").
This means:
- users can connect with IPv6. this is partly a connector problem.
- storage of user address information, e.g. in mysql.user, can be in IPv6 format
- the proposed new data types CIDR and INET allow IPv6 format as described in WL#2037 "Add CIDR and INET data types"
- functions like inet_ntoa() need revision
Try using this for your PDO conenction and see if it works.
$dbh = new PDO('mysql:host=<ipv6-address>;port=<port>;dbname=<dbname>', <dbusername>, <dbpassword>);
In case if fails, you can better use try...catch to get exactly at the error
<?php
try {
$dbh = new PDO('mysql:host=<ipv6-address>;port=<port>;dbname=<dbname>', <dbusername>, <dbpassword>);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
Related
In TestLink, I found a NO_DSN option in Database connection in installNewDB.php script. I never heard of NO_DSN and would like to know if someone can explain it to me:
see Lines 163 - 180 (https://github.com/viglesiasce/testlink/blob/master/install/installNewDB.php):
// Connect to DB Server without choosing an specific database
$db = new database($db_type);
define('NO_DSN',FALSE);
#$conn_result = $db->connect(NO_DSN,$db_server, $db_admin_name, $db_admin_pass);
if( $conn_result['status'] == 0 )
{
echo '<span class="notok">Failed!</span><p />Please check
the database login details and try again.';
echo '<br>Database Error Message: ' . $db->error_msg() . "<br>";
close_html_and_exit();
}
else
{
echo "<span class='ok'>OK!</span><p />";
}
$db->close();
$db=null;
What does it mean here?: define('NO_DSN',FALSE);
and here: $db->connect(NO_DSN,$db_server, $db_admin_name, $db_admin_pass);
In this case DSN refers to 'Data source name'.
It can be an optional connection string that you pass to the database to set additional options like db driver, host, db name, charset, port, etc..
An example of a DSN string using PDO would be like this:
mysql:host=localhost;dbname=test;port=3306;charset=utf8mb4
So in your case it looks like the 'NO_DSN' option is defaulting to false unless you specify the connection string.
DNS is a server that translates websites' addresses so that your browser can connect to them. If the addresses become out-of-date or theserver has issues, you'll encounter aDNS error and won't be able to connect to a specific site or group of sites even with Internet access.
I have one file on one web serve and my phpmyadmin SQL databases on a seperate server and am currently trying to connect to my external serve but it doesnt seem to work.
I keep getting the error message:
'Access denied for user ''#'localhost' (using password: NO)'
and am not sure what this means.
Any help would be greatly appreciated or even an article to get started on figuring this out since I cant seem to find anything myself.
Thank you
EDIT --- PDO SCRIPT ---
My PDO Script is the generic one from w3, I have place holders for security reasons.
<?php
$servername = "externalIP";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=Reservations", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
you have to find your phpmyadmin page where you login using also a password.
Try this one :if you have not assign password into database for specific user then you just have to apply 'root' as user and leave blank password field and also set your hostname as 'localhost' or 127.0.0.1
also remember that you have to start first apache and mysql services before access.
If you are using remote server as database then not required.in that case you have to apply your remote Ip address and also remember that in that remote server if you have not specific user then leave password as blank. one another way to debug mysql connection into your remote server creating mysql connection file with its required paramter to check that your remote server ok or not.
This error will come most probably because of user permission issue. Make sure you have privilege to that user for that database.
I am trying to set up a new site on my hosting (Host route if it matters) but i keep getting this error when i try using PDO (first PDO site im trying):
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected' in /home/kennyi81/public_html/gamersite/login.php:36 Stack trace: #0 /home/kennyi81/public_html/gamersite/login.php(36): PDOStatement->execute() #1 {main} thrown in /home/kennyi81/public_html/gamersite/login.php on line 36
When i use these settings:
$dbh = new PDO("mysql:91.146.107.11;dbname=kennyi81_gamersite", "kennyi81_gamer", "***************");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
....
$stmt = $dbh->prepare('SELECT * FROM USERS WHERE ID = :id LIMIT 1');
How the database is laid out:
I am able to use mysqli connect fine on my other sub domains / main site, but i just cannot get PDO to work.
I've tried this, which i have seen around:
$stmt = $dbh->prepare('SELECT * FROM gamersite.USERS WHERE ID = :id LIMIT 1');
but it retuns a syntax error.
Anyone have any idea what may be causing this?
This is all working on my local server, nothing changed on upload apart from connect line.
Instead of:
$dbh = new PDO("mysql:91.146.107.11;dbname=kennyi81_gamersite", "kennyi81_gamer", "***************");
Try:
$dbh = new PDO("mysql:host=91.146.107.11;dbname=kennyi81_gamersite", "kennyi81_gamer", "***************");
(add host=)
And it most likely works on your local server, because you have mysql:localhost... or mysql:127.0.0.1... there and it's ignored (cause it's missing host= aswell) and by default it's localhost.
From the PDO manual page, you can see that you need to wrap the connection in a try/catch block. This way if something goes wrong with the connection, it will tell you. Something like this:
try {
$dbh = new PDO("mysql:91.146.107.11;dbname=kennyi81_gamersite", "kennyi81_gamer", "***************");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
// Then actually do something about the error
logError($e->getMessage(), __FILE__, __LINE__);
emailErrorToAdmin($e->getMessage(), __FILE__, __LINE__);
// etc.
die(); // Comment this out if you want the script to continue execution
}
The reason you are getting this error is because there is an error with your connection, but since you don't tell your script to stop, it doesn't. Look at the error message produced, and how to fix it should be made obvious. It appears that Michael Prajsnar's answer is correct in that you aren't setting a "host".
Edit:
As it turns out, PDO doesn't complain if you leave out your host or dbname in the PDO connection DSN part (at least on Unix). I tested it and leaving it blank will default it to "localhost" and I was therefore able to connect perfectly fine leaving this out completely for localhost connections, which would explain why it worked on your local server but not on your production server. In fact, it is completely possible to connect supplying absolutely nothing in the DSN except for the database engine like this:
$dbh = new PDO("mysql:", "kennyi81_gamer", "***************");
The only problem is that it won't be using a database, so to USE a database, just do:
if ($dbh->query("USE kennyi81_gamersite") === false)) {
// Handle the error
}
However with that said, I have my doubts that you actually tried connecting using a try/catch block (as you mention in your comments) unless you somehow provided valid database credentials. The ONLY way that doing it this way did not produce any sort of error is if you actually connected correctly and selected the database kennyi81_gamersite. If not, you would have seen a message like this:
Unable to connect to database. "mysql" said: SQLSTATE[28000] [1045]
Access denied for user 'kennyi81_gamer'#'localhost' (using password: YES)
In summary, always wrap your connection in a try/catch block if you want to find errors during connection. Just make sure not to re-throw (and not catch) the PDOException's getMessage() or you could expose your login credentials.
Is it possible to connect to a database lying on different server through another server ?
For example :-
I want to access the users table of www.abc.com from www.xqz.com, both are on different server.
Can you give me any ideas ?
will really appreciate if provide me the php query to connect.
Thanks.
"Is it possible" is a bit over-reaching, I think. To give you the shortest answer, yes, it is possible. However, whether or not you could do it depends on a lot of variables, not least of which is whether your hosting providers allow it. For instance, I use Hostmonster for Linux hosting, and to remotely access my MySQL database I have to first whitelist the IP address of the machine that will be accessing it.
Most hosting services provide a F.A.Q. section that should do a decent job of answering this particular question for you. Some will even provide support technicians help you set it up (Hostmonster does, within reason).
HTH.
Try This :
<?php
// Server in the this format: <computer>\<instance name> or
// <server>,<port> when using a non default port number
// Suppose your "www.abc.com" has an IP = 192.168.1.1
// So to connect, do something like this :
$server = '192.168.1.1,PORT_NUMBER'; // FOR WINDOWS
$server = '192.168.1.1:PORT_NUMBER'; // FOR LINUX
// Connect to MSSQL
$link = mssql_connect($server, [username], [password]);
if (!$link) {
die('Something went wrong while connecting to MSSQL');
}
?>
I have a Master - Slave setup for a web application written in PHP. I have a pool of slaves I use for reading, and a Master that is used for writes (and reads if a write has been sent this request). I would like to incorporate an automated system for removed crashed servers from the read pool. Currently I am using:
foreach($readers as $reader)
{
$fp = #fsockopen($reader['host'],3306,$errno,$errstr,1);
if(!$fp)
{
//Remove from pool
}
unset($fp);
}
My primary question is there a more reliable method. I have had quite a few false positives, and vice versa because it is not actually checking for a MySQL server, but rather just a connection on port 3306. Is there a way to check for a MySQL server without raising an exception, which is the behaviour of the PDO and MySQLi extensions in PHP.
You could just use mysql_connect() and check the result for false, and close the connection right away on success. You can make a dummy account with no privileges for that if you like.
That's really the only reliable way, especially if you want to distinguish a running MySQL server from any other random process listening on port 3306.
You could use mysql_ping() to check if a current DB Connection you have open is still alive
Here is the example posted at http://www.php.net/manual/en/function.mysql-ping.php
<?php
set_time_limit(0);
$conn = mysql_connect('localhost', 'mysqluser', 'mypass');
$db = mysql_select_db('mydb');
/* Assuming this query will take a long time */
$result = mysql_query($sql);
if (!$result) {
echo 'Query #1 failed, exiting.';
exit;
}
/* Make sure the connection is still alive, if not, try to reconnect */
if (!mysql_ping($conn)) {
echo 'Lost connection, exiting after query #1';
exit;
}
mysql_free_result($result);
/* So the connection is still alive, let's run another query */
$result2 = mysql_query($sql2);
?>
The best way to check if any service is alive is to actually use it. So for MySQL try to connect and execute some fast query, for web server try to fetch some file, for PHP try to fetch some simple script...
For MySQL master/slave setup, one of the solutions is to actually check the state of replication. You can check how many transactions is the slave behind master and decide to stop using that slave when/while it has old data. (I don't do the replication myself, but I think you need to compare the variables Read_Master_Log_Pos and Relay_Log_Pos)