简体   繁体   English

PHP if / else语句插入MYSQL表不起作用

[英]PHP if/else statement inserting into MYSQL table not working

I can't get this if/else statement to work when verifying form data before inserting into database. 在插入数据库之前验证表单数据时,我无法使用此if / else语句。 The If section works with no problems when I have tested it by removing the rest 如果我通过除去其余部分进行测试,则If部分可以正常工作

My code; 我的代码;

if (array_key_exists("submit", $_POST)){
    if(!$_POST['tiptitle']) {
        $error .= "An Title is required<br>";
    }
    if(!$_POST['tiptext']) {
        $error .= "Text is required<br>";
    } 
    if('!$error') {
        $dangererror = "<div class='alert alert-danger'>";
        $dangererror .= $error;
        $dangererror .= "</div>";
    } else {
        /*
        Attempt MySQL server connection. Assuming you are running MySQL
        server with default setting (user 'root' with no password) 
        */
        $mysqli = new mysqli("localhost", "paul", "pass", "yourcomp");
        // Check connection
        if($mysqli === false){
            die("ERROR: Could not connect. " . $mysqli->connect_error);
        }
        // Prepare an insert statement
        ............
        // Close statement
        $stmt->close();
        // Close connection
        $mysqli->close();
    }
} 

Form Submit 表格提交

<form action="addtip.php" method="post" id="AddTipForm">

Form Button 表单按钮

<input type="submit" name="submit" class="btn btn-primary btn-block mb-4" value="Add Tip!">
// you can use the isset() function to see if post values are set 
if (isset($_POST['submit'])){

    // empty() functions checks if the value is set or not null
    if(empty($_POST['tiptitle'])) {
        $error .= "An Title is required<br>";
    } else{
        // etra validation.... mysql espaces...etc
    }

    // empty() functions checks if the value is set or not null
    if(empty($_POST['tiptext'])) {
        $error .= "Text is required<br>";
    } else{ 
        // etra validation.... mysql espaces...etc
    }

    // ****  an empty string, "", is considered false in PHP
    // you had it in a 'string' format, which is always true.

    if($error) {
        $dangererror = "<div class='alert alert-danger'>";
        $dangererror .= $error;
        $dangererror .= "</div>";
    } else {

        /* Attempt MySQL server connection. Assuming you are running MySQL
        server with default setting (user 'root' with no password) */
        $mysqli = new mysqli("localhost", "paul", "pass", "yourcomp");

        // Check connection
        if($mysqli === false){
            die("ERROR: Could not connect. " . $mysqli->connect_error);
        }

        // Prepare an insert statement

        ............

        // Close statement
        $stmt->close();

        // Close connection
        $mysqli->close();
    }
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM