-1

Update Oct 11 2020

I tried this code:

<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$connect = mysqli_connect("localhost", "root", "", "sip-krl");
 
// Check connection
if($connect === false){
    die("ERROR: Koneksi gagal " . mysqli_connect_error());
}

$id_jenisPembayaran = $_POST['id_jenisPembayaran'];
$nama_jenisPembayaran = $_POST['nama_jenisPembayaran'];
 
// Attempt insert query execution
$sql = "INSERT INTO jenispembayaran (id_jenisPembayaran, nama_jenisPembayaran) VALUES ('$id_jenisPembayaran', '$nama_jenisPembayaran')";
if(mysqli_query($connect, $sql)){
    echo "Data berhasil dimasukkan";
} else{
    echo "ERROR: Data gagal masuk ke basis data $sql. " . mysqli_connect_error();
}
 
// Close connection
$connect->close();

header("location:/skripsi-manual/data-jenisPembayaran.php");
?>

It works perfectly. However, this also makes my program vulnerable to SQL Injection.

I'm stumped as why this (the code above) works but the code below gets me nowhere?

Could anyone show me the why? Thanks in advance.


I'm making a form to input type of payment data to my database. The codes are following:

.php file = input-jenisPembayaran.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "sip-krl";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";

$id_jenisPembayaran = mysqli_escape_string ($conn, $_POST['id_jenisPembayaran']);
$nama_jenisPembayaran = mysqli_escape_string($conn, $_POST['nama_jenisPembayaran']);

$sql = "INSERT INTO jenispembayaran (id_jenisPembayaran, nama_jenisPembayaran);
VALUES (?,?)";

$stmt = mysqli_stmt_init($conn);

if(!mysqli_stmt_prepare($stmt, $sql)){
    echo "Error.";
} else{
    mysqli_stmt_bind_param($stmt, "is", $id_jenisPembayaran, $nama_jenisPembayaran);
    mysqli_stmt_execute($stmt);
}

header("location:/skripsi-manual/jenispembayaran.php?tambah-data=success");

$conn->close();
$stmt->close();
?> 

Form: jenispembayaran.php

<div class="content">
        <form action="./assets/php/input-jenisPembayaran.php" method="POST">
           <article class="card">
                <h4> Masukkan Jenis Pembayaran </h4>
                <br>
                <br>
                <label for="id_jenisPembayaran">Kode Jenis Pembayaran:</label>
                <input type="text" name="id_jenisPembayaran" id="id_jenisPembayaran">
                <br>
                <br>
                <label for="nama_jenisPembayaran">Nama Jenis Pembayaran:</label>
                <input type="text" name="nama_jenisPembayaran" id="nama_jenisPembayaran">
                <br>
                <br>
                <button input type="submit" value="submit">Masukkan</button>
            </article>
        </form>
    </div>

Database structure:

dbName: sip-krl => table: jenispembayaran => tableRows: id_jenisPembayaran(int), nama_jenisPembayaran(varchar)

"input-jenisPembayaran.php" manages to connect my form to the database. But it fails to insert the data I typed in.

Could anyone show me where my code went wrong and show me how to solve this?

Thank you in advance.

jovitaAS
  • 29
  • 6
  • Do not use `mysqli_escape_string()` – Dharman Oct 06 '20 at 20:57
  • You cannot use headers after you've echoed something. I think you need to do some debugging first. [Switch on error reporting](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display) and check for MySQL errors. – KIKO Software Oct 06 '20 at 21:00
  • @Dharman, Okay. I'll scrap that line. – jovitaAS Oct 06 '20 at 21:25
  • @Dharman: I already deleted the line (and saved the file and reloaded it). Still, it didn't save any data. – jovitaAS Oct 06 '20 at 21:37
  • @KIKOSoftware: I've tried it. But it didn't display any error. It was as if I didn't put the syntax at all. (Every time. Except for that time I tried putting it on top of my form.php file (above the ), it printed the syntax on the top left of my page.) – jovitaAS Oct 06 '20 at 21:37
  • ` – Funk Forty Niner Oct 06 '20 at 21:39
  • *"it printed the syntax on the top left of my page"* - What do you mean by that, that it prints code? – Funk Forty Niner Oct 06 '20 at 21:42
  • @FunkFortyNiner: I mean, the code is written on the top left of my page. Literally, with the semicolon. I've deleted the 'input' and still, nothing changed. – jovitaAS Oct 06 '20 at 21:46
  • Seems to me that you're not running this off a web server or you're using `file:///` instead of using an HTTP prototocol, am I correct on this? – Funk Forty Niner Oct 06 '20 at 22:13
  • Are you able to detect whether the `INSERT` query did execute or not? I have this habit of checking by deliberately using a non-existent table in my query to see if it return any error or not. I mean, try changing the table name in your insert query to something like `INSERT INTO jenispembayaranxxxx .... ` and see if it return table not exists error. – FanoFN Oct 07 '20 at 01:33
  • @FunkFortyNiner: I'm running this with xampp (localhost/....) – jovitaAS Oct 07 '20 at 02:35
  • @tcadidot0: I tried changing the table name and the variables. It didn't return error. It ran as if I did no changes at all. – jovitaAS Oct 07 '20 at 03:02
  • @tcadidot0: after I changed the table name and variable name, the program only redirected me back to "jenispembayaran.php". – jovitaAS Oct 07 '20 at 08:06
  • You mean after you changed them to some non-existent table name etc.? If that's the case, it should return error but instead what happen is seems like the program doesn't even get to the `INSERT ` statement at all. did you write this code from scratch or you copy paste them and edit few lines? – FanoFN Oct 08 '20 at 01:03
  • @tcadidot0: yep. I changed the table and the variables to non-existent names. I copy-pasted and edited several lines (from many tutorials in the internet) – jovitaAS Oct 08 '20 at 02:42

