HTTP error when trying to access mysql database - php

Hey guys I'm still learning PHP and need help. I have 3 files that require a database.php file to connect to MySQL. when I execute the files only two of them work. For the last file, I get an HTTP error 500.
<?php
require( 'database.php');
// inserting information from the form into the database
$sql = ("INSERT INTO guestlist (firstName, lastName, phoneNumber,guests,event)
VALUES (?,?,?,?,?)");
// values are prepared to bind
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt,"sssss",$_POST['first_name'],$_POST['last_name'], $_POST['phonenumber'], $_POST['guest'], $_POST['event']);
$stmt->execute();
if (!$stmt)// Was not updated
{
// shows error
echo("There was an error with your RSVP. Please try again.");
mysqli_stmt_close($stmt);
}
else //Was updated
{
echo("Your RSVP has been completed.");
}
//End database connection
mysqli_close($con);
?>
this is my database file that was provided by my professor
<?php
$myHost = "localhost"; // localhost, do not change this string
$myUserName = "cmorales"; // CHANGE TO YOUR USERNAME
$myPassword = ""; // CHANGE TO YOUR PASSWORD
$myDataBaseName = "cmorales_project"; // CHANGE USERNAME
username_project
$con = mysqli_connect( "$myHost", "$myUserName", "$myPassword",
"$myDataBaseName" );
if( !$con ) // == null if creation of connection object failed
{
// report the error to the user, then exit program
die("connection object not created: ".mysqli_error($con));
}
if( mysqli_connect_errno() ) // returns false if no error occurred
{
// report the error to the user, then exit program
die("Connect failed: ".mysqli_connect_errno()." : ".
mysqli_connect_error());
}
?>

Because there is a syntax error in your database.php
Cause :
No semicolon end of username_project 7th line.
Solution:
remove undefined constant username_project on the 7th line.
as #Antonio Teh Sumtin mentioned in the comments, Always check the error log or enable the display error during development.

Related

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.

When creating a database in MySQL with PHP using the following code where does we make the connection and where does we make the database?

I am new in PHP and would need some explanation. Here is a code where we connect to MySQL with PHP. Can you please explain me where is the statement that makes the connection? I can see only that we define what the value of $conn is, but does it mean execution as well? The other thing is: where do we create the database? I can see that we give the string "CREATE DATABASE myDB" as a value to $sql and we have an if statement, but does the expression ($conn->query($sql) === TRUE) also evaluated? It is strange for me, can somebody please explain it to me?! :) Thanks!
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
Here is a simple explanation of which lines do what. If you would like to know specifically what the individual parts of these mean, then please say which ones so they can be further explained to you. Or the correct links pointed to.
I notice that you are using the W3Schools example, as an almost exact copy and paste. Have you installed MySQL on your machine and created a username and password?
<?php
$servername = "localhost"; // This is the location of your server running MySQL
$username = "username"; // This is the username for MySQL
$password = "password"; // This is the password for MySQL
// Create connection
$conn = new mysqli($servername, $username, $password); // This is where you create a connection
// Check connection
if ($conn->connect_error) { // This checks if the connection happened
die("Connection failed: " . $conn->connect_error); // and produces an error message if not
} // otherwise we move on
// Create database
$sql = "CREATE DATABASE myDB"; // This is the SQL query which is sent to the MySQL server
if ($conn->query($sql) === TRUE) { // When the if statement begins here, it executes the query and test if it returns true
echo "Database created successfully"; // If it returns true then here is the message is returns
}
else {
echo "Error creating database: " . $conn->error; // Or if there was error with the query this is returned
}
$conn->close(); // Close the connection when it is no longer in use
?>
Although, your question does not belong here (This place is to help with your coding issues), but I will give you a bit explanation.
PHP reads each line and EXECUTES It. the create connection part opens a new connection using the "new" object and save it a variable ($conn),
($conn->connect_error) checks if the connection was successful with connect_error property. if it was connected, continue, or else through and error and stop.
If connection was successful, then create the database based on connection opened in variable ($conn).

