this is my first time asking a question since I cant find any better solutions for my problem. I got a task to make a form by website that uses file_put_contents() for book data library. My code contains:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$file = "dataBuku.txt";
if (file_exists($file) && filesize($file) > 0) {
$getContent = file_get_contents($file);
if (preg_match_all('/Kode Buku: (\d+)/', $getContent, $matches)) {
$kode = $matches[1];
$kodeAkhir = max($kode);
$kodeBuku = $kodeAkhir + 1;
}
} else {
$kodeBuku = 1;
}
$judul = $_POST['judul'];
$pengarang = $_POST['pengarang'];
$tahunTerbit = $_POST['tahunTerbit'];
$halaman = $_POST['halaman'];
$penerbit = $_POST['penerbit'];
$kategori = $_POST['kategori'];
$dataBuku = "Kode Buku: $kodeBuku" . PHP_EOL;
$dataBuku .= "Judul Buku: $judul" . PHP_EOL;
$dataBuku .= "Pengarang Buku: $pengarang" . PHP_EOL;
$dataBuku .= "Tahun Terbit Buku: $tahunTerbit" . PHP_EOL;
$dataBuku .= "Halaman Buku: $halaman" . PHP_EOL;
$dataBuku .= "Penerbit Buku: $penerbit" . PHP_EOL;
$dataBuku .= "Kategori Buku: $kategori" . PHP_EOL;
if ($_FILES['cover']['error'] === UPLOAD_ERR_OK) {
$ekstensiFile = strtolower(pathinfo($_FILES['cover']['name'], PATHINFO_EXTENSION));
$namaFile = $kodeBuku . "_" . $pengarang . "_" . $judul . "." . $ekstensiFile;
$namaSementara = $_FILES['cover']['tmp_name'];
$lokasiFile = 'cover/' . $namaFile;
move_uploaded_file($namaSementara, $lokasiFile);
}
$dataBuku .= "Cover Buku: $lokasiFile" . PHP_EOL . PHP_EOL;
if (file_put_contents($file, $dataBuku, FILE_APPEND) > 0){
echo "<p> Data Written successfully </p>";
}else{
echo "<p> Data Written failed </p>";
}
$fileIndiv = "$kodeBuku - $judul - $pengarang.txt";
if (file_put_contents($fileIndiv, $dataBuku) > 0){
echo "<p> $fileIndiv Written successfully </p>";
}else{
echo "<p> Data Written failed </p>";
}
}
echo "<br> <a href='tes.php'><button>Back</button></a>";
echo "<br> <a href='cek.php'><button>Cek Data</button></a>"
?>
With the expected output:
Kode Buku: 1 (auto_increment)
Judul Buku: Harga Sebuah Percaya
Pengarang Buku: Tere Liye
Tahun Terbit Buku: 2017
Halaman Buku: 302
Penerbit Buku: Mahaka Publishing
Kategori Buku: Novel
Cover Buku: cover/1_Tere Liye_Harga Sebuah Percaya.jpg
Sorry, it's all in Indonesian, but Im sure you'll get the point, tho. I wanted to make the most effective that can auto_increment the 'kodeBuku' without that long code block, reply below if you have any thoughts, will be appreciated, Thanks.
kodeBuku become auto_increment that not counting for lines but the last kodeBuku + 1