This should do just fine. Let me know if there's any other issue further on.
<?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();
?>
By the way, before you continue developing, read more about parameterized statements. Also, try to understand the code I'm giving you and read the comments. Last time I changed pretty much everything and I can see in this question that you ignored all that. Furthermore, you don't seem to understand the logic of your code, so give it some thought. Try writing every algorithm down in paper, then test the algorithm, and then build your applications based on that algorithm.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…