如题所述
php连接mysql 分为面向过程和面向对象的。
以下三种方式都可以连接
一 MySQLi - 面向对象
<?php$servername = "localhost";
$username = "username";
$password = "password";
// 创建连接$conn = new mysqli($servername, $username, $password);
// 检测连接if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);} echo "连接成功";
?>
二 MySQLi - 面向过程
<?php$servername = "localhost";
$username = "username";
$password = "password";
// 创建连接$conn = mysqli_connect($servername, $username, $password);
// 检测连接if (!$conn) {
die("Connection failed: " . mysqli_connect_error());}echo "连接成功";
?>
三 PDO方式
<?php$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
echo "连接成功";
}catch(PDOException $e){
echo $e->getMessage();
}
?>
连接在脚本执行完后会自动关闭。你也可以使用以下代码来关闭连接:
MySQLi - 面向对象
$conn->close();
MySQLi - 面向过程
mysqli_close($conn);
PDO
$conn = null;
温馨提示:答案为网友推荐,仅供参考
第1个回答 2017-03-20
这个很简单的。
原生php:
mysql_connect('连接地址【如果是本地一般是:localhost】','数据库账号【本地一般默认是:root】','数据库密码【本地一般默认是:root】');//连接数据库
mysql_select_db('数据库名字');//选择数据库
原生php:
mysql_connect('连接地址【如果是本地一般是:localhost】','数据库账号【本地一般默认是:root】','数据库密码【本地一般默认是:root】');//连接数据库
mysql_select_db('数据库名字');//选择数据库
第2个回答 2016-11-22
<?php
$db_server = "localhost";
$db_user = "root";
$db_pwd = "password";
$db_name = "test";
$sql = "select * from user where username='admin'";
$conn = mysql_pconnect($db_server, $db_user, $db_pwd);
$my_db = mysql_select_db($db_name, $conn);
$result = mysql_query($sql, $conn);
$userInfo = mysql_fetch_array($result);
mysql_close($conn);
?>本回答被提问者采纳
$db_server = "localhost";
$db_user = "root";
$db_pwd = "password";
$db_name = "test";
$sql = "select * from user where username='admin'";
$conn = mysql_pconnect($db_server, $db_user, $db_pwd);
$my_db = mysql_select_db($db_name, $conn);
$result = mysql_query($sql, $conn);
$userInfo = mysql_fetch_array($result);
mysql_close($conn);
?>本回答被提问者采纳