配置 config.php
配置Mysql连接参数后,引入文件此就可以操作Mysql了
$mysql = [
'host' => '127.0.0.1:3306',
'db' => 'testdb', // 数据库
'db_user' => 'root', // 用户名
'db_pwd' => 'root', // 密码
];
mysql_connect($mysql['host'], $mysql['db_user'], $mysql['db_pwd']);
mysql_select_db($mysql['db']);
mysql_query('set names utf8');
查询
引入配置文件,查询数据库的内容
include('./config.php');
$sql = 'select * from cinema';
$res = mysql_query($sql);
$data = array();
while ( $line = mysql_fetch_assoc($res) ) {
$data[] = $line;
}
print_r($data);
添加
INSET INTO 表名 (字段1,字段2,…) VALUES (内容1,内容2,…)
$sql = "INSERT INTO `cinema` (`movie`, `description`, `rating`) VALUES ('Ice song', 'Fantacy', '8.6')";
if( mysql_query($sql) ){
echo '添加成功';
}
更新
UPDATE 表名 SET 字段1 = 内容1 , 字段2 = 内容2 WHERE(条件) id = n
更新 id 等于 4的内容
$sql = "UPDATE `cinema` SET `movie`='Singer', `rating`='8.8' WHERE (`id`='4')";
$status = mysql_query($sql);
删除
DELETE FROM 表名 条件 id = n
删除 Id 等于 4 的数据
$sql = "DELETE FROM `cinema` WHERE (`id`='4')";
$status = mysql_query($sql);
执行成功返回状态1
Mysql函数详解:
mysql_fetch_array() 和 mysql_fetch_assoc() 和mysql_fetch_row() 函数之间的区别 ?
示例数据:
INSERT INTO `testdb`.`cinema` (`id`, `movie`, `description`, `rating`) VALUES ('1', 'War', 'great 3D', '8.9');
mysql_fetch_array()
函数从结果集中取得一行作为关联数组,或数字数组,或二者兼有
Array(
[0] => 1
[id] => 1
[1] => War
[movie] => War
[2] => great 3D
[description] => great 3D
[3] => 8.9
[rating] => 8.9
)
mysql_fetch_assoc
函数从结果集中取得一行作为关联数组
Array(
[id] => 1
[movie] => War
[description] => great 3D
[rating] => 8.9
)
mysql_fetch_row()
函数从结果集中取得一行作为数字数组。
Array(
[0] => 1
[1] => War
[2] => great 3D
[3] => 8.9
)