单击“提交”时,页面将变为空白

时间:2017-10-23 02:20:36

标签: php mysqli

我是一名学生,我被赋予了预约系统的任务。我对php有点新意,所以我仍需要一些指导,我的问题是,当我尝试从表单中插入数据时,我的页面在我单击提交按钮后变为空白。

我已经尝试用Google搜索答案,而且一些答案是因为在PHP编码中有额外/缺少括号,额外空格,还有一个提示将此编码放在php代码的开头{{1}看看错误是什么,但不幸的是,没有正确的解决方案。

通过发布这个,我希望你们中的一些人可以帮助我,看看我的编码有什么问题。

非常需要你的帮助。非常感谢你提前。

Page2.php:

error_reporting(-1);

html:

<?php
session_start();
require('db.php');
include("auth.php");
$status = "";
if(isset($_POST['new']) && $_POST['new']==1){
    $trn_date = date("Y-m-d H:i:s");
    $checkBox = implode(',', $_POST['item']);
    $microphones = $_REQUEST['microphones'];
    $amplifers =$_REQUEST['amplifers'];
    $loudspeakers = $_REQUEST['loudspeakers'];
    $mixers =$_REQUEST['mixers'];
    $catatan = $_REQUEST['catatan'];
    $submittedby = $_SESSION["username"];   
    $ins_query="insert into pasystems
    (`trn_date`,`item`,`microphones`,`amplifers`,`loudspeakers`,`mixers`,`catatan`,`submittedby`)values
    ('$trn_date','". $checkBox ."','$microphones','$amplifers','$loudspeakers','$mixers','$catatan','$submittedby')";   
    mysqli_query($con,$ins_query)
    or die(mysql_error());
    $status = "New Record Inserted Successfully.
    </br></br><a href='view.php'>View Inserted Record</a>";
}
?>

我编辑了我的编码,但似乎仍有问题

2 个答案:

答案 0 :(得分:2)

这是一个使用面向对象风格的MySQLi和预编译语句的解决方案。虽然,我建议你转移到PDO而不是MySQLi。它更干净,更好。

Here是PDO和MySQLi的一些很棒的教程。并且,为了激活错误报告,这是一个很好的资源:Error reporting basics

  • 原则上,所有数据访问操作都在页面的上层 - php - 部分实现。提取的数据保存在数组中(如$n_anjuranItems)。在html代码部分中,您只需遍历此数组。这样做,您就不会将数据访问代码与HTML代码混合在一起。
  • 此外,您不应该使用php编写HTML代码。
  • 有一个&#34; @ todo&#34;在代码中。请搜索它。
  • 如上所述,我重新添加了组合框&#34; n_anjuran&#34;。必须完成/选择输入catatann_anjuran。但请尝试使用空/未选择的值,以便查看错误消息的显示方式。如果您愿意,可以在html中为输入提供required属性。
  • 您应该在PHP(服务器端)中清理并过滤发布的值。您还应验证客户端的输入值。
  • 在html中,最后一个插入ID附加到&#34;查看记录&#34;锚
  • 我删除了复选框和&#34; item&#34; db表中的字段。
  • 我根据自己的喜好用Bootstrap 3.3.7重新设计了html,写了一些评论,希望你能理解。
  • 通常,如果不涉及输入参数,您可以使用mysqli::query代替mysqli_stmt::prepare + mysqli_stmt::execute。我个人倾向于准备sql语句,即使我不需要。
祝你好运。

页面db.php

<?php

/*
 * Enable internal report functions. This enables the exception handling, 
 * e.g. mysqli will not throw PHP warnings anymore, but mysqli exceptions
 * (mysqli_sql_exception).
 * 
 * MYSQLI_REPORT_ERROR: Report errors from mysqli function calls.
 * MYSQLI_REPORT_STRICT: Throw a mysqli_sql_exception for errors instead of warnings. 
 * 
 * See:
 *      http://php.net/manual/en/class.mysqli-driver.php
 *      http://php.net/manual/en/mysqli-driver.report-mode.php
 *      http://php.net/manual/en/mysqli.constants.php
 */
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Create the db connection.
$connection = new mysqli('host', 'user', 'pass', 'db');

Page page2.php

<?php
session_start();

require_once 'db.php';
require_once 'auth.php';

// @todo Delete. Just for testing.
$_SESSION['username'] = 'Tarzan';

// Flag to signalize if record saved.
$recordSaved = FALSE;

/*
 * ================================
 * Operations upon form submission.
 * ================================
 */
if (isset($_POST['submitButton'])) {
    /*
     * ==========================
     * Validate the input values.
     * ==========================
     */
    if (!isset($_POST['microphones'])) {
        $errors[] = 'Please provide the microphones number.';
    }
    if (!isset($_POST['amplifiers'])) {
        $errors[] = 'Please provide the amplifiers number.';
    }
    if (!isset($_POST['loudspeakers'])) {
        $errors[] = 'Please provide the loudspeakers number.';
    }
    if (!isset($_POST['mixers'])) {
        $errors[] = 'Please provide the mixers number.';
    }
    if (!isset($_POST['catatan']) || empty($_POST['catatan'])) {
        $errors[] = 'Please provide the catatan.';
    }
    if (!isset($_POST['n_anjuran']) || empty($_POST['n_anjuran'])) {
        $errors[] = 'Please select a n_anjuran.';
    }

    /*
     * ======================
     * Read the input values.
     * ======================
     */
    $trnDate = date('Y-m-d H:i:s');
    $microphones = $_POST['microphones'];
    $amplifiers = $_POST['amplifiers'];
    $loudspeakers = $_POST['loudspeakers'];
    $mixers = $_POST['mixers'];
    $catatan = $_POST['catatan'];
    $n_anjuran = $_POST['n_anjuran'];
    $submittedBy = $_SESSION['username'];

    /*
     * ========================================
     * Save the new record if no errors raised.
     * ========================================
     */
    if (!isset($errors)) {
        $sql = 'INSERT INTO pasystems (
                        `trn_date`,
                        `microphones`,
                        `amplifiers`,
                        `loudspeakers`,
                        `mixers`,
                        `catatan`,
                        `n_anjuran`,
                        `submittedby`
                    ) VALUES (
                        ?, ?, ?, ?, ?, ?, ?, ?
                    )';

        // Prepare the SQL statement for execution.
        $statement = $connection->prepare($sql);

        /*
         * Bind the variables for the parameter markers (?). The first 
         * argument of mysqli_stmt::bind_param is a string that contains one 
         * or more characters which specify the types for the corresponding bind variables.
         */
        $bound = $statement->bind_param(
                'siiiisis' // Bind variable types.
                , $trnDate
                , $microphones
                , $amplifiers
                , $loudspeakers
                , $mixers
                , $catatan
                , $n_anjuran
                , $submittedBy
        );

        // Execute the prepared statement.
        $executed = $statement->execute();

        // Close the prepared statement and deallocate the statement handle.
        $statement->close();

        // Get the last insert id.
        $lastInsertId = $connection->insert_id;

        // Update record saved flag.
        $recordSaved = TRUE;
    }
}

