[MySqli擴展]⑥--添加用戶

test.php

<?php
$mysqli = new mysqli('localhost', 'root', '', 'test');
if ($mysqli->connect_errno) {
    die('CONNECT ERROR : ' . $mysqli->connect_error);
}
$sql = "SELECT id,username,age FROM user";
$mysqli_result = $mysqli->query($sql);
if ($mysqli_result && $mysqli_result->num_rows > 0) {
    while ($row = $mysqli_result->fetch_assoc()) {
        $rows[] = $row;
    }
}
?>
<html>
<head>
    <title>Document</title>
</head>
<body>
<h2>用戶列表-<a href="addUser.php">添加用戶</a></h2>
<table border="1" cellpadding="0" cellspacing="0" width="80%" bgcolor="#ABCDE">
    <tr>
        <td>編號</td>
        <td>用戶名</td>
        <td>年齡</td>
        <td>操作</td>
    </tr>
    <?php $i = 1;
    foreach ($rows as $row): ?>
        <tr>
            <td><?php echo $i ?></td>
            <td><?php echo $row['username']; ?></td>
            <td><?php echo $row['age']; ?></td>
            <td><a href="editUser.php">更新</a>|<a href="doAction.php">刪除</a></td>
        </tr>
        <?php $i++;endforeach; ?>

</table>
</body>

</html>

addUser.php

<html>
<head>
    <title>addUser</title>
</head>
<body>
<h2>添加用戶</h2>
<form action="doAction.php?act=addUser" method="post">
    <table border="1" cellspacing="0" cellpadding="0" bgcolor="#ABCDEF" width="80%">
        <tr>
            <td>用戶名</td>
            <td><input type="text" name="username" placeholder="請輸入用戶名" required="required"></td>
        </tr>
        <tr>
            <td>密碼</td>
            <td><input type="password" name="password" placeholder="請輸入密碼" required="required"></td>
        </tr>
        <tr>
            <td>年齡</td>
            <td><input type="number" name="age" min="1" max="125" placeholder="請輸入合法年齡" required="required"></td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit"value="添加用戶"></td>
        </tr>
    </table>
</form>
</body>

</html>

doAction.php

<?php
header("Content-type:text/html;charset=utf-8");
$mysqli = @new mysqli('localhost', 'root', '', 'test');
if ($mysqli->connect_errno) {
    die($mysqli->connect_error);
}
$mysqli->set_charset('utf8');
$username = $_POST['username'];
$username = $mysqli->escape_string($username);//轉義
$password = md5($_POST['password']);
$age = $_POST['age'];
$act = $_GET['act'];

switch ($act) {
    case "addUser":
        $sql = "INSERT INTO user(username,password,age) VALUES('{$username}','{$password}','{$age}') ";
        $res = $mysqli->query($sql);
        if ($res) {
            $insert_id = $mysqli->insert_id;
            echo "<script type='text/javascript'>
                alert('添加成功,網站的第{$insert_id}位用戶');
                location.href='test.php';</script>";
        } else {
            echo "<script type='text/javascript'>
                alert('添加失敗,請重新添加');
                location.href='addUser.php';</script>";
        }
        break;

}

?>
Paste_Image.png
Paste_Image.png
Paste_Image.png
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容