PHP操作MySQL資料庫
前言
在正式開始學習前,我們需要開啟mysqli擴展,使用phpinof()你可以看到如下展示就說明開啟成功:

若沒有看到mysqli擴展在windows服務器下,打開php.ini檔案,將php_mysqli.dll打開即可,
注意:
從PHP7開始默認不再支持mysql擴展,即不再支持mysql_*系列函式,請使用mysqli連接資料庫,
mysqli即支持php5也支持php7,
創建表結構:
mysql> create table if not exists users (
-> id int(10) unsigned primary key auto_increment not null,
-> username varchar(30),
-> password varchar(100),
-> createtime varchar(40) not null,
-> createip binary(16)
-> );
Query OK, 0 rows affected (0.02 sec)
index.html 代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP操作MySQL資料庫</title>
</head>
<body>
<form action="connect.php" method="post">
用戶名:<input type="text" name="username"><br />
密碼:<input type="password" name="password"><br />
重復密碼:<input type="password" name="repassword"><br />
<input type="submit" value="提交">
</form>
</body>
</html>
connect.php代碼如下:
<?php
if (trim($_POST['password']) != trim($_POST['repassword'])) {
exit('兩次密碼不一致,請回傳上一頁');
}
$username = trim($_POST['username']);
$password = md5(trim($_POST['password']));
$time = time();
$ip = $_SERVER['REMOTE_ADDR'];
$conn = mysqli_connect('localhost', 'root', '123456');
//如果有錯誤,存在錯誤號
if (mysqli_errno($conn)) {
echo mysqli_error($conn);
exit;
}
mysqli_select_db($conn, 'php');
mysqli_set_charset($conn, 'utf8');
$sql = "insert into users(username,password,createtime,createip)
values('" .$username. "','" .$password. "','" .$time. "','".$ip."')";
//echo $sql.PHP_EOL;
$result = mysqli_query($conn, $sql);
if ($result) {
echo '資料寫入成功'.PHP_EOL;
} else {
echo '資料寫入失敗';
}
echo '當前用戶插入的ID為:' . mysqli_insert_id($conn);
mysqli_close($conn);
?>
list.php代碼如下:
<?php
$conn = mysqli_connect('localhost', 'root', '123456', 'php');
if (mysqli_errno($conn)) {
mysqli_error($conn);
exit;
}
mysqli_set_charset($conn, 'utf8');
$sql = "select id,username,createtime,createip from users order by id desc";
//進行降序排序
$result = mysqli_query($conn, $sql);
if ($result && mysqli_num_rows($result)) {
//查詢出來的行數可以使用mysqli_num_rows,這個函式要求傳入$result查詢的結果變數,
//如果有結果則顯示串列,如果沒有結果我們產生一句提示即可,
echo '<table width="800" border="1">';
while ($row = mysqli_fetch_assoc($result)) {
//使用到的函式是mysqli_fetch_assoc,回傳的會是一個關聯陣列,
//這個函式讀取一個結果集,會向后移動一次,讀取到最后沒有結果的時候會回傳bool值的false,因此,我們選擇while來配合mysqli_fetch_assoc,
//每次回圈的結果賦值給$row,$row中是關聯陣列,因此我在這次回圈中,可以將行和列都顯示出來,
echo '<tr>';
echo '<td>' . $row['username'] . '</td>';
echo '<td>' . date('Y-m-d H:i:s', $row['createtime']) . '</td>';
echo '<td>' . long2ip($row['createip']) . '</td>';
echo '<td><a href="edit.php?id=' . $row['id'] . '">編輯用戶</a></td>';
echo '<td><a href="delete.php?id=' . $row['id'] . '">洗掉用戶</a></td>';
echo '</tr>';
}
echo '</table>';
} else {
echo '沒有資料';
}
mysqli_close($conn);
?>
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/148962.html
標籤:其他
下一篇:分布式鎖-資料庫實作
