I have this simple code:
<?php
//Open the mySQL connection
$conn_string = "'localhost', 'Vale', 'test'";
$dbh = mysql_connect($conn_string);
//Check that a connection with the DB has been established
if (!$dbh)
{
die("Error in MySQL connection: " . mysql_error());
}
...
And I get the error: Error in MySQL connection: php_network_getaddresses: getaddrinfo failed: The requested name is valid, but no data of the requested type was found.
I cannot figure out what the problem is, I have been google-ing but all the suggestions have failed (tried 127.0.0.1 instead of localhost, 127.0.0.1:3306, etc.)
I have code that works with postgre, but I need to use mysql, and I am trying to modify it, but I cannot pass the first line and get a connection. Any suggestion, please? Thank you!
mysql_connect doesn't take a comma seperated string. It takes 3 individual strings.
Change it to this:
$dbh = mysql_connect($server, $mysql_user, $password);
If you absolutely have a comma separated string, and can't get around this, you can split the string like this:
$config = str_replace("'", '', $conn_string); // replace the quotes.
$config = preg_split('/,/', $conn_string); // split string on ,
if($config != $conn_string) { // make sure this returned an array
count($config) === 3 OR die("Invalid database configuration string");
$dbh = mysql_connect($config[0], $config[1], $config[2]);
if(FALSE === $dbh) {
die("Coult not connect: " . mysql_error());
}
}
You might want to consider MySQLi, instead of MySQL.
<?php
$dbh=mysqli_connect("localhost","Vale","Password","test"); /* Vale is your username? And the name of your database if test, right? And your Username's Password is blank? */
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
?>
As other users have pointed out mysql_connect expects the database, username, and password as separate arguments rather than a single string.
I think another highly important issue to point out is that this particular extension is deprecated.
Please see: http://uk1.php.net/function.mysql-connect
A better solution would be to use mysqli_connect: http://uk1.php.net/manual/en/function.mysqli-connect.php
$db = mysqli_connect( 'localhost', 'Vale', 'test', 'yourDatabaseName' );
mysql_connect requires three argument not single string
$dbh = mysql_connect('localhost', 'Vale', 'test');
Related
I'm running this code on GoDaddy webhosting and I'm getting 'The database could not be found' echoed.
Obviously the database in question can't be selected, even though I've privileged the user and checked the db name.
I don't get anything out of here mysqli_error()
$db= 'test2' ;
$con = mysqli_connect('whatever','whatever','whatever') or die ('The connection to the database could not be established.');
mysqli_select_db($db , $con) or die ('The database could not be found' . mysqli_error());
As per the mysqli_select_db documentation, it expects the parameters this way:
mysqli_select_db ( mysqli $link , string $dbname ) : bool
So your parameters are put in backwards, change it to this:
mysqli_select_db($con, $db) ...
Or, alternatively, just select the database inside mysqli_connect().
$con = mysqli_connect('whatever','whatever','whatever', $db) ...
Side note, your die() isn't really doing anything, you won't get an actual error code out of that. To use mysqli_error(), you need to pass your database handle:
die('There was an error: ' . mysqli_error($con));
For the die() that is attached to mysqli_connect(), you should do this:
die('There was an error: ' . mysqli_connect_error());
I already have my database named als and I still got the error.
<?php
$mysql_host='localhost';
$mysql_user='root';
$mysql_password='';
$mysql_db='als';
$con = #mysql_connect($mysql_host,$mysql_user,$mysql_password) or die(mysql_error());
#mysql_select_db($mysql_db) or die(mysql_error());
?>
Not exactly an answer to your question but too long for a comment:
After establishing the database connection you could just query the existing databases via SHOW DATABASES
<?php
$mysqli = new mysqli('localhost', 'root', '');
if ($mysqli->connect_errno) {
trigger_error('query failed: '.$mysqli->connect_error, E_USER_ERROR);
}
$result = $mysqli->query('SHOW databases')
or trigger_error('connect failed: '.join(',', $mysqli->error_list), E_USER_ERROR);
foreach( $result as $row ) {
echo join(', ', $row), "<br />\r\n";
}
Does your database als show up?
Since you're using the default root account (with an empty password; you might want to look into that as well) there shouldn't be any permission related problems. So, if the database doesn't show up, it's just not there...
(almost) same script using PDO (my weapon of choice) instead of mysqli:
<?php
$pdo = new PDO('mysql:host=localhost;charset=utf8', 'root', '', array(
PDO::MYSQL_ATTR_DIRECT_QUERY => false,
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));
foreach( $pdo->query('SHOW DATABASES', PDO::FETCH_NUM) as $row ) {
echo $row[0], "<br />\r\n";
}
There you go. The mysql_ family has been deprecated for some time. Please change to the mysqli_ library. Another machine may work because it's using an older version of PHP in which it hasn't been deprecated OR where deprecated warnings have been globally supressed.
MySQLI Connect
In the wild
$mysql_host='localhost';
$mysql_user='root';
$mysql_password='';
$mysql_db='als';
$con= mysqli_connect($mysql_host,$mysql_user,$mysql_password, $mysql_db) or die("Error " . mysqli_error($con));
There's no need to arbitrarily select the database anymore. Now you can use $con as an argument to the mysqli_ family of procedural functions.
Last, but not least, never debug with the # symbol. This suppresses the error warnings from the function it precedes.
I have read a lot about this but it still doesn't work.
I'm just trying to select a database to create a new table in, I try:
$db = mysqli_select_db("test");
if(!$db) {
echo "error: " . mysqli_error($db);
}
But I still get an error (and mysqli_error($db) doesn't seem to work).
Of course I have already connected to it:
$con=mysqli_connect("localhost", "administrator", "****");
On phpMyAdmin I have these databases:
Why can't I select "test" ?
And creating a database doesn't work because I don't have the rights, as you can see.
The procedular signature of this function is:
bool mysqli_select_db ( mysqli $link , string $dbname )
So you will have to provide the resource you got back from the mysqli_connect() to make it work. Something like this:
$con = mysqli_connect("localhost", "administrator", "****");
$success = mysqli_select_db($con, "test");
Alternatively you could specify the database on the connect call with a 4th argument:
$con = mysqli_connect("localhost", "administrator", "***", "test");
See the examples on mysqli_connect().
mysqli_select_db function requires two parameters link and dbname. Please refer to the documentation:
http://php.net/manual/en/mysqli.select-db.php
You are only passing link and no database name in your call:
$db = mysqli_select_db("test");
Got a problem! Though I found almost similar threads but none helped :(
I've written a php script to fetch the number of registered users from my MySQL database. The script is working great in my localhost; it is using the given username,pass and host name which are "root", "root", and "localhost" respectively, but the script is not using the given username/pass/host rather using root#localhost (password: NO) in Live server.
In the Live server I created a MySQL user, set an different password, and hostname there is of course not localhost. I updated the script with my newly created mysql users data. BUT, whenever I run the script, I see that the script is still using "root", "root", and "localhost"!!
take a look at the script:
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
$db = mysql_select_db ("regdb",$conn); //Oops, actually it was written this way in the script. I misstyped it previously. now edited as it is in the script.
//Query to fetch data
$query = mysql_query("SELECT * FROM regd ");
while ($row = mysql_fetch_array($query)):
$total_regd = $row['total_regd'];
endwhile;
echo $total_regd;
-- Some says to change the default username and pass in the config.ini.php file located in phpMyAdmin directory. Would this help?? I didn't try this because either my hosting provider didn't give me privilege to access that directory (because I am using free hosting for testing scripts) or I simply didn't find it :(
Please help....
Foreword: The MySQL extension is marked as deprecated, better use mysqli or PDO
Though you store the connection resource in $conn you're not using it in your call to mysql_query() and you're not checking the return value of mysql_connect(), i.e. if the connection fails for some reason mysql_query() "is free" to establish a new default connection.
<?php
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
if ( !$conn ) {
die(mysql_error()); // or a more sophisticated error handling....
}
$db = mysql_select_db ("regdb", $conn);
if ( !$db ) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
//Query to fetch data
$query = mysql_query("SELECT * FROM regd ", $conn);
if (!$query) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
while ( false!=($row=mysql_fetch_array($query)) ):
$total_regd = $row['total_regd'];
endwhile;
echo $total_regd;
edit: It looks like you're processing only one row.
Either move the echo line into the while-loop or (if you really only want one record) better say so in the sql statement and get rid of the loop, e.g.
// Query to fetch data
// make it "easier" for the MySQL server by limiting the result set to one record
$query = mysql_query("SELECT * FROM regd LIMIT 1", $conn);
if (!$query) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
// fetch data and output
$row=mysql_fetch_array($query);
if ( !$row ) {
echo 'no record found';
}
else {
echo htmlspecialchars($row['total_regd']);
}
First of all:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
What is your mysql_error()? :)
for a project I need to open a Mysql connection, close it and let old legacy code run after that. The legacy code have it's own connection, and just call mysql_query($sql) without the resource parameter.
How can I handle this? Can I set a Mysql connexion as the global one? Must I re-execute the mysql_connect() statement? The legacy code can't be refactored just now.
Here a short demo
<?php
function show()
{
$a = mysql_fetch_array(mysql_query('select database()'));
echo $a[0] . "<br>";
}
$conn = mysql_connect('localhost', 'root', '', TRUE);
mysql_select_db('dredd');
show();
mysql_connect('localhost', 'root', '', TRUE);
mysql_select_db('afup');
show();
mysql_close();
$a = mysql_fetch_array(mysql_query('select database()', $conn));
echo $a[0] . "<br>";
show();
The first select is ok, the second two, the third is ok because it have the ressource, but the fourth broke ("Access denied for user 'ODBC'#'localhost' (using password: NO)").
Regards, Cédric
If you don't specify the connection it will use the last created one, so it should be ok if you close the other connection first, e.g.
//open your db connection
$conn1 = mysql_connect();
mysql_query($sql, $conn1);
mysql_close($conn1);
//open legacy code's db connection
$conn = mysql_connect();
//run legacy code
If you are having problems it might be easier to use PDO or mysqli for the second connection, because then you know they are definately separate without modifying the legacy code.