【问题标题】:Why is my PHP scripts not inserting data into database? Response is "added successfully"为什么我的 PHP 脚本没有将数据插入数据库?响应是“添加成功”
【发布时间】:2022-11-29 08:31:03
【问题描述】:

我有一个包含 4 列客户表的数据库:first_name、last_name、email、phone_number)。我创建了两个文件。 customer.php 具有所有 html,而 customer_db.php 具有连接到数据库和插入数据的所有代码。我知道一些代码是有效的,因为当我输入错误的电话和电子邮件格式时会收到错误消息。当我完成表格时,我得到“客户记录添加成功!”回复。当我检查数据库时,没有输入。我还通过手动添加记录然后尝试在 Web 表单中输入相同的信息来对此进行了测试,这也导致“客户记录添加成功!”

我没能发现脚本有任何问题。脚本在下面列出。第一个是 customer.php。

<?php
//start sessions.
session_start();
// If the user is not logged in redirect to the login page...
if (!isset($_SESSION['loggedin'])) {
    header('Location: index.html');
    exit;
}
?>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Home Page</title>
        <link href="style.css" rel="stylesheet" type="text/css">
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css">
    </head>
    <body class="loggedin">
        <nav class="navtop">
            <div>
                <h1>Brew City Rentals</h1>
                <a href="home.php"><i class="fa-duotone fa-house"></i>MAIN MENU<a/>
                <a href="profile.php"><i class="fas fa-user-circle"></i>Profile</a>
                <a href="logout.php"><i class="fas fa-sign-out-alt"></i>Logout</a>
            </div>
        </nav>
        <div class="content">
            <h2>Customers</h2>
            <p>Enter or edit existing customers</p>
        
            <form action="customer_db.php" method="post" autocomplete="off">
                <div class="input-group">
                    <label>First Name</label>
                    <input type="text" name="first_name" value="">
                
                    <label>Last Name</label>
                    <input type="text" name="last_name" value="">
                
                    <label>Email</label>
                    <input type="text" name="email" value="">
                
                    <label>Phone Number</label>
                    <input type="text" name="phone_number" value="">
                </div>
                <button class="btn" type="submit" name="save" >Save</button>
            </form>
        </div>
    <footer>
    <p>Copyright &copy; <a href="#">Paul's Web Design</a> 2022 | Designed by Paul Bohnhoff | Sponsored by <a href="https://uwm.edu/technology/help/">UMW Help Desk</a> | Valid <a href="http://jigsaw.w3.org/css-validator/">CSS</a> &amp; <a href="http://validator.w3.org/">XHTML</a></p>
    </footer>   
    </body>
</html>
<?php
// DB connection info.
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'bohnhof4_Brew_User1';
$DATABASE_PASS = 'Hjwetyg456$';
$DATABASE_NAME = 'bohnhof4_Brew_City_Rentals2';

// Try and connect using the info above.
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if (mysqli_connect_errno()) {
    // If there is an error with the connection, stop the script and display the error.
    exit('Failed to connect to MySQL: ' . mysqli_connect_error());
}

// Now we check if the data was submitted, isset() function will check if the data exists.
if (!isset($_POST['first_name'], $_POST['last_name'], $_POST['email'], $_POST['phone_number'])) {
    // Could not get the data that should have been sent.
    exit('Please complete the customer form!');
}
// Make sure the submitted registration values are not empty.
if (empty($_POST['first_name']) || empty($_POST['last_name']) || empty($_POST['email']) || empty($_POST['phone_number'])) {
    // One or more values are empty.
    exit('Please complete the customer form');
}

//First name Validation
if (preg_match('/^[a-zA-Z]+$/', $_POST['first_name']) == 0) {
    exit('First name is not valid!');
}

//Email Validation
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    exit('Email is not valid!');
}

//Last name Validation
if (preg_match('/^[a-zA-Z]+$/', $_POST['last_name']) == 0) {
    exit('Last name is not valid!');
}

//Phone number validation
if (preg_match("/[0-9]{3}-[0-9]{3}-[0-9]{4}/", $_POST['phone_number']) == 0) {
    exit('Phone number is not valid! Please enter phone number with area code and dashes.');
}

// We need to check if the email exists.
if ($stmt = $con->prepare('SELECT email FROM accounts WHERE email = ?')) {

    // Store the result so we can check if the account exists in the database.
    if ($stmt->num_rows > 0) {
        // email already exists
        echo 'Email exists, please choose another!';
    } else {

// email doesn't exits, insert new customer record
if ($stmt = $con->prepare('INSERT INTO customers (first_name, last_name, email, phone_number) VALUES (?, ?, ?, ?)')) {
echo 'Customer record added successfully!';
} else {
    // Something is wrong with the sql statement, check to make sure customers table exists with all 4 fields.
    echo 'Could not prepare statement!';
}
    }
    $stmt->close();
} else {
    // Something is wrong with the sql statement, check to make sure customers table exists with all 4 fields.
    echo 'Could not prepare statement!';
}
$con->close();
?>

【问题讨论】:

  • 您已准备好 SQL 语句。您是否设置了准备好的语句的值?
  • 绑定参数和 execute() 在哪里?

标签: php


【解决方案1】:

您将需要添加它来设置准备好的语句的值,然后执行它。

$stmt->bind_param("ssss", $_POST['email'], $_POST['last_name'], $_POST['email'], $_POST['phone_number']);

然后执行你的语句

$stmt->execute();

//After execution, don't forget to close connection.
$stmt->close();

【讨论】:

    猜你喜欢
    • 2018-01-19
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    • 2019-05-03
    • 2012-06-11
    • 1970-01-01
    • 2013-06-22
    相关资源
    最近更新 更多