本文目录一览:
php怎么连接mysql
连接到一个 MySQL 数据库
在您能够访问并处理数据库中的数据之前,您必须创建到达数据库的连接。
在 PHP 中,这个任务通过 mysql_connect()
函数完成。
语法
mysql_connect(servername, username, password);
参数
参数名 | 描述 |
---|---|
servername | 可选。规定要连接的服务器。默认是 "localhost:3306"。 |
username | 可选。规定登录所使用的用户名。默认值是拥有服务器进程的用户的名称。 |
password | 可选。规定登录所用的密码。默认是 ""。 |
php连接mysql
public function getInfo(){
$this->userName = $this->userInfo["name"];
$this->userPSW = $this->userInfo["password"];
$this->userAge = $this->userInfo["age"];
$this->userGrade = $this->userInfo["grade"];
}
你这里不对吧,应该是:
$this->userName = $this->userInfo[0]["name"];
$this->userPSW = $this->userInfo[0]["password"];
$this->userAge = $this->userInfo[0]["age"];
$this->userGrade = $this->userInfo[0]["grade"];
就算你只取一条数据,也还是一个数组,所以要加下标 0
。
php如何连接mysql
用 mysql 的函数库 第一步 连接数据库
mysql_connect('localhost', 'username', 'password')
第二步 设置字符集
mysql_set_charset('utf8');
第三步 选择数据库
mysql_select_db('DB_name');
第四步 准备 SQL 语句
$sql = 'select * from table_name';
第五步 执行 SQL 语句
$result = mysql_query($sql);
第六步 解析数据
$data = mysql_fetch_array($result);
最后一步 关闭数据库连接
mysql_close();
以上是数据库最基本操作,不过 mysql 这套函数库将要被淘汰,建议改用 mysqli 或则 pdo。
如何在PHP中连接MySQL数据库
php链接mysql必备条件:
- 已安装 mysql 数据库;
- 检查 php 环境是否已开启 mysql 扩展(一般情况下是开启的);
- 检查方法:
- a. 使用
phpinfo();
函数,看有没有 mysql 项; - b. 打开
php.ini
文件,检查php_mysql.dll
前分号是否已取掉。 php链接代码如下:
- a. 使用
<?php
// 设置编码格式
header("Content-type:text/html;charset=utf-8");
// 定义数据库主机地址
$host = "localhost";
// 定义 mysql 数据库登录用户名
$user = "root";
// 定义 mysql 数据库登录密码
$pwd = "";
// 链接数据库
$conn = mysql_connect($host, $user, $pwd);
// 对连接进行判断
if(!$conn){
die("数据库连接失败!" . mysql_errno());
} else {
echo "数据库连接成功!";
}
?>