Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have a PHP script which I use to connect to a MySQL database. Connection through mysql_connect works perfectly, but when trying with PDO I get the following error:
SQLSTATE[HY000] [2005] Unknown MySQL server host 'hostname' (3)
the code I use to connect is below:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$hostname_localhost ="hostname";
$database_localhost ="dbname";
$username_localhost ="user";
$password_localhost ="pass";
$user = $_GET['user'];
$pass = $_GET['pass'];
try{
$dbh = new PDO("mysql:host=$hostname_localhost;dbname=$database_localhost",$username_localhost,$password_localhost);
echo 'Connected to DB';
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("SELECT check_user_company(:user,:pass)");
$stmt = $dbh->bindParam(':user',$user,PDO::PARAM_STR, 16);
$stmt = $dbh->bindParam(':pass',$pass,PDO::PARAM_STR, 32);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row)
{
echo $row['company_id'].'<br />';
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Thanks in advance
Got the same problem. Mine solution was another database port. I wrote localhost:1234 and got this error.
Fixed with:
mysql:host=$hostname_localhost;port=1234;dbname=$database_localhost",$username_localhost,$password_localhost);
echo 'Connected to DB';
It does seem pretty straightforward, here is what I use to build my PDO connectors(noticed your dbname and host are done differently than mine, dunno if that's relevant, but worth a check):
PDO Creation function
require_once('config.inc.php');
function buildDBConnector(){
$dsn = 'mysql:dbname='.C_BASE.';host='.C_HOST;
$dbh = new PDO($dsn, C_USER, C_PASS);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
config.inc.php
define('C_HOST','localhost');// MySQL host name (usually:localhost)
define('C_USER','sweetUsername');// MySQL username
define('C_PASS','sweetPassword');// MySQL password
define('C_BASE','superGreatDatabase');// MySQL database
And while it makes no sense, when I tried to declare $dsn inline including variables during the newPDO call, I kept getting failures too. I broke it apart and used the $dsn variable to do so. And haven't had an issue since.
Wondering if you're in shared hosting by chance?
NOTE:
If you don't have a dedicated IP, and instead are going through a NAT, your IP won't properly translate to your actual server.
That help at all?
UPDATE:
Just thought of another thing. Are you trying to connect to a mysql database that is on a different IP than you are running your scripts from? If so, you will likely need to enable remoteSQL access for the ip you are calling the database from. Fairly easy to do, but CRITICAL if you are not accessing localhost.
You dont seem to specify the database host dns details or IP address. Adding that will solve the problem
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm making a website that uses SQL and PHP functionalities. How do I connect to a database?
I would advise you begin by looking here.
You need to ensure that you have created user credentials with the correct permissions to query the database before you try this. You can do this through the cPanel of your web server (I'm going to assume you are using a web hosted server for this question).
Once you have a working and tested connection to the database, you can then start looking at the mySQLi documentation here. Which will show you how to execute and retrieve results from a database query and how to handle the returned data with PHP.
I see you are seriously downvoted.
I learned it the hard way and I am still learning to post here.
Stack sites are supposed to be searched first. If your question is already answered then people downvote you.
The solution to your question:
In your mysql or phpmyadmin you can set whether you use a password or not. The best way to learn is to set mysql with a password in my opinion. If you will launch a website online finally, you have to take security measures anyway.
If you make contact to your mysql database with you have to set:
username, password, database and servername ( for instance localhost).
The most secure way is using the OOP / prepared method:
$servername ='localhost';
$username='yourname';
$password='12345';
$dbname='name_database';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($stmt = $conn->prepare("SELECT idnum, col2, col FROM `your_table` WHERE idnum ='5' ")) {
$stmt->execute();
$res = $stmt->get_result();
$qrow = mysqli_num_rows($res);
while ($row = mysqli_fetch_assoc($res)) {
var_dump($qrows); // number of rows you have
$total = implode(" / " , $row);
var_dump($total);
$idnum = $row['idnum'];
var_dump($idnum);
}
The easiest way that I do with my site is make a file called db.php containing:
<?php
$host = 'localhost';
$user = 'root';
$pass = 'password';
$db = 'databasename';
$mysqli = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
..then in the index.php file, at the top:
<?php
require_once('db.php')
?>
I just installed MAMP and have created a MYSQL database. I can access it via PHPMYADMIN.
In my php page I have this, pasted directly from the MAMP webstart page--
$user = 'root';
$password = 'root';
$db = 'local_db';
$host = 'localhost';
$port = 3306;
$link = mysql_connect(
"$host:$port",
$user,
$password
);
$db_selected = mysql_select_db(
$db,
$link
);
The resulting page stops at this point, won't print anything below these instructions.
I've tried changing the port in the MAMP preferences. I also included or die("Could not connect"); after the first line, but still don't get any text after the link data in the page.
I checked online, and others with the problem at least see the die text. I don't get that.
I haven't changed any passwords or data other than mess with the port number.
Any help would be appreciated!
Please give the following a try, I have developed and tested it locally, functionality within has been documented to help you understand what is going on in every step.
/**
*
* Modern method of connecting to a MySQL database and keeping it simple.
*
* If you would like to learn more about PDO,
* please visit http://php.net/manual/en/book.pdo.php
*
*/
//Set up database connection constants, so they cannot be changed.
define('DBHOST','127.0.0.1'); //Change this to the ip address of your database
define('DBNAME','test'); // Change this to the database name you are trying to connect to.
define('DBUSER','databaseuser'); // Insure this user is not the root user!!!!
define('DBPASS','databasepassword'); // Insure this is not the root password!!!!
//Let's try to connect to the database first.
try {
//Initiate a new PDO object called $MYDB and pass it the proper information to make
//the connection
$MYDB = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME."", DBUSER, DBPASS);
//If we are successful show it :D for the test page, if this is for production you should not show this.
echo "Database connection was successful.";
//If this does not worth catch the exception thrown by PDO so we can use it.
} catch(PDOException $e) {
//Show that there was an issue connecting to the database. Do not be specific because,
//user's do not need to know the specific error that is causing a problem for security
//reasons.
echo "Oh, sorry there was an issue with your request please try again.";
//Since we had an issue connecting to the database we should log it, so we can review it.
error_log("Database Error" . $e->getMessage());
}
//Since this is 100% php code we do not need to add a closing php tag
//Visit http://php.net/manual/en/language.basic-syntax.phptags.php for more information.
If you have any issues with this please attempt to break it up into smaller pieces while reviewing the PDO documentation.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have been trying to connect to a mysql database many different ways but no matter how I do it I get an error. I'm pretty new to php so it might be my mistake but I would appreciate any help.
<?php
$servername = "localhost";
$username = "xyz";
$password = "1234567";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
All of the information is correct but it returns Connection failed: Access denied for user 'xyz'#'localhost' (using password: YES)
mysqli_connect($serverName,$Username,$Password,$Database);
Try appending your database name to the final parameter
Solutions:
Have you granted your user access to the database schema?
Have you ensured you're using the correct password/user?
Have you ensured your server name is correct? (Not localhost,
possibly an external IP?)
A possible solution would be try the server IP, as DNS can sometimes fail. Incase you was unaware, localhost IP is 127.0.0.1
Put localhost into quotes:
mysql_connect('localhost',$username,$password);
The error message Access denied for user 'xyz'#'localhost' (using password: YES) is an indication that either the password is wrong or the user xyz has not been installed as descibed in the manual: https://dev.mysql.com/doc/refman/5.6/en/adding-users.html
The username and password you specified is not registered as a database administrator.... the default username is root and password is blank
basically you did not set up permission correctly, double check host.
run
select user,host from mysql.user;
to check what is host address you provided
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have a function that handles my db connection. In casse my main DB isn't available I want to use a backup one.
I tried to do so using below code but it's not working...
$host = 'xxx';
$database = 'xxx';
$login = 'xxx';
$pass = 'xxx';
if (! mysql_connect( $host, $login, $pass ) )
{
// try to connect to backup db
$host = 'yyy';
$database = 'yyy';
$login = 'yyy';
$pass = 'yyy';
mysql_connect ( $host, $login, $pass ) or die ( "Failed to connect to the database: " . mysql_error());
}
mysql_select_db ( $database ) or die ( "Failed to find the database" . mysql_error());
mysql_query("SET NAMES 'utf8'");
I'm sure about my connection parameters, so the problem isn't there
Edit:
I'm using an old version of php so I'm limited to Mysql_*
My 1st server is currently down, and I'm getting a 'Warning: mysql_connect() [function.mysql-connect]: Too many connections in ...' error
In fact my problem is that I need NOT to print this warning message if the 1st connection failed...
Please note Mysql_* is deprecated, use mysqli_ or PDO which is far more secure.
Have you tried outputting the error? I don't see it in your code.
I haven't used mysql_ for a long time, but try outputting the error using:* mysql_error()
As mentioned, it could be a variety of problems:
Mysql isn't started
Firewall is blocking the connection
Not using default port
...
Edit:
Also you may want to look into setting up replecation for such events as DB failure.
Don't do this in your code, just use something like MySQL Proxy to do it for you.
When php fails to connect, it generates a warning, which stops the php execution.
You may use #mysql_connect (function name prefixed with an "#") to avoid the warning. And your code will continue to execute, even if first sql server does not respond. crappy, but working.
I am trying to connect to a MySQL server using PHP's 'mysql_connect()' function, but the connection fails. This is my code:
$con = mysql_connect("example.net", "myusername","") or die("Could not connect: ".mysql_error());
I placed this code inside a PHP script, which I try to open using a web browser (the script is stored on a remote host which has PHP enabled) but it doesn't work. It doesn't return the die error either. Echoing something before the $con successfully outputs in the browser, whereas nothing outputs after that line. If I type:
mysql -h example.net -u myusername
from a remote machine, I could connect to the DB without any problem and do queries and other modifications.
Update :
I also tried this after some suggestion, but no improvement:
<?php
$usern = "myusername";
$dbh = new PDO('mysql:host=servername.net;dbname=test', $usern, "");
echo $usern;
?>
What operating system is the remote host running PHP using? Perhaps MySQL isn't enabled in php.ini. Also, please don't use mysql_* functions for new code. They are no longer maintained and the community has begun the deprecation process (see the red box). Instead, you should learn about prepared statements and use either PDO or MySQLi. If you can't decide which, this article will help you. If you care to learn, this is a good PDO tutorial.
Have you tried using PDO or the MySQLi interface? If you're trying to learn PHP, you should not be using the mysql_* functions regardless. See if you can access the database by using a line similar to this:
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
If you need more detailed documentation, this code comes directly from the documentation itself.
EDIT: Also, try using PDO's error checking functionality. This example creates a database connection using PDO and tries to perform a simple query. It doesn't use prepared statements or any of those features, so it's not production-ready code (i.e. *don't just throw this into your code without understanding how to improve it) and you'll need to edit it to include a SELECT query that's relevant to your database, but it should at least tell PDO to provide more information about the errors it encounters.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "admin";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// query
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM booksa";
$q = $conn->query($sql) or die("ERROR: " . implode(":", $conn->errorInfo()));
$r = $q->fetch(PDO::FETCH_ASSOC);
print_r($r);
?>
Is the php file located on the same server as the mysql database, if so you might have to use 'localhost' as the first argument for mysql_connect() instead the external address.