is it possible to catch error in a php file, lets say in the connection section, and return it to the HTML file as json for printing.
This is my try:
<?php
$srevernme = "localhost";
$username = "root";
$password = "";
$dbname = "db";
//create connection
$conn = new mysqli($srevernme,$username,$password,$dbname);
$errors = array(); // array to hold connection errors
//check connection //<-----POSSIBLE ERROR
if ($conn->connect_error) {
$data['success'] = false;
$errors['error_info'] = "connection failed:" . $conn->connect_error ."Please try later.";
$data['errors'] = $errors;
echo json_encode($data);
//die("connection failed:" . $conn->connect_error);
}
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (isset($_POST["fnameInput"]) && isset($_POST["lnameInput"]) && isset($_POST["addressInput"]) && isset($_POST["cityInput"]) && isset($_POST["zipcodeInput"]))
{
// prepare and bind
$stmt = $conn->prepare("INSERT INTO users (first_name, last_name) VALUES (?, ?)");
if ($stmt == FALSE) { //<-----POSSIBLE ERROR
$data['success'] = false;
$errors['error_info'] = "Connection failed: Cannot create connection to sql DB. Please try later.";
$data['errors'] = $errors;
echo json_encode($data);
//die("Connection failed: Cannot create connection to sql DB. Please try later.");
}
if (empty($errors))
{
//mark as success
$data = array(); //array for saving the data
$data['success'] = true;
//get wanted data....
$data['wanted_data'] = json_encode($some_data);
echo json_encode($data);
$stmt->close();
}
}
$conn->close();
The relevant sections are marked with //<-----POSSIBLE ERROR
.
To be clear- data
represents the data I want to echo
to the html file and it had a key named success
that his values are true
if everything is ok or false
if there is an error.
EDIT: In the current state the php file send request in this format when I shot down MySQL server (from chrome inspector):
<br />
<b>Warning</b>: mysqli::mysqli(): in <b>C:\xampp\htdocs\projectegister.php</b> on line <b>7</b><br />
<br />
<b>Warning</b>: mysqli::prepare(): Couldn't fetch mysqli in <b>C:\xampp\htdocs\ex3egister.php</b> on line <b>26</b><br />
{"success":false,"error_info":"Connection failed: Cannot create connection to sql DB. Please try later."}<br />
<b>Fatal error</b>: Call to a member function bind_param() on null in <b>C:\xampp\htdocs\ex3egister.php</b> on line <b>39</b><br />
Thanks!