-1

我正在尝试为我正在创建的继续教育网站注册客户,并且需要将多个条目添加到 phpMyAdmin 表“用户”以进行注册。我正在尝试添加多个条目,总共 25 个。

正如您将看到的,我尝试了mysqli_multi_query()将它们全部添加的功能,但我无法为这些条目创建新记录。

它表明我已连接到数据库,并且我已将代码中的所有值与表中的值进行了检查,并且它们是有序的。所以我的问题是:

  • 每个表的条目有限制吗?
  • 与多行登录页面相比,一次添加几个条目是否更好?
  • 我是否试图在一个文件中做太多事情并且需要拆分我的工作?

我得到的错误:

You are connected to the database. Error: INSERT INTO users (myName, home1, home2) VALUES (?, ?, ?);INSERT INTO users (city, ste, zip) VALUES (?, ?, ?);INSERT INTO users (email, certification, experience) VALUES (?, ?, ?);INSERT INTO users (employer, marketing, gender) VALUES (?, ?, ?);INSERT INTO users (dob, recert, full_name) VALUES (?, ?, ?);INSERT INTO users (phone, bHome1, bHome2) VALUES (?, ?, ?);INSERT INTO users (bCity, bState, bZip) VALUES (?, ?, ?);INSERT INTO users (payment, cardNum, expDate) VALUES (?, ?, ?);INSERT INTO users (pwd) VALUES (?);
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?, ?, ?);INSERT INTO users (city, ste, zip) VALUES (?, ?, ?);INSERT INTO users (' at line 1

到目前为止的代码验证所有条目,检查是否有空白条目,并使用函数 test-input。感谢您提供任何帮助,包括学习 PHP 的资源,这些资源对您的教育更有效。在此先感谢您的收听。

<?php
// Defined variables for validation
$myNameErr = $home1Err = $home2Err =$cityErr = $steErr = $zipErr = $emailErr = "";
$certificationErr = $experienceErr = $employerErr = $marketingErr = "";
$genderErr = $dobErr = $recertErr = $full_nameErr = $phoneErr = $bHome1Err = ""; 
$bHome2Err = $bCityErr = $bStateErr = $bZipErr = $paymentErr = $cardNumErr = "";
$expDateErr = $pwdErr = $pwd2Err = "";
$myName = $home1 = $home2 = $city = $ste = $zip = $email = "";
$certification = $experience = $employer = $marketing = "";
$gender = $dob = $recert = $full_name = $phone = $bHome1 = ""; 
$bHome2 = $bCity = $bState = $bZip = $payment = $cardNum = "";
$expDate = $pwd = $pwd2 = "";

// Validating fields by checking if fields are empty
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Checks full name
    if (empty($_POST['myName'])) {
        $myNameErr = "Name required.";
    } else {
        $myName = test_input($_POST['myName']);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z-' -.]*$/", $myName)) {
            $myNameErr = "Only letters and white space allowed";
        }
    }
    // Checks address
    if (empty($_POST['home1'])) {
        $home1Err = "Address required.";
    } else {
        $home1 = test_input($_POST['home1']);
    }
    // Checks additional address input
    if (empty($_POST['home2'])) {
        $home2 = test_input($_POST['home2']);
    }
    // Checks for city
    if (empty($_POST['city'])) {
        $cityErr = "City is required.";
    } else {
        $city = test_input($_POST['city']);
    }
    // Checks for state
    if (empty($_POST['ste'])) {
        $steErr = "State is required.";
    } else {
        $ste = test_input($_POST['ste']);
    }
    // Checks for zipcode
    if (empty($_POST['zip'])) {
        $zipErr = "Zip code is required.";
    } else {
        $zip = test_input($_POST['zip']);
    }
    // Checks for email and if format is correct
    if (empty($_POST['email'])) {
        $emailErr = "Email is required.";
    } else {
        $email = test_input($_POST['email']);
        // check if e-mail address is well-formed
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailErr = "Invalid email format";
        }
    }
    // Confirms the current email
    if (empty($_POST['email2'])) {
        $email2Err = "Confirm your email.";
    } else {
        $email2 = test_input($_POST['email2']);
        // check if e-mail address is well-formed
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $email2Err = "Invalid email format";
        }
        // Check if emails match
        if ($email != $email2) {
            $email2Err = "Emails don't match!";
        }
    }
    // Checks for modality certification
    if (empty($_POST['certification'])) {
        $certificationErr = "Current certification is required.";
    } else {
        $certification = test_input($_POST['certification']);
    }
    // Checks for years of experience
    if (empty($_POST['experience'])) {
        $experienceErr = "Years of experience are required.";
    } else {
        $experience = test_input($_POST['experience']);
    }
    // Checks for the current employer
    if (empty($_POST['employer'])) {
        $employerErr = "Current employer required.";
    } else {
        $employer = test_input($_POST['employer']);
    }
    // Input about how they heard about us
    if (empty($_POST['marketing'])) {
        $marketing = "";
    } else {
        $marketing = test_input($_POST['marketing']);
    }
    // Checks for gender
    if (empty($_POST['gender'])) {
        $genderErr = "Gender required.";
    } else {
        $gender = test_input($_POST['gender']);
    }
    // Check the date of birth
    if (empty($_POST['dob'])) {
        $dobErr = "Date of birth required.";
    } else {
        $dob = test_input($_POST['dob']);
    }
    // Checks their end of certification date
    if (empty($_POST['recert'])) {
        $recertErr = "Recertification date required.";
    } else {
        $recert = test_input($_POST['recert']);
    }
    // Checks name as in credit card
    if (empty($_POST['full_name'])) {
        $full_nameErr = "Name as written in credit card required.";
    } else {
        $full_name = test_input($_POST['full_name']);
    }
    // Checks for phone number
    if (empty($_POST['phone'])) {
        $phoneErr = "Phone number is required.";
    } else {
        $phone = test_input($_POST['phone']);
    }
    // Billing Information
    // Checks for billing address
    if (empty($_POST['bHome1'])) {
        $bHome1 = "";
    } else {
        $bHome1 = test_input($_POST['bHome1']);
    }
    // Checks for billing address 2
    if (empty($_POST['bHome2'])) {
        $bHome2 = "";
    } else {
        $bHome2 = test_input($_POST['bHome2']);
    }
    // Checks for billing city
    if (empty($_POST['bCity'])) {
        $bCity = "";
    } else {
        $bCity = test_input($_POST['bCity']);
    }
    // Checks for billing state
    if (empty($_POST['bState'])) {
        $bState = "";
    } else {
        $bState = test_input($_POST['bState']);
    }
    // Checks for billing zip code
    if (empty($_POST['bZip'])) {
        $bZip = "";
    } else {
        $bZip = test_input($_POST['bZip']);
    }
    // Checks for payment mode
    if (empty($_POST['payment'])) {
        $paymentErr = "Mode of payment is required.";
    } else {
        $payment = test_input($_POST['payment']);
    }
    // Checks for credit card number
    if (empty($_POST['cardNum'])) {
        $cardNumErr = "Credit card number required.";
    } else {
        $cardNum = test_input($_POST['cardNum']);
    }
    // Checks for expiration date
    if (empty($_POST['expDate'])) {
        $expDateErr = "Card's expiration date required.";
    } else {
        $expDate = test_input($_POST['expDate']);
    }
    // Checks for password
    if (empty($_POST['pwd'])) {
        $pwdErr = "Password required.";
    } else {
        $pwd = test_input($_POST['pwd']);
    }
    // Asks to confirm password and if both match
    if (empty($_POST['pwd2'])) {
        $pwd2Err = "Confirm your email.";
    } else {
        $pwd2 = test_input($_POST['pwd2']);
        // Check if passwords match
        if ($pwd != $pwd2) {
            $pwd2Err = "Passwords don't match!";
        }
    }
}

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
} 

