我正在尝试在认证后向数据库写入数据,但无法成功。
一旦成功登录,我会重定向到index.php
<?php session_start(); if (isset($_SESSION["user_id"])) { $mysqli = require __DIR__ . "/database.php"; $sql = "SELECT * FROM user WHERE id = {$_SESSION["user_id"]}"; $result = $mysqli->query($sql); $user = $result->fetch_assoc(); } ?> <!DOCTYPE html> <html> <head> <title>Home</title> <meta charset="UTF-8"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css@2/out/water.css"> </head> <body> <h1>Home</h1> <?php if (isset($user)): ?> <p>Hello <?= htmlspecialchars($user["name"]) ?></p> <form action="user-input.php" method="post" id="availDates"> <label for="nickName">Nickname:</label> <input id="nickName" name="nickname" /> <label for="startDate">Start Date:</label> <input type="date" id="startDate" name="startdate"> <button type="submit">Submit</button> </form> <p><a href="logout.php">Log out</a></p> <?php else: ?> <p><a href="login.php">Log in</a> or <a href="signup.html">sign up</a></p> <?php endif; ?> </body> </html>
从这里开始,我想捕获一个名字和一个日期并提交,但每次提交后,我在phpmyadmin中查看,表格单元格都是空白的。我正在使用xampp在本地运行。以下是我尝试从表单中捕获输入的代码:
<?php if (empty($_POST["nickname"])) { die("Name is required"); } if (empty($_POST["date"])) { die("Name is required"); } $mysqli = require __DIR__ . "/database.php"; $sql = "INSERT INTO user (nickname) VALUES (?)"; $stmt = $mysqli->stmt_init(); if ( ! $stmt->prepare($sql)) { die("SQL error: " . $mysqli->error); } $stmt->bind_param("sss", $_POST["name"]); if ($stmt->execute()) { echo "successful"; } else { if ($mysqli->errno === 1062) { die("error"); } else { die($mysqli->error . " " . $mysqli->errno); } }
任何帮助都将不胜感激
表单数据具有带有值为“nickname”和“startdate”的
name
属性。我猜你应该正确使用它们来构建插入查询,例如$_POST["nickname"]
和$_POST["startdate"]
如果你仍然遇到问题,请发布完整的错误日志进行调试。