Im encountering an issue in my PHP code. When I enter an email into my form, and the POST request is sent to MYSQL server, it’s giving me a 200 response even if I enter a duplicate email. In my network I am getting an error that looks like this:
Received POST data:Array
(
[csrfToken] => <?php echo generateCSRFToken(); ?>
[first-name] => Moses
[last-name] => Avigdor
[email] => [email protected]
[password] => gfdjgdfj
)
Sorry, there was an error uploading your file.<br />
<b>Fatal error</b>: Uncaught mysqli_sql_exception: Duplicate entry '[email protected]' for key 'profile.email' in /opt/homebrew/var/www/ipn.php:60
Stack trace:
#0 /opt/homebrew/var/www/ipn.php(60): mysqli_stmt->execute()
#1 {main}
thrown in <b>/opt/homebrew/var/www/ipn.php</b> on line <b>60</b><br />
Inside my console log I’m getting an affirmative response status: 200.
What I’m trying to do is have a 400 error when a duplicate email is entered and a 200 response when there is no duplicate.
This is my PHP code.
<?php
error_reporting(E_ALL);
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Access- Control-Allow-Headers, Authorization, X-Requested-With");
header('Content-Type: application/json');
session_start();
$servername = "localhost";
$username = "root";
$password = "Proverbs31!";
$database = "IPN";
// Assign values from the form data to variables
$first_name = $_POST['first-name'];
$last_name = $_POST['last-name'];
$email = $_POST['email'];
$user_password = $_POST['password'];
// Check if email already exists
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Check if email already exists
$sql = "SELECT COUNT(*) AS count FROM profile WHERE email = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$count = (int) $row['count'];
if ($count > 0) {
// Email address already exists, send a client error response
http_response_code(409); // Conflict
echo json_encode(array("error" => "Email address already exists"));
exit(); // Stop further execution
}
// If email doesn't exist, proceed with insertion
// Handle profile picture upload
$profile_picture = null;
if(isset($_FILES['profile-picture'])) {
$file_name = $_FILES['profile-picture']['name'];
$file_tmp = $_FILES['profile-picture']['tmp_name'];
$file_size = $_FILES['profile-picture']['size'];
$file_type = $_FILES['profile-picture']['type'];
$target_dir = "uploads/";
$target_file = $target_dir . basename($file_name);
// Move uploaded file to target directory
if (move_uploaded_file($file_tmp, $target_file)) {
$profile_picture = $target_file;
} else {
// Handle file upload error
http_response_code(500); // Internal Server Error
echo json_encode(array("success" => false, "message" => "Error uploading profile picture"));
exit();
}
}
// Proceed with insertion
$sql = "INSERT INTO profile (first_name, last_name, email, password, profile_picture) VALUES (?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssss", $first_name, $last_name, $email, $user_password, $profile_picture);
try {
// Attempt to execute the prepared statement
if ($stmt->execute()) {
http_response_code(200); // OK
echo json_encode(array("success" => true, "message" => "Signup successful"));
} else {
http_response_code(500);
echo json_encode(array("error" => "An unexpected error occurred"));
}
} catch (mysqli_sql_exception $e) {
error_log("MySQLi SQL Exception: " . $e->getMessage());
if ($e->getCode() == 1062) {
http_response_code(409);
echo json_encode(array("error" => "Email address already exists"));
} else {
http_response_code(500);
echo json_encode(array("error" => "An unexpected error occurred"));
}
} catch (Exception $e) {
error_log("Exception: " . $e->getMessage());
http_response_code(500);
echo json_encode(array("error" => "An unexpected error occurred"));
} finally {
$stmt->close();
$conn->close();
}
And here is my JavaScript
// Define the handleSubmit function
function handleSubmit(event) {
event.preventDefault(); // Prevent default form submission
const form = event.target;
const formData = new FormData(form);
// Fetch API to send POST request to ipn.php with form data
fetch('http://127.0.0.1:8080/ipn.php', {
method: 'POST',
body: formData,
})
.then((response) => {
console.log('Response status:', response.status);
if (response.status === 200) {
form.reset();
// window.location.href = 'login.html';
} else if (response.status === 409) {
// Check if response is JSON
return response
.json()
.then((data) => {
console.log('Response:', data);
// Display error message if email already exists
const errorMessage = document.getElementById('error-message');
errorMessage.textContent = data.message; // Set the error message content
errorMessage.style.display = 'block'; // Show the error message
console.log('Parsed JSON data:', data);
})
.catch((error) => {
console.error('Error parsing JSON:', error);
const errorMessage = document.getElementById('error-message');
errorMessage.textContent =
'An error occurred. Please try again later.';
errorMessage.style.display = 'block';
});
}
})
.catch((error) => {
console.error('Fetch error:', error);
});
}
document.getElementById('signup-form').addEventListener('submit', handleSubmit);
In MySQL I have a table with a column designated email and it is unique.
I tried to move the try statement around, specifically where the 200 code is tripped. This was primarily because the 200 code is being recieved before the MySQL workbench gives its 1062 code. I’ve tried to specify the error codes like this:
try {
// Attempt to insert data into the database
$sql = "INSERT INTO profile (first_name, last_name, email, password) VALUES (?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssss", $first_name, $last_name, $email, $password);
$stmt->execute();
// If insertion was successful, send a success response
http_response_code(200); // OK
echo json_encode(array("success" => true, "message" => "Signup successful"));
} catch (mysqli_sql_exception $e) {
// Handle duplicate entry error
if ($e->getCode() == 1062) { // MySQL error code for duplicate entry
// Send an error response indicating duplicate entry
http_response_code(409);
echo json_encode(array("error" => "Email address already exists"));
} else {
// Handle other MySQLi SQL exceptions
http_response_code(500); // Internal Server Error
echo json_encode(array("error" => "An unexpected error occurred"));
}
}
This resulted in a json parsing error. I also tried to change up my JavaScript to handle the errors first then move on to a 200 code
if (response.status !== 200) {
// Handle non-successful HTTP status codes (e.g., 409 for duplicate entry)
return response.json()
.then((data) => {
const errorMessage = document.getElementById('error-message');
errorMessage.textContent = data.error;
errorMessage.style.display = 'block';
})
.catch((error) => {
console.error('Error parsing JSON:', error);
const errorMessage = document.getElementById('error-message');
errorMessage.textContent = 'An error occurred. Please try again later.';
errorMessage.style.display = 'block';
});
}
This had no affect on the outcome that I can tell. Needless to say I need help.