/*
 * ==========================
 * Fetch the n_anjuran items.
 * ==========================
 */

$sql = 'SELECT kd_dept, desc_dept FROM koddept';

// Prepare the SQL statement for execution.
$statement = $connection->prepare($sql);

/*
 * Execute the prepared statement. When executed, any parameter markers 
 * which exist will automatically be replaced with the appropriate data.
 */
$executed = $statement->execute();

// Get the result set from the prepared statement.
$result = $statement->get_result();

// Fetch data.
$n_anjuranItems = array();
if ($result->num_rows > 0) {
    $n_anjuranItems = $result->fetch_all(MYSQLI_ASSOC);
}

/*
 * Free the memory associated with the result. You should 
 * always free your result when it is not needed anymore.
 */
$result->close();

/*
 * Close the prepared statement. It also deallocates the statement handle.
 * If the statement has pending or unread results, it cancels them 
 * so that the next query can be executed.
 */
$statement->close();

// Close the database connection.
$connection->close();
?>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title>Demo</title>

        <!-- ======================================= -->
        <!-- CSS resources -->
        <!-- ======================================= -->

        <!-- Font-Awesome -->
        <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css" rel="stylesheet" />

        <!-- Bootstrap -->
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" rel="stylesheet" />

        <!-- ======================================= -->
        <!-- JS resources -->
        <!-- ======================================= -->

        <!-- jQuery -->
        <script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>

        <!-- Bootstrap -->
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" type="text/javascript"></script>
    </head>
    <body>

        <div class="container">
            <div class="row page-header">
                <div class="col-xs-12">
                    <h1>
                        Demo
                    </h1>
                </div>
            </div>
            <div class="row">
                <div class="col-xs-12 col-md-6 col-md-offset-3">
                    <form name="form" action="Page2.php" method="post">
                        <?php
                        if (isset($errors)) {
                            foreach ($errors as $error) {
                                ?>
                                <div class="alert alert-danger alert-dismissible" role="alert">
                                    <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                                    <i class="fa fa-exclamation-circle"></i> <?php echo $error; ?>
                                </div>
                                <?php
                            }
                        } elseif (isset($recordSaved) && $recordSaved) {
                            ?>
                            <div class="alert alert-success alert-dismissible" role="alert">
                                <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                                <i class="fa fa-check-circle"></i> New record successfully saved. <a href='view.php?id=<?php echo $lastInsertId; ?>'>View record</a>.
                            </div>
                            <?php
                        }
                        ?>

                        <div class="form-group">
                            <label for="microphones">Microphones</label>
                            <input type="number" name="microphones" value="<?php echo !$recordSaved && isset($microphones) ? $microphones : 0; ?>" class="form-control">   
                        </div>
                        <div class="form-group">
                            <label for="amplifiers">Amplifiers</label>
                            <input type="number" name="amplifiers" value="<?php echo !$recordSaved && isset($amplifiers) ? $amplifiers : 0; ?>" class="form-control">   
                        </div>
                        <div class="form-group">
                            <label for="loudspeakers">Loudspeakers</label>
                            <input type="number" name="loudspeakers" value="<?php echo !$recordSaved && isset($loudspeakers) ? $loudspeakers : 0; ?>" class="form-control">   
                        </div>
                        <div class="form-group">
                            <label for="mixers">Mixers</label>
                            <input type="number" name="mixers" value="<?php echo !$recordSaved && isset($mixers) ? $mixers : 0; ?>" class="form-control">   
                        </div>
                        <div class="form-group">
                            <label for="catatan">Catatan *</label>
                            <textarea name="catatan" placeholder="Complete catatan..." rows="3" class="form-control"><?php echo !$recordSaved && isset($catatan) ? $catatan : ''; ?></textarea>
                        </div>
                        <div class="form-group">
                            <label for="n_anjuran">Dept/Kelab/Anjuran *</label>
                            <select name="n_anjuran" class="form-control">
                                <option value="">- SILA PILIH -</option>
                                <?php
                                if ($n_anjuranItems) {
                                    foreach ($n_anjuranItems as $n_anjuranItem) {
                                        $selected = (!$recordSaved && isset($n_anjuran) && $n_anjuran == $n_anjuranItem['kd_dept']) ? 'selected' : '';
                                        ?>
                                        <option value="<?php echo $n_anjuranItem['kd_dept']; ?>" <?php echo $selected; ?>>
                                            <?php echo $n_anjuranItem['desc_dept']; ?>
                                        </option>
                                        <?php
                                    }
                                }
                                ?>
                            </select>
                        </div>
                        <div class="form-group text-center">
                            <button type="submit" id="submitButton" name="submitButton" class="btn btn-success" aria-label="Submit" title="Submit">
                                <i class="fa fa-check" aria-hidden="true"></i> Submit
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

    </body>