if(isset($_POST['submit'])){
    $myName = $_POST['myName'];
    $home1 = $_POST['home1'];
    $home2 = $_POST['home2'];
    $city = $_POST['city'];
    $ste = $_POST['ste'];
    $zip = $_POST['zip'];
    $email = $_POST['email'];
    $certification = $_POST['certification'];
    $experience = $_POST['experience'];
    $employer = $_POST['employer'];
    $marketing = $_POST['marketing'];
    $gender = $_POST['gender'];
    $dob = $_POST['dob'];
    $recert = $_POST['recert'];
    $full_name = $_POST['full_name'];
    $phone = $_POST['phone'];
    $bHome1 = $_POST['bHome1'];
    $bHome2 = $_POST['bHome2'];
    $bCity = $_POST['bCity'];
    $bState = $_POST['bState'];
    $bZip = $_POST['bZip'];
    $payment = $_POST['payment'];
    $cardNum = $_POST['cardNum'];
    $expDate = $_POST['expDate'];
    $pwd = $_POST['pwd'];

    // Adding multiple values to database table users
    $sql = "INSERT INTO TABLE users (myName, home1, home2) VALUES (?, ?, ?);";
    $sql .= "INSERT INTO TABLE users (city, ste, zip) VALUES (?, ?, ?);";
    $sql .= "INSERT INTO TABLE users (email, certification, experience) VALUES (?, ?, ?);";
    $sql .= "INSERT INTO TABLE users (employer, marketing, gender) VALUES (?, ?, ?);";
    $sql .= "INSERT INTO TABLE users (dob, recert, full_name) VALUES (?, ?, ?);";
    $sql .= "INSERT INTO TABLE users (phone, bHome1, bHome2) VALUES (?, ?, ?);";
    $sql .= "INSERT INTO TABLE users (bCity, bState, bZip) VALUES (?, ?, ?);";
    $sql .= "INSERT INTO TABLE users (payment, cardNum, expDate) VALUES (?, ?, ?);";
    $sql .= "INSERT INTO TABLE users (pwd) VALUES (?);";

    // Trying to save to the database
    if (mysqli_multi_query($con, $sql)) {
        echo "New records created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($con);
    }


    $hashPwd = password_hash($pwd, PASSWORD_DEFAULT);

    $stmt->bind_param("sssssssssssssssssssssssss", $myName, $home1, $home2, $city, $ste, $zip, 
        $email, $certification, $experience, $employer, $marketing, $gender, $dob, $recert, 
        $full_name, $phone, $bHome1, $bHome2, $bCity, $bState, $bZip, $payment, $cardNum,
        $expDate, $hashPwd); 
      
    mysqli_close($con);
}
4

