Unable to successfully write to MySQL database after PHP authentication
P粉221046425
P粉221046425 2023-09-13 09:54:01
0
1
586

I am trying to write data to the database after authentication but cannot succeed.

Once successfully logged in, I will redirect to 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>

From here, I want to capture a name and a date and submit it, but after each submission, I view it in phpmyadmin and the table cells are blank. I'm using xampp to run locally. Here is the code I am trying to capture input from the form:

<?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);
    }
}

Any help would be greatly appreciated

P粉221046425
P粉221046425

reply all(1)
P粉517814372

The form data has a name attribute with the values ​​"nickname" and "startdate". I guess you should use them correctly to build insert queries like $_POST["nickname"] and $_POST["startdate"]

If you still have problems, please post the full error log for debugging.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template