简体   繁体   中英

How to Connect to a Mysql database using PHP?

<?php
mysql_connect("localhost", "username", "password") or die(mysql_error());
echo "Connected to MySQL<br />";
?>

This is the code I am using to check if I am able to connect to Mysql.

I am having problem connecting using this code. Should I change localhost to the name of the website?

I tried ("www.abc.com","login username", "password") even this is not working.

EDIT:

Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'mobile4_you'@'cl79.blahblah.com' (using password: YES) in /home/mobilew4/public_html/mysql.php on line 2 Access denied for user 'mobile4_you'@'cl79.blahblah.com' (using password: YES)

If you're using something like cPanel, it will prefix your username and your database with your username for cpanel, for example:

> cPanel login: foo 
> Database User: bar
> Database: ey

Your database user will be foo_bar and your database will be called foo_ey

Localhost refers to where the database is running. If it's running on the same server as your PHP server localhost should work fine. What kind of problems are you having? Are you sure that your username/password is correct?

You should replace :

  • localhost by the name of the server on which your MySQL server is
    • if your MySQL server is on the same server as PHP, then it's localhost
  • username by the login that allows you to access your database
  • password by the corresponding password

Of course, this is supposing you actually have a MySQL server up and running, with a user account created on it.

Didn't you hosting company provide you with any information related to MySQL ? Using those informations, what error message does mysql_error() give ?

Do you have a mysql user which you've set up? You'll need to do that. In cPanel you can do it by clicking on MySQL databases, and on phpMyAdmin you can just add a new user on the start page. Put that users' username and password in.

You need to pay attention to the error, if any, reported by mysql_error() . This should give you some information you can use to diagnose the connection problem.

See this MySQL Forge wiki page about connection failure:

http://forge.mysql.com/wiki/Error2003-CantConnectToMySQLServer

Or this page from the MySQL Manual:

http://dev.mysql.com/doc/refman/5.1/en/can-not-connect-to-server.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM