-1

I'm a student and I was given a task to make a reservation system. I'm a bit new to php so I still need some guidance, my problem here is, when I try to insert data from a form, my page turns white blank just after I clicked the submit button.

I've tried googled for answers and some answers are because there are extra/lack of brackets, extra spaces in php coding and there are also a tip to put this coding in the beginning of php code error_reporting(-1); to see what is the error but unfortunately, there are no right solutions.

By posting this I hope some of you can help me and see what's wrong with my coding.

Your help is much needed. Thank you so much in advance.

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>";
}
?>

html:

<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>

I have edited my coding but it seems to still have a problem

user8674032
  • 51
  • 3
  • 9
  • Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackoverflow.com/rooms/157477/discussion-on-question-by-cuntspire-when-click-submit-the-page-turns-white-blan). – Andy Oct 25 '17 at 13:00

2 Answers2

2

Here is a solution using object oriented-styled MySQLi with prepared statements. Though, I recommend you to move to PDO instead of MySQLi. It's cleaner and better.

Here are some great tutorials for PDO and MySQLi. And, in order to activate error reporting, here is a good resource to look into: Error reporting basics.

  • In principle, all data access operation are implemented in the upper - php - part of the page. Fetched data is saved in arrays (like $n_anjuranItems). In the html code part you just loop through this arrays. Doing this you don't mix data access codes with html codes.
  • Also you should not write html codes using php.
  • There is a "@todo" in the code. Search for it please.
  • As said, I re-added the combobox "n_anjuran". The inputs catatan and n_anjuranmust be completed/selected. But try with empty/unselected values, so that you see how the error messages are displayed. You can give the inputs the required attribute in html if you wish.
  • You should sanitize and filter the posted values in PHP (server side). You should also validate the input values on the client side.
  • In html, the last insert id is appended to "View record" anchor.
  • I removed the checkboxes and "item" field from db table.
  • I redesigned html with Bootstrap 3.3.7 by my taste and wrote some comments which I hope you understand.
  • Normally, if no input parameters are involved, you could use mysqli::query instead of mysqli_stmt::prepare + mysqli_stmt::execute. Personally I tend to prepare the sql statements, even if I don't need to.

Good luck.

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

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>

Used tables

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;

Used table values

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

I don't use procedural style, so my code may have a typo in it -- I didn't test before posting. I wrote inline comments to help explain my snippet. Valid isset() syntax permits multiple variables in it. In bind() I am assuming your columns are int-type in your database so I used i, and submittedby is a varchar/string-type. This may not fix everything, but it should put you on the right path to debugging it yourself. EDIT: I just saw that you said in your comments that amplifers should be amplifiers so I've adjusted my answer.

Untested Procedural-style Code:

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";
}
mickmackusa
  • 43,625
  • 12
  • 83
  • 136