</html>

使用过的表

CREATE TABLE `pasystems` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `trn_date` varchar(100) DEFAULT NULL,
  `microphones` int(11) DEFAULT NULL,
  `amplifiers` int(11) DEFAULT NULL,
  `loudspeakers` int(11) DEFAULT NULL,
  `mixers` int(11) DEFAULT NULL,
  `catatan` varchar(100) DEFAULT NULL,
  `n_anjuran` int(11) DEFAULT NULL,
  `submittedby` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `koddept` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `kd_dept` int(11) DEFAULT NULL,
  `desc_dept` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

使用的表值

INSERT INTO `koddept` (`id`, `kd_dept`, `desc_dept`)
VALUES
    (1,1,'my dept 1'),
    (2,2,'my dept 2');

答案 1 :(得分:1)

我不使用程序样式,所以我的代码可能有拼写错误 - 我没有在发布之前测试。我写了内联注释来帮助解释我的代码片段。有效的isset()语法允许其中包含多个变量。在bind()我假设您的列在数据库中是int类型,因此我使用i,而submittedby是varchar / string类型。这可能无法解决所有问题,但它应该让您自己正确地调试它。编辑:我刚看到你在评论中说amplifers应该是amplifiers所以我已经调整了我的答案。

未经测试的程序式代码:

session_start();
require('db.php');
include("auth.php");
if(isset($_SESSION["username"],$_POST['new'],$_POST['microphones'],$_POST['amplifiers'],$_POST['loudspeakers'],$_POST['mixers'],$_POST['catatan'])){  // check superglobals
    // for debugging: var_export($_SESSION); echo "<br><br>"; var_export($_POST);
    if(mysqli_connect_errno()){  // check connection for an error
        echo "Connection Error: ",mysqli_connect_error();  // do not echo when live
    }else{
        $stmt=mysqli_stmt_init($con);
        if(!mysqli_stmt_prepare($stmt,"INSERT INTO pasystems (`trn_date`,`microphones`,`amplifiers`,`loudspeakers`,`mixers`,`catatan`,`submittedby`) VALUES
    (".date("Y-m-d H:i:s").",?,?,?,?,?,?)")){  // use prepared statement with placeholders for security/reliability and check for false
            echo "Statement Preparation Error: ",mysqli_stmt_error($stmt);  // do not echo when public
        }else{
            if(!mysqli_stmt_bind_param($stmt,"iiiiis",$_POST['microphones'],$_POST['amplifiers'],$_POST['loudspeakers'],$_POST['mixers'],$_POST['catatan'],$_SESSION["username"])){ // bind superglobal values to query and check for false
                echo "Statement Bind Error: ",mysqli_stmt_error($stmt);  // do not echo when public
            }elseif(!mysqli_stmt_execute($stmt)){ // run and check query for false
                echo "Statement Bind/Execution Error: ",mysqli_stmt_error($stmt);  // do not echo when public
            }else{
                echo "New record created successfully";
                // if you have a database-generated ID... echo "<br><br><a href='view.php?ID=",mysqli_stmt_insert_id($stmt),"'>View Inserted Record</a>";
            }
        }
        mysqli_stmt_close($stmt);
    }
}else{
    echo "Insufficient/Invalid Submission";
}