failed connection proceed to logout - php

I am trying to redirect to the logout page when the database connection fails. How do I do it? It always shows the error message but not the one I specify. Help appreciated, thanks in advance.
Richard
code:
function ms_connect() {
// Create connection
// Microsoft Access
$db_source = DB_SERVER;
$db_system = DB_SYSTEM_SEC;
$odbc_driver = "driver={microsoft access driver (*.mdb)};dbq=" . $db_source . ";systemdb=" . $db_system;
$conn = odbc_connect($odbc_driver, DB_SERVER_USERNAME,DB_SERVER_PASSWORD); // Error returned here!
if ($conn) {
return $conn;
} else{
exit("Connection could not be established.");
header ("Location: /logout.php");
}
}
it does not show "Connection could..."
error shown
PHP Warning: odbc_connect(): SQL error: [Microsoft][ODBC Microsoft Access Driver] Not a valid account name or password., SQL state 08004 in SQLConnect in C:\inetpub\wwwroot\functions\functions.php on line 11

You are doing an exit, which will terminate the script before the redirect.
You can pass your error message as a get param and show it on your page if you need.
Your code should look like this :
if ($conn) {
return $conn;
} else{
header ("Location: /logout.php?error=Connection+could+not+be+established.");
}
Also if you want to hide the warning just add:
error_reporting(0);
ini_set('display_errors', 'Off');

The warning you see is triggered by the odbc_connect function, while it is strange that the exit string is not printed, it is not strange that your redirect does not work since the exit prevents it from being executed.
Try:
if ($conn !== false) {
return $conn;
} else{
header ("Location: /logout.php");
exit();//just in case
}
You can ignore the warning (and you should) by the connection using the '#' sign in front of the connect function. (which is more elegant than to ignore all errors).
$conn = #odbc_connect($odbc_driver, DB_SERVER_USERNAME,DB_SERVER_PASSWORD); // Error returned here!
edit:
A nice way to do it and still show a message to the user plus redirect is using html meta redirects:
if ($conn !== false) {
return $conn;
} else{
echo '<html><head><meta http-equiv="refresh" content="5;url=/logout.php" /></head><body>Could not create a connection, redirecting in 5 seconds.</body></html>';
exit();
}

Related

How to display error and load the rest of the page if database-related content is optional?

My .php includes quote.php followed with the rest of the page.
When the connection fails, I see "Fatal error: Uncaught mysqli_sql_exception: ----- include_once('C:\xampp\htdocs...') ----
and the remainder of the page does not load.
What must I do to display an error message, THEN the rest of my page?
Your situation is a rare case when using a try catch is justified.
All you need to do it wrap the include in a try-catch:
try {
require 'quote.php';
} catch(\Throwable $e) {
error_log($e); // for the future inspection
echo "Problem loading this part of page";
}
That's all. The error message will be shown and the rest of the page will be loaded.
But of course this approach should only be used when the content from quote.php is optional. In the every other case there must be no local try-catch but a site-wide error handler.
php / msqli is throwing exceptions. You need to write exception handler code (try { } catch (mysqli_sql_exception $e) { } code in your program to handle errors.
As a quick and sleazy workaroud for the current state of your code you can put this line of code at the top of your page. give this line of code
mysqli_report(MYSQLI_REPORT_OFF):;
This will suppress php exceptions and warnings, and let you rely completely on mysqli_connect_errno() to catch your errors.
Using #O. Jones idea and some nasty GoTO's, this does the job. The warnings and error are still displayed. The rest of the page is able to load now.
<?php
mysqli_report(MYSQLI_REPORT_OFF);
$dbServer = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "project_01";
$conn = mysqli_connect($dbServer, $dbUsername, $dbPassword, $dbName);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to the MySQL Database: ";
goto end;
}
$sql = "SELECT * FROM tbl_quotes";
if ($result=mysqli_query($conn,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
$rand = random_int(1,$rowcount);
} else {
echo "No records were found";
goto end;
}
$sql = "SELECT quote, credit FROM tbl_quotes where ID = $rand";
if ($result = mysqli_query($conn, $sql)) {
// Fetch one and one row
while ($row = mysqli_fetch_row($result)) {
printf ("%s" . " - " . "(%s)\n", $row[0], $row[1]);
}
// Free result set
mysqli_free_result($result);
}
end:
?>
Thanks to all who looked.

catch error in php and return it as json to html

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\project\register.php</b> on line <b>7</b><br />
<br />
<b>Warning</b>: mysqli::prepare(): Couldn't fetch mysqli in <b>C:\xampp\htdocs\ex3\register.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\ex3\register.php</b> on line <b>39</b><br />
Thanks!
Ohh, is that what you mean?
It seems the JSON arrives just fine. What you mean is to disable php errors? In this case, you can turn off php's standard error reporting, so it only shows your custom errors. (Note that this means you will not get an error that you aren't manually taking care of)
see http://php.net/manual/en/function.error-reporting.php for more information.
// Turn off all error reporting
error_reporting(0);
This will prevent php from echo-ing its own errors, thus only returning your (valid) json_encoded errors.
edit:
You'll want to return json_encode($errors) instead of json_encode($data) in case of an error.
edit#2:
I would really advise you to not return anything until you've reached the end of your script, so it's less confusing. Simply put an if statement at the end.
if(!empty($errors)){
echo json_encode($errors);
return false; //don't go on
}
else{
echo json_encode($data);
return false; //don't go on
}
In case of an error, simply add to the $errors array, as it seems to me that's what you're wanting to do in the first place.

