简体   繁体   中英

Connecting to a specific database using php (xampp / mysql)

I want to run a script that successfully connects to a database. I have xampp, both programs running, I have created a database within phpMyAdmin named "testing" with a user login "root" and password "root" (just for this).

The PHP code:

mysql_connect("localhost", "root", "root") or die("<p>failed: " . mysql_error() . "</p>");

I have no idea what is supposed to go into where "localhost" is and can't find an answer. I've tried several different options. Including pointing directly to the damn thing "localhost/xampp/mysql/data/testing".

localhost is your own machine. If you're using Xampp you most likely won't need to change it.

Besides from opening a connection to the db host, you still need to select a database name (the one you created with phpmyadmin)

mysql_select_db('testing');

Since you're just starting I don't want to annoy you with the rant about the old mysql_ functions to be deprecated. But once you get the basics, try to switch to PDO mysql, the learning curve is the same and you'll avoid wasting your time.

The first parameter to mysql_connect is the host for your MySQL server. Since you are developing locally, localhost or 127.0.0.1 is probably what you want, unless you want to connect to a remove MySQL server. Both of these addresses will loopback to your own computer, where you should be running your MySQL service.

Also, you may want to consider using MySQLi or PDO . mysql_connect and the related functions are deprecated in PHP 5.5.

Note that the MySQL extension has been deprecated since PHP 5.5 in favor of PDO MySQL or MySQL Improved .

Using for example MySQLi, in your case the connection statetement should read:

$mysqli = new mysqli("localhost", "root", "root", "testing");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

More information here .

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