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

Php 单击“提交”时,页面将变为白色空白,php,mysqli,Php,Mysqli,我是一名学生,有人给我一个任务,让我建立一个预订系统。我对php有点陌生,所以我仍然需要一些指导,我的问题是,当我尝试从表单中插入数据时,我的页面在单击submit按钮后变成白色空白 我试着在谷歌上搜索答案,有些答案是因为php编码中有额外的/缺少括号、额外的空格,还有一个技巧可以将这种编码放在php代码错误报告(-1)的开头查看错误是什么,但不幸的是,没有正确的解决方案 通过发布这篇文章,我希望你们中的一些人能帮助我,看看我的编码有什么问题 非常需要你的帮助。事先非常感谢你 Page2.php

我是一名学生,有人给我一个任务,让我建立一个预订系统。我对php有点陌生,所以我仍然需要一些指导,我的问题是,当我尝试从表单中插入数据时,我的页面在单击submit按钮后变成白色空白

我试着在谷歌上搜索答案,有些答案是因为php编码中有额外的/缺少括号、额外的空格,还有一个技巧可以将这种编码放在php代码
错误报告(-1)的开头
查看错误是什么,但不幸的是,没有正确的解决方案

通过发布这篇文章,我希望你们中的一些人能帮助我,看看我的编码有什么问题

非常需要你的帮助。事先非常感谢你

Page2.php:

<?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>";
}
?>
<form action="Page2.php" name="form" method="POST">
<input type="hidden" name="new" value="1" />        

<ul class="errorMessages"></ul>             

        <div class="form-group row text-left">
          <label for="example-date-input" class="col-2 col-form-label">Nama Peralatan: </label>
          <div class="col-10">

            <div class="form-group">
              <div class="form-row">
                <div class="col-md-3">
                        <div class="form-check text-left">
                            <label class="form-check-label">
                                <input class="form-check-input" name="item[]" type="checkbox" value="Microphones">
                                Microphones
                            </label>
                        </div>
                </div>
                <div class="">
                    <input class="form-control" type="number" name="microphones" value="0" id="example-number-input">   
                </div>
              </div>
            </div>

            <div class="form-group">
              <div class="form-row">
                <div class="col-md-3">
                        <div class="form-check text-left">
                            <label class="form-check-label">
                                <input class="form-check-input" name="item[]" type="checkbox" value="Amplifiers">
                                Amplifiers
                            </label>
                        </div>
                </div>
                <div class="">
                    <input class="form-control" type="number" name="amplifiers" value="0" id="example-number-input">    
                </div>
              </div>
            </div>      

            <div class="form-group">
              <div class="form-row">
                <div class="col-md-3">
                        <div class="form-check text-left">
                            <label class="form-check-label">
                                <input class="form-check-input" name="item[]" type="checkbox" value="Loudspeakers">
                                Loudspeakers
                            </label>
                        </div>
                </div>
                <div class="">
                    <input class="form-control" type="number" name="loudspeakers" value="0" id="example-number-input">  
                </div>
              </div>
            </div>

            <div class="form-group">
              <div class="form-row">
                <div class="col-md-3">
                        <div class="form-check text-left">
                            <label class="form-check-label">
                                <input class="form-check-input" name="item[]" type="checkbox" value="Mixers">
                                Mixers
                            </label>
                        </div>
                </div>
                <div class="">
                    <input class="form-control" type="number" name="mixers" value="0" id="example-number-input">    
                </div>
              </div>
            </div>                          

          </div>
        </div>          

        <div class="form-group row text-left">
        <label for="exampleTextarea" class="col-2 col-form-label">Catatan: </label>
            <div class="col-10">
            <textarea class="form-control" name="catatan" id="exampleTextarea" rows="3"></textarea>
            </div>
        </div>      

<p style="color:#FF0000;"><?php echo $status; ?></p>                        

    <center><button type="submit" name="submit" class="btn btn-info">Submit</button></center>

</form>

我不使用过程风格,所以我的代码可能有输入错误——我在发布之前没有测试。我写了内联注释来帮助解释我的代码片段。有效的
isset()
语法允许在其中包含多个变量。在
bind()
中,我假设您的列在数据库中是int类型的,所以我使用了
I
,而
submittedby
是varchar/string类型。这可能不能解决所有问题,但它应该让您自己调试它。编辑:我刚才看到你在评论中说,
amplifiers
应该是
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";
}
session_start();
require('db.php');
包括(“auth.php”);
如果(设置($会话[“用户名],$发布['new'],$发布['microphones'],$发布['ampliers'],$发布['loudspeakers'],$发布['mixers'],$发布['catatan']){//检查超球
//用于调试:var\u导出($\u会话);echo“

”var\u导出($\u POST); 如果(mysqli\u connect\u errno()){//检查连接是否有错误 echo“Connection Error:”,mysqli_connect_Error();//活动时不回显 }否则{ $stmt=mysqli\u stmt\u init($con); 如果(!mysqli_stmt_prepare($stmt,“插入pasystems(`trn_date`、`microsphones`、`ampliers`、`loudspeakers`、`mixers`、`catatan`、`submittedby`)值 (“.date”(“Y-m-d H:i:s”),,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,)”) echo“语句准备错误:”,mysqli_stmt_Error($stmt);//公开时不回显 }否则{ 如果(!mysqli_stmt_bind_param($stmt,“iiis”,$POST['microsphones'],$POST['ampliers'],$POST['loudspeakers'],$POST['mixers'],$POST['catatan'],$SESSION[“username”]){//绑定超全局值以查询并检查是否为false echo“语句绑定错误:”,mysqli_stmt_Error($stmt);//公开时不回显 }elseif(!mysqli_stmt_execute($stmt)){//运行并检查查询是否为false echo“语句绑定/执行错误:”,mysqli_stmt_Error($stmt);//公开时不回显 }否则{ echo“新记录创建成功”; //如果您有一个数据库生成的ID…echo“

”; } } mysqli_stmt_close($stmt); } }否则{ 回应“提交不足/无效”; }
这是一个使用面向对象样式的MySQLi和准备好的语句的解决方案。不过,我建议您转到PDO而不是MySQLi。它更干净更好

有一些很棒的PDO和MySQLi教程。而且,为了激活错误报告,这里有一个很好的资源可以查看:

  • 原则上,所有数据访问操作都在页面的上部php中实现。获取的数据保存在数组中(如
    $n\u anjuranItems
    )。在html代码部分,您只需循环遍历这个数组。执行此操作时,您不会将数据访问代码与html代码混合使用
  • 此外,您不应该使用php编写html代码
  • 代码中有一个“@todo”。请搜索一下
  • 如前所述,我重新添加了组合框“n_anjuran”。必须完成/选择输入
    catatan
    n_anjuran
    。但请尝试使用空/未选择的值,以便查看错误消息的显示方式。如果愿意,可以在html中为输入提供
    required
    属性
  • 您应该在PHP(服务器端)中清理和过滤发布的值。您还应该在客户端验证输入值
  • 在html中,最后一个插入id被附加到“查看记录”锚点
  • 我从db表中删除了复选框和“item”字段
  • 根据我的喜好,我用Bootstrap3.3.7重新设计了html,并写了一些评论,希望你们能理解
  • 通常,如果不涉及输入参数,可以使用
    mysqli::query
    而不是
    mysqli\u stmt::prepare
    +
    mysqli\u stmt::execute
    。就个人而言,我倾向于准备sql语句,即使我不需要
祝你好运

Page 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');
<?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');