Trouble using a reusable database connector

I'm new to php. I've been having trouble connecting to and using a data with PHP. I don't really have much information on the issue, maybe I'm using some out of date method, or I did something wrong. I've double checked and looked on this website for information, but I didn't find much. Here's the code below.
The error reads :
Fatal error: Call to a member function query() on boolean in C:\xampp\htdocs\website\Practice\mysqli\pdo.php on line 6
That would mean that there is a problem located near the
$result = $conn->query($sql)or die(mysqli_error());
I entered my username and password correctly. I even created a new username and password just to make sure. I have no other ideas why $conn isn't working, and I would love any thoughts or ideas on the issue!
connection.ini.php
function dbConnect($usertype, $connectiontype = 'pdo') {
$host = 'localhost';
$db = 'student';
if ($usertype == 'read') {
$user = 'user';
$pwd = 'pass';
}
elseif ($usertype == 'write') {
$user = 'root';
$pwd = 'password';
}
else {
exit('Unrecognized connection type');
}
//Connection Code
if ($connectionType ='mysqli') {
return new mysqli($host, $user, $pwd, $db) or die ('Cannot open database');
}
else {
try {
return new PDO('mysql:host=$host;dbname=$db, $user, $pwd');
}
catch(PDOExecption $e) {
echo 'Cannot connect to database';
exit;
}
}
}
?>
mysqli.php
?php
require_once('connection.inc.php');
$conn = dbConnect('read', 'pdo');
$sql = 'SELECT * FROM guestbook';
$result = $conn->query($sql)or die(mysqli_error());
$numRows = $result->num_rows;
?>
<!DOCTYPE html>
<html>
<p> A total of <?php
echo $numRows;
?>
records were found.</p>
</html>
Any time you get the...
"Fatal error: Call to a member function bind_param() on boolean"
...it is likely because there is an issue with your query. The prepare() might return FALSE (a Boolean), but this generic failure message doesn't leave you much in the way of clues. How do you find out what is wrong with your query? You ask!
First of all, make sure error reporting is turned on and visible: add these two lines to the top of your file(s) right after your opening <?php tag:
error_reporting(E_ALL);
ini_set('display_errors', 1);
If your error reporting has been set in the php.ini you won't have to worry about this. Just make sure you handle errors gracefully and never reveal the true cause of any issues to your users. Revealing the true cause to the public can be a gold engraved invitation for those wanting to harm your sites and servers. If you do not want to send errors to the browser you can always monitor your web server error logs. Log locations will vary from server to server e.g., on Ubuntu the error log is typically located at /var/log/apache2/error.log. If you're examining error logs in a Linux environment you can use tail -f /path/to/log in a console window to see errors as they occur in real-time....or as you make them.
Once you're squared away on standard error reporting adding error checking on your database connection and queries will give you much more detail about the problems going on. Have a look at this example where the column name is incorrect. First, the code which returns the generic fatal error message:
$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
$query = $mysqli->prepare($sql)); // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();
The error is generic and not very helpful to you in solving what is going on.
With a couple of more lines of code you can get very detailed information which you can use to solve the issue immediately. Check the prepare() statement for truthiness and if it is good you can proceed on to binding and executing.
$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
if($query = $mysqli->prepare($sql)) { // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();
// any additional code you need would go here.
} else {
$error = $mysqli->errno . ' ' . $mysqli->error;
echo $error; // 1054 Unknown column 'foo' in 'field list'
}
If something is wrong you can spit out an error message which takes you directly to the issue. In this case there is no foo column in the table, solving the problem is trivial.
If you choose, you can include this checking in a function or class and extend it by handling the errors gracefully as mentioned previously.