1 Answers1

0

I've tried with your code and with my limited PHP knowledge, I couldn't make it work. Also I did find a tutorial similar to your codes but I also couldn't make it work. However, I found another tutorial that works and try to emulate what you're doing with this tutorial instead and I've managed to perform the process that you desire with this code below:

<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'mydatabase');
 
/* Attempt to connect to MySQL database */
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
 
// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

/* You can set a separate connection file and instead of writing the database connection credentials, 
   just call it using  require_once "config\database.php"; */

// Define variables and initialize with empty values
$id_jenisPembayaran = $nama_jenisPembayaran = "";

// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){

    // Assigning variables with data from input fields
        $id_jenisPembayaran = trim($_POST["id_jenisPembayaran"]);
        $nama_jenisPembayaran = trim($_POST["nama_jenisPembayaran"]);

         // Prepare an insert statement
        $sql = "INSERT INTO jenispembayaran (id_jenisPembayaran, nama_jenisPembayaran) VALUES (?,?)";
         
        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "ss", $param_id_jenisPembayaran, $param_nama_jenisPembayaran);
            
            // Set parameters
            $param_id_jenisPembayaran = $id_jenisPembayaran;
            $param_nama_jenisPembayaran = $nama_jenisPembayaran;

            
            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                // Records created successfully. Redirect to landing page
                header("location: testing2.php");
                exit();
            } else{
                echo "Something went wrong. Please try again later.";
            }
         
        // Close statement
        mysqli_stmt_close($stmt);
}
    // Close connection
    mysqli_close($link);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Create Record</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
    <style type="text/css">
        .wrapper{
            width: 500px;
            margin: 0 auto;
        }
    </style>
</head>
<body>
<div class="content">
    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
        <article class="card">
            <br>
            <br>
            <label for="id_jenisPembayaran">Kode Jenis Pembayaran:</label>
            <input type="text" name="id_jenisPembayaran" value="<?php echo $id_jenisPembayaran; ?>">
            <br>
            <br>
            <label for="nama_jenisPembayaran">Nama Jenis Pembayaran:</label>
            <input type="text" name="nama_jenisPembayaran" value="<?php echo $nama_jenisPembayaran; ?>">
            <br>
            <br>
            <input type="submit" value="submit">
        </article>
    </form>
</div>
</body>

As you can see, the PHP and HTML code are in one single file and honestly I attempted many times just to understand how the flow went because I've manage to post this code but with empty and NULL values. Even though I got this initial code from a tutorial, I had to trim and re-code them to make it work.

This is the source of the tutorial : https://www.tutorialrepublic.com/php-tutorial/php-mysql-crud-application.php and I was particularly re-create your codes according to the create.php section. Also, please look at the database config section and how every PHP page is calling it to create a connection.

FanoFN
  • 6,815
  • 2
  • 13
  • 33
  • thank you for your efforts! I tried this and it works. Although, while it manages to post data to my database and redirects back to the form, it also echoes "Something went wrong. Please try again later." at the top left of my form page. Do you know how could I pull this off by separating the php code in a separate file? I tried putting it in **_input-datajenispembayaran.php_** but I got "undefined variable" in both ``. I type the action as: `
    `.
    – jovitaAS Oct 18 '20 at 01:36
  • Honestly, I just learn this PHP because of your question :) . I can try with separating the code into php file but it might take me a while to figure it out. If you're looking for a quick solution, you might want to post a new question with this requirement. – FanoFN Oct 19 '20 at 00:41
  • 1
    oh... I see. Again, thank you for your efforts. That means a lot for me. Do you get the error message too? Even though your code manages to post data in your database? – jovitaAS Oct 19 '20 at 01:48
  • You mean this message "Something went wrong. Please try again later."? No. On my testing it just redirect back to the page. I've tested on Edge Version 86, Chrome Version 86, Firefox Version 81 and Internet Explorer Version 11, all behave the same. – FanoFN Oct 19 '20 at 01:59
  • Yep. I modified `mysqli_stmt_bind_param($stmt, "ss", $param_id_jenisPembayaran, $param_nama_jenisPembayaran);` into `mysqli_stmt_bind_param($stmt, "is", $param_id_jenisPembayaran, $param_nama_jenisPembayaran);` since "id_jenisPembayaran" is an int. That couldn't be the issue, could it? – jovitaAS Oct 21 '20 at 00:42
  • I've tried that and didn't receive the error message. Would you mind to post a new question and copy the code that you're working with? Once you've post it, just leave a comment here and I'll be able to find the question. Thanks ;) – FanoFN Oct 21 '20 at 01:14
  • Sure! Thanks a bunch, bro. I'll comment you once I've posted it. – jovitaAS Oct 21 '20 at 02:57
  • 1
    done: https://stackoverflow.com/questions/64493170/html-form-succeeds-to-do-its-job-but-theres-an-error-message-saying-that-somet?noredirect=1#comment114039363_64493170 – jovitaAS Oct 23 '20 at 10:29
  • I see the question is already being marked as duplicate. Does the [linked duplicate question](https://stackoverflow.com/questions/22662488/mysqli-fetch-assoc-expects-parameter-call-to-a-member-function-bind-param) resolve your issue? – FanoFN Oct 24 '20 at 00:38
  • I've tried them, but to no avail. Now I got **Object not found** too. – jovitaAS Oct 26 '20 at 15:21
  • I've added the **object not found** issue in the question. – jovitaAS Oct 26 '20 at 16:20