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.