3 回答 3

1

您的多重查询是完全错误的。它将创建九个新行,每行包含用户的一部分数据,而不是一个。你只有一组数据,所以你根本不需要 multi_query。

你需要

// Adding multiple values to database table users
    $sql = "INSERT INTO TABLE users (myName, home1, home2, city, ste, zip, email, employer, marketing, gender, certification, experience, dob, recert, full_name, phone, bHome1, bHome2, bCity, bState, bZip, payment, cardNum, expDate, pwd) VALUES (?, ?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";

    $stmt = $con->prepare($sql);

    $hashPwd = password_hash($pwd, PASSWORD_DEFAULT);

    $stmt->bind_param("sssssssssssssssssssssssss", $myName, $home1, $home2, $city, $ste, $zip, 
        $email, $certification, $experience, $employer, $marketing, $gender, $dob, $recert, 
        $full_name, $phone, $bHome1, $bHome2, $bCity, $bState, $bZip, $payment, $cardNum,
        $expDate, $hashPwd); 

   $result = $stmt->execute();
于 2021-02-08T23:05:41.383 回答
-1

Tangentially Perpendicular & Rager 为我指明了正确的方向,因为我的输入是错误的。使用多查询(mysqli_multi_query)是做我需要做的事情的错误方法,与将多个条目添加到表中无关。mysqli_multi_query 执行一个或多个由分号连接的查询(https://www.php.net/manual/en/mysqli.multi-query.php)。

是的,您可以根据需要为每条记录添加任意数量的条目(如果您想使生活复杂化),但简单更好。最后,我无法将数据放入表中的原因(除了使用多查询并且我的条目错误)是我的 MAMP 版本(在 Mac 中)运行的是 7.4 版,而不是我的计算机中的 PHP 8.0。一旦我检查了 MAMP 上标记的版本 8,我就可以在表中获取我的查询,而不会出现任何其他问题。

于 2021-02-11T02:23:58.810 回答
-3

你需要准备好你的sql,绑定参数然后执行。忘记 mysqli 函数。

 $sql = "INSERT INTO TABLE users (myName, home1, home2, city, ste, zip,   email, employer, marketing, gender, certification, experience, dob, recert, full_name, phone, bHome1, bHome2, bCity, bState, bZip, payment, cardNum, expDate, pwd) VALUES (?, ?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";

 $stmt = $con->prepare($sql);
    
 $hashPwd = password_hash($pwd, PASSWORD_DEFAULT);
    
 $stmt->bind_param("sssssssssssssssssssssssss", $myName, $home1, $home2, $city, $ste, $zip, 
            $email, $certification, $experience, $employer, $marketing, $gender, $dob, $recert, 
            $full_name, $phone, $bHome1, $bHome2, $bCity, $bState, $bZip, $payment, $cardNum,
            $expDate, $hashPwd); 

 $stmt->execute();
      
 mysqli_close($con);

你得到那个错误是因为 mysql 不知道什么?是。您几乎是在尝试执行INSERT INTO users (city, ste, zip) VALUES (?, ?, ?);无效的 sql。必须先转换变量。

此外,这对你来说可能有点高级,但你绝对可以从中重构出很多冗余代码......只要练习,你就会明白!

这是我正在谈论的内容的粗略

if ($_SERVER["REQUEST_METHOD"] != "POST") { 
    //Better to exit on smaller if then wrap everything in if statement.
    die();
}

$list = [
    'myName' => [ 'type' => 's', 'value' => '', 'err' => 'Name required.'],
    'home1' => [ 'type' => 's', 'value' => '', 'err' => 'Address required.'],
    'home2' => [ 'type' => 's', 'value' => '', 'err' => '']
    // Complete all your entries
];

$hasErr = false;
foreach($list as $key => &$item){
    if (empty($_POST[$key])) {
        $item['value'] = $item['err'];
    } else {
        $hasErr = true;
        $item['value'] = test_input($_POST[$key]);
        switch($key){
            case'myName':
                if (!preg_match("/^[a-zA-Z-' -.]*$/", $item['value'])) {
                    $item['value'] = "Only letters and white space allowed";
                }
                break;
            // Add more casses for more special proccessing.
        }
    }
}
unset($item); //Always unset pointers after loop.

if(!$hasErr){
    $sql = "INSERT INTO users(";
    $sqlCols = [];
    $sqlVals = [];

    foreach($list as $key => $item){
        $sqlCols[] = $key;
        $sqlVals[] = "?";
    }
    $sql .= implode(",", $sqlCols) . ") values ( " . implode(",", $sqlVals ). " )";
    $stmt->prepare($sql);
    foreach($list as $key => $item){
        // Actually not sure this is possible, worth a shot though.
        $stmt->pind_param($item['type'], $item['value']);
    }
    $stm->execute();
} else{
    //Handle error
}
于 2021-02-08T22:54:06.390 回答