mysqli_connect Fatal Error: require()

Developing a very simple UPDATE query page for users to change their account password, but have run into a bit of a brick wall with establishing the MySQLi connection (or so it would seem). I'm new to this line of programming and this is my first attempt to perform a dynamic query, so hopefully it's something that one of you can spot easily enough and you'd so kind as to offer some much-needed sage advice.
Here's the page in question: http://www.parochialathleticleague.org/accounts.html
Upon executing the form's PHP script, I was at first receiving nothing but a blank white screen. I scoured through my code and did everything I could think of to diagnose the problem. After eventually adding an "OR die" function to the require command, I am now greeted with this message:
Warning: require(1) [function.require]: failed to open stream: No such file or directory > in /home/pal/public_html/accounts.php on line 10
Fatal error: require() [function.require]: Failed opening required '1'
(include_path='.:/usr/local/php52/pear') in
/home/pal/public_html/accounts.php on line 10
I'm pretty stumped. Here's the script code:
<?php
// Show errors:
ini_set('display_errors', 1);
// Adjust error reporting:
error_reporting(E_ALL);
// Connect to the database:
require ('../mysqli_connect.php') OR die('Error : ' . mysql_error());
// Validate the school:
if (empty($_POST['school'])) {
echo "You forgot to enter your school.<br>";
$validate = 'false';
} else {
$school = mysqli_real_escape_string($db, trim($_POST['school']));
$validate = 'true';
}
// Validate the existing password:
if (empty($_POST['pass'])) {
echo "You forgot to enter your existing password.<br>";
$validate = 'false';
} else {
$pass = mysqli_real_escape_string($db, trim($_POST['pass']));
$validate = 'true';
}
// Validate the new password:
if (empty($_POST['new_pass'])) {
echo "You forgot to enter your new password.<br>";
$validate = 'false';
} elseif (empty($_POST['confirm_pass'])) {
echo "You forgot to confirm your new password.<br>";
$validate = 'false';
} elseif ($_POST['new_pass'] != $_POST['confirm_pass']) {
echo "Sorry, your new password was typed incorrectly.<br>";
$validate = 'false';
} else {
$new_pass = mysqli_real_escape_string($db, trim($_POST['new_pass']));
$validate = 'true';
}
// If all conditions are met, process the form:
if ($validate != 'false') {
// Validate the school/password combination from the database:
$q = "SELECT school_id FROM user_schools WHERE (school_name='$school' AND pass=SHA1('$pass') )";
$r = #mysqli_query($db, $q);
$num = #mysqli_num_rows($r);
if ($num == 1) {
// Get the school_id:
$row = mysqli_fetch_array($r, MYSQLI_NUM);
// Perform an UPDATE query to modify the password:
$q = "UPDATE user_schools SET pass=SHA1('$new_pass') WHERE school_id=$row[0]";
$r = #mysqli_query($db, $q);
if (mysqli_affected_rows($db) == 1) {
header("Location: confirm_accounts.html");
} else {
echo "Your password could not be changed due to a system error. Apologies for the inconvenience. If this problem continues, please contact us directly.";
}
}
}
mysqli_close($db);
exit();
?>
Lastly, here's the code from the connection script that it's requiring (with omitted account values, of course):
<?php
// Set the database access information as constants:
DEFINE ('DB_USER', '***');
DEFINE ('DB_PASSWORD', '***');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', '***');
// Make the connection:
$db = #mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' .mysqli_connect_error() );
// Set the encoding:
mysqli_set_charset($db, 'utf8');
I've been trying for the last couple of hours to troubleshoot this problem on my own. Google couldn't solve it. Looking through archives here couldn't solve it.
Here's what I do know for sure:
The script that it's requiring, mysqli_connect.php, does work on its own. I've tested it extensively to make sure that all of the log-in info is correct.
The script is also definitely in the parent directory that I've requested it from. I've tried moving it to the public directory and calling it from there. Same error message. Tried typing the entire file path. Same message.
Also, most of the script works fine on its own. When I omitted all of the MySQL lines and just left the basic validation code, it ran without a problem and sent me to the confirmation page as requested. It definitely seems to be a problem with making the connection.
Not sure where to go from here. Any assistance would be GREATLY appreciated! Many thanks in advance.
EDIT: #YourCommonSense - Here's the modified script, as per your suggestions. Still getting the blank screen. Am I following your advice incorrectly?
<?php
// Show errors:
ini_set('display_errors', 1);
// Adjust error reporting:
error_reporting(E_ALL);
// Connect to the database:
require ('../mysqli_connect.php');
// Validate the school:
if (empty($_POST['school'])) {
echo "You forgot to enter your school.<br>";
$validate = 'false';
} else {
$school = mysqli_real_escape_string($db, trim($_POST['school']));
$validate = 'true';
}
// Validate the existing password:
if (empty($_POST['pass'])) {
echo "You forgot to enter your existing password.<br>";
$validate = 'false';
} else {
$pass = mysqli_real_escape_string($db, trim($_POST['pass']));
$validate = 'true';
}
// Validate the new password:
if (empty($_POST['new_pass'])) {
echo "You forgot to enter your new password.<br>";
$validate = 'false';
} elseif (empty($_POST['confirm_pass'])) {
echo "You forgot to confirm your new password.<br>";
$validate = 'false';
} elseif ($_POST['new_pass'] != $_POST['confirm_pass']) {
echo "Sorry, your new password was typed incorrectly.<br>";
$validate = 'false';
} else {
$new_pass = mysqli_real_escape_string($db, trim($_POST['new_pass']));
$validate = 'true';
}
// If all conditions are met, process the form:
if ($validate != 'false') {
// Validate the school/password combination from the database:
$q = "SELECT school_id FROM user_schools WHERE (school_name='$school' AND pass=SHA1('$pass') )";
$r = mysqli_query($db, $q);
if (!$r) {
throw new Exception($mysqli->error." [$query]");
}
$num = mysqli_num_rows($r);
if ($num == 1) {
// Get the school_id:
$row = mysqli_fetch_array($r, MYSQLI_NUM);
// Perform an UPDATE query to modify the password:
$q = "UPDATE user_schools SET pass=SHA1('$new_pass') WHERE school_id=$row[0]";
$r = mysqli_query($db, $q);
if (!$r) {
throw new Exception($mysqli->error." [$query]");
}
if (mysqli_affected_rows($db) == 1) {
header("Location: confirm_accounts.html");
} else {
echo "Your password could not be changed due to a system error. Apologies for the inconvenience. If this problem continues, please contact us directly.";
}
}
}
mysqli_close($db);
exit();
?>
Two BIGGEST problems with your code and your "solution":
You have # operator all over the place. For which you have -1 vote to your question. # operator is the evil itself. IT is responsible for the blank page you see.
However, the remedy you choose made the things worse. This "OR die" thing is not a magic chant to solve any error reporting problem. And used improperly will cause errors like one you have. For which you have 1 in the error message.
First of all, your include is all right, so, leave it alone.
While to get an error from mysqli, follow these instructions:
Instead of adding "or die" randomly, you need more robust and helpful error reporting solution.
If you are using mysqli_query() all over the application code without encapsulating it into some helper class, trigger_error() is a good way to raise a PHP error, as it will tell you also the file and the line number where error occurred
$res = mysqli_query($mysqli,$query) or trigger_error(mysqli_error($mysqli)."[$query]");
in all your scripts
and since then you will be notified of the reason, why the object weren't created.
(If you're curious of this or syntax, I've explained it here - it also explains why you have (1) in the error message)
However, if you're encapsulating your query into some class, file and line from trigger error will be quite useless as they will point to the call itself, not the application code that caused certain problem. So, when running mysqli commands encapsulated, another way have to be used:
$result = $mysqli->query($sql);
if (!$result) {
throw new Exception($mysqli->error." [$query]");
}
as Exception will provide you with a stack trace, which will lead you the the place from which an erroneous query were called.
Note that you have to be able to see PHP errors in general. On a live site you have to peek into error logs, so, settings have to be
error_reporting(E_ALL);
ini_set('display_errors',0);
ini_set('log_errors',1);
while on a local development server it's all right to make errors on screen:
error_reporting(E_ALL);
ini_set('display_errors',1);
and of course you should never ever use error suppression operator (#) in front of your statements.

PDO Exceptions in PHP

Okay I have a bit of a question dealing with $_POST. I'm attempting to send a few values from an Android App (Using HTTPclient) I'm developing but the PHP sends the message from the exception back. I'm trying to figure out why is that happening and how to fix it:
login
<?php
//load and connect to MySQL database stuff
require("configmob.php");
if (!empty($_POST)) {
//gets user's info based off of a username.
$query = "
SELECT
myusername,
mypassword
FROM Customer
WHERE
myusername = :myusername
mypassword = :mypassword";
$query_params = array(
':myusername' => $_POST['username'],
':mypassword' => $_POST['password']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
//This will be the variable to determine whether or not the user's information is correct.
//we initialize it as false.
$validated_info = false;
//fetching all the rows from the query
$row = $stmt->fetch();
if ($row) {
//if we encrypted the password, we would unencrypt it here, but in our case we just
//compare the two passwords
if ($_POST['password'] === $row['password']) {
$login_ok = true;
}
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if ($login_ok) {
$response["success"] = 1;
$response["message"] = "Login successful!";
die(json_encode($response));
} else {
$response["success"] = 0;
$response["message"] = "Invalid Credentials!";
die(json_encode($response));
}
}
?>
config
<?php
// These variables define the connection information for your MySQL database
$host = "mysql17.000webhost.com";
$dbname = "a4335408_data1";
$username = "******";
$password = "******";
// UTF-8 is a character encoding scheme that allows you to conveniently store
// a wide varienty of special characters, like ¢ or €, in your database.
// By passing the following $options array to the database connection code we
// are telling the MySQL server that we want to communicate with it using UTF-8
// See Wikipedia for more information on UTF-8:
// http://en.wikipedia.org/wiki/UTF-8
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
// A try/catch statement is a common method of error handling in object oriented code.
// First, PHP executes the code within the try block. If at any time it encounters an
// error while executing that code, it stops immediately and jumps down to the
// catch block. For more detailed information on exceptions and try/catch blocks:
// http://us2.php.net/manual/en/language.exceptions.php
try
{
// This statement opens a connection to your database using the PDO library
// PDO is designed to provide a flexible interface between PHP and many
// different types of database servers. For more information on PDO:
// http://us2.php.net/manual/en/class.pdo.php
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
// If an error occurs while opening a connection to your database, it will
// be trapped here. The script will output an error and stop executing.
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code
// (like your database username and password).
die("Failed to connect to the database: " . $ex->getMessage());
}
// This statement configures PDO to throw an exception when it encounters
// an error. This allows us to use try/catch blocks to trap database errors.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// This statement configures PDO to return database rows from your database using an
associative
// array. This means the array will have string indexes, where the string value
// represents the name of the column in your database.
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// This block of code is used to undo magic quotes. Magic quotes are a terrible
// feature that was removed from PHP as of PHP 5.4. However, older installations
// of PHP may still have magic quotes enabled and this code is necessary to
// prevent them from causing problems. For more information on magic quotes:
// http://php.net/manual/en/security.magicquotes.php
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
// This tells the web browser that your content is encoded using UTF-8
// and that it should submit content back to you using UTF-8
header('Content-Type: text/html; charset=utf-8');
// This initializes a session. Sessions are used to store information about
// a visitor from one web page visit to the next. Unlike a cookie, the information is
// stored on the server-side and cannot be modified by the visitor. However,
// note that in most cases sessions do still use cookies and require the visitor
// to have cookies enabled. For more information about sessions:
// http://us.php.net/manual/en/book.session.php
session_start();
// Note that it is a good practice to NOT end your PHP files with a closing PHP tag.
// This prevents trailing newlines on the file from being included in your output,
// which can cause problems with redirecting users.
?>
Thank you and I hope this question isn't too difficult or anyhting.
Try replacing the static error message with the exception message to see what's going wrong
Change:
$response["message"] = "Database Error1. Please Try Again!";
to:
$response["message"] = $ex->getMessage();
Conditions in a WHERE statement must be separated with AND keyword

Categories