Php8.1连接Mariadb数据库及简单查、插、更、删
连接Mariadb数据库
创建数据库filesStation
并新建pic
表1
2
3
4
5
6
7
8
9
10
11CREATE database development;
DROP TABLE IF EXISTS `pic`;
CREATE TABLE `files` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`filename` varchar(255) DEFAULT NULL,
`path` varchar(255) DEFAULT NULL,
`mark` tinyint(3) DEFAULT NULL,
`scale` varchar(255) DEFAULT NULL,
`info` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
连接文件conn.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$dsn = "mysql:host=localhost;dbname=filesStation;charset=utf8mb4";
//$dsn = "mysql:host=localhost;dbname=filesStation";
$options = [
PDO::ATTR_EMULATE_PREPARES => false, // Disable emulation mode for "real" prepared statements
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // Disable errors in the form of exceptions
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // Make the default fetch be an associative array
];
try {
$pdo = new PDO($dsn, "数据库用户名", "数据库密码", $options);
}
catch (Exception $e) {
error_log($e->getMessage());
echo $e;
echo '<br>';
exit('数据库连接失败');
}
操作数据库
操作文件op.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Include the database connection file
include_once("conn.php");
// PHP class
class Contact {
public $id;
public $filename;
public $path;
public $mark;
public $scale;
public $info;
}
// Fetch contacts (in descending order)
$contacts = $pdo->query( "SELECT * FROM pic ORDER BY id DESC")->fetchAll(PDO::FETCH_CLASS, 'Contact');
$query = http_build_query($contacts);
echo $query;
//插入数据
//使用 PDO::prepare 插入 pic
//$stmt = $pdo->prepare("INSERT INTO pic (path, mark, info) VALUES(?, ?, ?)");
//$stmt->execute([$path, $mark, $info]);
//更新数据
//使用 PDO::prepare 更新 contacts
//$stmt = $pdo->prepare("UPDATE pic SET path = ?, mark = ?, info = ? WHERE id = ?");
//$stmt->execute([$path, $mark, $info, $id]);
//删除数据
//使用 PDO::prepare 删除 contacts
//$stmt = $pdo->prepare("DELETE FROM pic WHERE id = ?");
//$stmt->execute([$id]);