Mysqli stopped working because of fetch issue

I have just come back to a project that was working fine a month ago. Today I have found im getting a "Warning: mysqli::query(): Couldn't fetch mysqli" error and I have no idea why. I have tried changing the if statement but I still get the same result.
php page
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
error_reporting(E_ALL); ini_set('display_errors', 1);
$email = $_SESSION['email'];
$name = $_SESSION['name'];
$hash = $_SESSION['hash'];
$password = $hash;
echo $name;
echo '<br>';
echo $email;
echo '<br>';
echo $hash;
echo '<br>';
$sql = "INSERT INTO signed_up(`name`, `email`, `password`) VALUES ('$name', '$email', '$password')";
if ($mysqli->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}
//if ($result = $mysqli->query("INSERT INTO `signed_up`(`name`, `email`, `password`) VALUES ('$name', '$email', '$password')")){
//
//header('location: ../register_success.php');
//// $result->close();
//
//}
//else {
// echo "error";
//}
?>
The error im getting
you have succesfuly connected to the database
gptgeoff
up666315#myport.ac.uk
$2y$10$JUi/eSNwbTnM4ZyWetEL6.ELSepLPKLkEiJdi4WYMyp/sEEAk9hKe
Warning: mysqli::query(): Couldn't fetch mysqli in /home/sites/unitest.co.uk/public_html/includes/register_user.inc.php on line 24 Warning: main(): Couldn't fetch mysqli in /home/sites/unitest.co.uk/public_html/includes/register_user.inc.php on line 27 Error: INSERT INTO signed_up(name, email, password) VALUES ('gptgeoff', 'up666315#myport.ac.uk', '$2y$10$JUi/eSNwbTnM4ZyWetEL6.ELSepLPKLkEiJdi4WYMyp/sEEAk9hKe')
The db_connect.php file works because I'm getting the "you have succesfuly connected to the database" displaying, the session variables are being passed and echoed out in both the echo statements and in the values of the $sql query so I am unable to understand why this has stopped working, can anyone advice please
db_connect.php
<?php
include_once 'psl-config.php'; // As functions.php is not included
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if(!$mysqli) {
die('error connecting to database');
}
echo 'you have succesfuly connected to the database'.'<br/><br/>';
?>
This line:
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
creates an object. It is an instance of the class mysqli. An object will always be true. Your if statement checks if $mysqli is false. This if statement is wrong, because whether the connection was successful or not the object will never be false.
Do not check for connection errors manually. Your connection failed and when it did PHP threw a warning. Please check your PHP configuration for error reporting, because you have probably warnings silenced. Also please enable mysqli error reporting. Insert this line before creating an instance of mysqli.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

Connecting to Database through functions and external files

