Display visitor's number on your web page.
The "visitors" table has only one column (visitor_count) and only one row. The column's initial value is 0.
I know goto should not be used but then the code would be nested if conditions:
if (...) {
if (...) {
if (...) {
.
.
.
// display successful result
echo "You are visitor number: ";
printf("%10d", $row["visitor_count"]);
}
}
}
Is there any other solution other than goto and nested if conditions such that "Rest of HTML" always show up even if php script encounters an error (like, database connection failed, table visitors not found, etc.)?
Code is below. Please do the code review.
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Visitor Count</title>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "exp";
// create db connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// check db connection
if ($conn == false) {
echo("Connection failed: " . mysqli_connect_error());
goto END;
}
// execute query
$sql = "UPDATE visitors SET visitor_count = visitor_count + 1";
$result = mysqli_query($conn, $sql);
// check result
if ($result == false) {
echo("Query failed: " . $sql. "<br>". "Error: " . mysqli_error($conn));
goto DB_END;
}
// execute query
$sql = "SELECT visitor_count FROM visitors";
$result = mysqli_query($conn, $sql);
// check result
if ($result == false) {
echo("Query failed: " . $sql. "<br>". "Error: " . mysqli_error($conn));
goto DB_END;
}
// get number of rows
$num_rows_expected = 1;
$num_rows_got = mysqli_num_rows($result);
// verify number of rows got
if ($num_rows_got != $num_rows_expected) {
echo("Error: Mismatch: Number of rows expected = " . $num_rows_expected . ", Number of rows got = " . $num_rows_got);
goto RESULT_END;
}
// get a row
$row = mysqli_fetch_assoc($result);
// check if we got a row
if (($row == false) || ($row == null)) {
echo("Error: Got no row (data).");
goto RESULT_END;
}
// display successful result
echo "You are visitor number: ";
printf("%10d", $row["visitor_count"]);
RESULT_END:
// free the memory used by $result
mysqli_free_result($result);
DB_END:
// close db connection
mysqli_close($conn);
END:
?>
<!-- Rest of HTML should show up in all cases (successful cases as well as in error cases) -->
<br><br>Rest of HTML
</body>
</html>