如何连接到mysql数据库[关闭]
问题描述:
How do I connect to a MySQL database in PHP?
- Database name:
NewDB1
- Username :
Mark
- Password :
secret
I have googled a few solutions, but none of them seem to work.
如何在PHP中连接MySQL数据库? p>
- 数据库名称:
NewDB1 code> li>
- 用户名:
标记 code> li>
- 密码:
secret 代码> li> ul>
我搜索了一些解决方案,但似乎都没有。 p> div>
- 用户名:
答
<?php
$servername = "localhost";
$username = "Mark";
$password = "secret";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
答
With PDO -
<?php
// turn on error reporting and display
error_reporting(E_ALL);
ini_set('display_errors', 1);
// define the user
define('USER', 'Mark');
define('PASS', 'secret');
// establish database connection
try {
$dbh = new PDO('mysql:host=localhost;dbname=NewDB1', USER, PASS);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // make sure to turn on error reporting
}
catch(PDOException $e) {
echo $e->getMessage(); // show any error messages.
$errorCode = $e->getCode();
}
?>
This comes from a more detailed tutorial on how to understand and simplify PDO.