Ini seharusnya baik-baik saja. Beri tahu saya jika ada masalah lain lebih lanjut.
<?php
try {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "2d_system";
$conn = new mysqli($servername, $username, $password, $dbname);
if($stmt = $conn->prepare($conn, "SELECT `Availability` FROM `number_availability` WHERE `Number`=? AND `GameCenter`=?")){
foreach($_POST['gamecenter'] as $key => $value){
$gamecenter = $_POST['gamecenter'][$key];
$number = $_POST['number'][$key];
$stmt->bind_param('ii', $number, $gamecenter); // if any of these values is a String, use 's' for that value instead (ii means integer-integer)
$stmt->execute();
if($conn->errno){
throw new Exception("Error: could not check for availability: " . $conn->error);
}
$result = $stmt->get_result();
$data = $result->fetch_array();
if($data['Availability'] <= 0){
unset($_POST['gamecenter'][$key]);
unset($_POST['number'][$key]);
unset($_POST['price'][$key]);
}
}
}
if($conn->errno){
throw new Exception("Error: could not check for availability: " . $conn->error);
}
if(count($_POST['gamecenter']) > 0){
if($conn->query("INSERT INTO `lottery_ticket` (`CreatedDateTime`) VALUES (now())")){
$lotteryTicketID = $conn->insert_id;
foreach($_POST['gamecenter'] as $key => $value){
$gamecenter = $_POST['gamecenter'][$key];
$number = $_POST['number'][$key];
$price = $_POST['price'][$key];
if($stmt = $conn->prepare("INSERT INTO `" . strtolower($gamecenter) . "_draw` (`LotteryId`, `" . $gamecenter . "_Number`, `Price`) VALUES (?, ?, ?)")){
$stmt->bind_param('idd', $lotteryTicketID, $number, $price);
$stmt->execute();
}
if($conn->errno){
throw new Exception("Error: could not execute query/queries: " . $conn->error);
}
}
}
if($conn->errno){
throw new Exception("Error: could not execute query/queries: " . $conn->error);
}
echo "Records added successfully.";
} else {
throw new Exception("Error: no available numbers.");
}
} catch(Exception $e){
echo $e->getMessage();
}
$conn->close();
?>
Omong-omong, sebelum Anda melanjutkan pengembangan, baca lebih lanjut tentang pernyataan berparameter. Juga, cobalah untuk memahami kode yang saya berikan kepada Anda dan baca komentarnya. Terakhir kali saya mengubah hampir semua hal dan saya dapat melihat dalam pertanyaan ini bahwa Anda mengabaikan semua itu. Selain itu, Anda tampaknya tidak memahami logika kode Anda, jadi pikirkanlah. Coba tuliskan setiap algoritme di kertas, lalu uji algoritme, lalu bangun aplikasi Anda berdasarkan algoritme itu.