I am simply trying to connect to my database by requiring another file with the connection function in it. I have tried numerous approaches but I always either get a blank page or my message 'failed execution'. Would appreciate someone pointing out where I am going wrong. Thanks.
config.php
define('DB_HOST','host'); //DATABASE HOST
define('DB_USERNAME','username'); //DATABASE USERNAME
define('DB_PASSWORD','password'); //DATABSE PASSWORD
define('DB_NAME','name'); //DATABASE NAME
function connectDB(){
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(!$mysqli){
trigger_error ('Avon Maitland Schools Canada could not establish a connection to the database at this time. Please try again later or contact info#yourschoolsincanada.com to inquire about this issue.'.mysqli_connect_error());
}else{
return $mysqli;
}
}
And then my register file
register.php
require_once('includes/config.php');
$db_connection = connectDB();
if(isset($_POST['register'])){
/*ALL MY POSTING OF VARIABLE AND VALIDATION IS HERE BUT NOT THE ISSUE*/
$sql = ("INSERT INTO members (username, email, password_1) VALUES (?,?,?)");
//Prepare our query
$stmt = $db_connection->prepare($sql) or die("Failed Execution");
//Can not proceed if we can not prepare the query
if(false===$stmt){
die('prepare() failed: ' . htmlspecialchars($db_connection->error));
}
//Bind the fields and there paramters to our query in our testing variable $next_step
$next_step = $stmt->bind_param('sss', $username, $email, $db_pass);
//If next_step is false then it didn't work and there is no sense of proceeding
if($false===$next_step){
die('bind_param() failed: ' . htmlspecialchars($db_connection->error));
}
//Place the Execute into a variable and test if it executed or not
$next_step = $stmt->execute();
//If next_step is false then it didn't work and there is no sense of proceeding
if(false===$next_step){
die('execute() failed: ' . htmlspecialchars($db_connection->error));
}
header('Location: redirect somewhere');
exit();
//Close the STMT Connection
$stmt->close();
}
I have tried passing the $mysqli variable into the functions but that does not work. And tried adding the Defines into the function as well and passing them into variables themselves with no luck either. If I don't get a blank page It just dies at the prepare and says 'Failed Execution'. I am stumped.
Substitute die("Failed Execution"); with the below code..
$stmt = $db_connection->prepare($sql) or die($db_connection->error); //<-- Assuming $db_connection is a valid MYSQLi connection..
If you are providing your own customized error messages, it will be hard to find out the error.
OK I figured it out, I am building this application through a wordpress child theme. The problem was that most of my defined variables had the same name as those in the wp-config.php so It was always looking in the wrong place with the wrong credentials and such. Changes those and it works fine. Thank you for you all your help especially with the error reporting that is what saved me. thanks again

MySQL won't read password from configuration file

I have an html form on my site and I am trying to process the data and then store it in a mysql database on my server. In order to connect securely to mysql via php, I have, as suggested here, placed the login information in a configuration file outside of the main webroot.
The code executes seamlessly when it is written like this:
<?php
$mysqli = mysqli_init( );
$mysqli->options(MYSQLI_READ_DEFAULT_FILE, "/this/is/the/filepath/to/my.cnf");
$mysqli->real_connect(NULL, NULL,'*********',NULL );
if (mysqli_connect_errno()) {
printf("Connect failed: ", mysqli_connect_error());
exit();
}
$email = $mysqli->real_escape_string($_POST['email']);
$mysqli->query("INSERT INTO subscribetest (email) VALUES ('$email')");
?>
But when I take the password out, like this:
<?php
$mysqli = mysqli_init( );
$mysqli->options(MYSQLI_READ_DEFAULT_FILE, "/this/is/the/filepath/to/my.cnf");
$mysqli->real_connect(NULL,NULL,NULL,NULL );
if (mysqli_connect_errno()) {
printf("Connect failed: ", mysqli_connect_error());
exit();
}
$email = $mysqli->real_escape_string($_POST['email']);
$mysqli->query("INSERT INTO subscribetest (email) VALUES ('$email')");
?>
The code crashes and I am given the error message: 'Warning: mysqli::real_connect(). Access denied for 'user'#'webaddress.net' (using password:NO)'
Why can my php script read everything EXCEPT the password from the config file? It is able to read the username, host, and database from the config file; the password is the only one which is left out. I've looked everywhere, spent hours on this, but I haven't been able to find any solutions. Has anyone else had this problem? What can I do?
The documentation says that setting the password parameter in real_connect() to NULL means "user does not need a password". Does it work if you call it without any parameters (they're all optional)?
This bug still seems to exist: https://bugs.php.net/bug.php?id=43812
Workaround:
$iniData = file_get_contents('/etc/mysql/debian.cnf');
$iniData = preg_replace('/#.*$/m', '', $iniData);
$mysqlConfig = parse_ini_string($iniData, true);
$mysqli = new mysqli( $mysqlConfig['client']['host'], $mysqlConfig['client']['user'], $mysqlConfig['client']['password'] );
if ( $mysqli->connect_error ) {
die(sprintf("MySQL Connect Error: %s", $mysqli->connect_error));
}

Categories