PHP MySQL - 无法删除脚本的某些部分

时间:2017-12-02 15:16:50

标签: php mysql

我有一个奇怪的问题。

基本上我有一个用户可以注册的页面。信息将发送到MySQL数据库,并存储在该数据库中。在页面上完成任何工作之前,如果表已经存在,我想要一个简短的脚本来更改。如果它不存在,它将被创建,如果它确实存在继续下一个任务。

但出于某种原因,如果我删除“报告结果”部分,我会收到错误(请参阅下面的脚本)。我想删除它的原因基本上是因为用户不需要知道刚刚创建了一个表。

为什么我不能在没有收到错误的情况下删除此部分?

<?php

$table       =     "database";

$servername      =  "xxx";
$username    =  "xxx";
$password    =  "xxx";
$dbname              =  "xxx";

// Connect to database
$conn = new mysqli($xxx, $xxx, $xxx, $xxx);

// Create table if it does not exist
$sql = "CREATE TABLE IF NOT EXISTS $table (
        id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        example-1VARCHAR(30) NOT NULL,
        example-2 VARCHAR(30) NOT NULL,
        example-3 VARCHAR(50),
        example-4 VARCHAR(50),
        example-5 VARCHAR(50),
        reg_date TIMESTAMP
        )";

// Report result <---------------------- PROBLEM HERE
if ($conn->query($sql) === TRUE) {
    echo "Table created successfully";
    } else {
    echo "Error creating table: " . $conn->error;
}

// Insert data into table
if (isset($_POST["submit"])) {

    $example-1      =   $_POST['example-1'];
    $example-2      =   $_POST['example-2'];
    $example-3      =   $_POST['example-3'];
    $example-4      =   $_POST['example-4'];
    $example-5      =   $_POST['example-5'];

    // Check if already exist in table
    $query = "SELECT * from $table where email ='$example-3'";

    if ($result=mysqli_query($conn,$query))

        {
            if(mysqli_num_rows($result) > 0) {

            // If already exist in table
            echo "Already exists";

        } else

            // If doesn't exist, add to table
            $sql = "INSERT INTO $table (example-1, example-2, example-3, example-4, example-5)
            VALUES ('".$example-1."', '".$example-2."', '".$example-3."', '".$example-4."', '".$example-5."')";

            if ($conn->query($sql) === TRUE) {
                echo "New record created successfully";
            }

        } else

        // If everything fails for technical reason 
        echo "Query Failed.";

}

$conn->close();

?>

1 个答案:

答案 0 :(得分:2)

删除“报告结果”块时,您必须至少保留此部分:$conn->query($sql);。否则,表根本就不会创建..

根据@ chris85评论,变量名称不得包含减去-,请参阅 PHP Manual Language Reference Variables Basics

语句$example-2$example minus two执行数学运算,因此如果$example = 5则结果为3。这是你不想要的。

更好的变量名称为$example_2$example2