Connecting to Database through functions and external files - php

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

Related

Verify if connection to the mySQL exists or let Apache do it

I created a function to connect to the db in php:
function fn_connect($is_write = false)
{
$host = '127.0.0.1';
$db = 'name_db';
if ($is_write) {
$user = 'user_write';
$pwd = 'password_write';
} else {
$user = 'user_read';
$pwd = 'password_read';
}
$conn = new mysqli($host, $user, $pwd, $db);
if ($conn->connect_error) {
die('The database is not available. Please, try again later.');
}
return $conn;
}
When I need to connect, im calling it (and closing it) like this
$conn = fn_connect(true);
$stmt = $conn->prepare($q);
$stmt->execute();
....
$stmt->close();
$conn->close();
I thought it will be a good idea to verify if the connection exists, that way, I guess, I save connecting to the db every time for nothing, like this:
if (!isset($conn)) $conn = fn_connect(true);
$stmt = $conn->prepare($q);
$stmt->execute();
....
$stmt->close();
if (isset($conn)) $conn->close();
Is this a good idea, a good practice? Should I jut connect normally and let Apache/PHP do the rest (no need to verify nothing)?
It is good practiose and good style to check the connection, before letting php try to get or send data.
What is not good style is to use die in your connection, because it leaves a broken page.
Better is to design the page so that page still works when the connection is broken.

HTTP error when trying to access mysql database

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.

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).

PHP Fatal error: Call to a member function execute() on a non-object( OPENSHIFT )

Getting this error:
PHP Fatal error: Call to a member function execute() on a non-object
while pushing new data to my openshit application.
function createAppInfo($title,$blog_link,$job_link,$description,$author,$status){
$db = dbopen();
$title = $db->real_escape_string($title);
$author = $db->real_escape_string($author);
$description = $db->real_escape_string($description);
$job_link = $db->real_escape_string($job_link);
$blog_link = $db->real_escape_string($blog_link);
$status = $db->real_escape_string($status);
$stmt = $db->prepare("INSERT INTO `app`(title,blog_link,job_link,description,author,status)
values('$title','$blog_link','$job_link','$description','$author','$status')");
$stmt->bind_param('s',$title,$blog_link,$job_link,$description,$author,$status); // bind inputs to the parameter
/* execute prepared statement */
$stmt->execute();
$stmt->close();
return true;
}
This is the code i am running, but it seems to me that Openshift is bloacking prepare or prepare is not working correctly i dont know..cause the code is working on local machine.
Also, its i change it to regular $db-query(INSERT) its working absolutely fine.
UPDATE:
dbcon.php file
<?php
function dbopen(){
$host="localhost"; // Host name
$username="**"; // Mysql username
$password="**"; // Mysql password
$db_name="***"; // Database name
$db= new mysqli($host, $username, $password, $db_name);
if (!$db)
{
die('Could not connect: ' . mysql_error());
}
return($db);
}?>
I am including this file to call dbopen()
see http://php.net/manual/fr/pdostatement.bindparam.php , there aren't as many parameters...
see #class comment: why bindparam for parameters that you already included in your request?
So maybe trying smthg like this should help? :
$stmt = $db->prepare("INSERT INTO `app` (title,blog_link,job_link,description,author,status) values(:title,:blog_link,:job_link,:description,:author,:status)");
$stmt->bind_param(':title',$title);
$stmt->bind_param(':blog_link', $blog_link);
etc...
$stmt->execute();
or simply let your prepare like you did, but forget about bind_param (but previous solution should be safer).
First of all, you do not need to use real_escape_string at all, prepared statements escapes all values automatically. Secondly, when binding your parameters, you need to specify the type for each (answer below assumes all are strings).
EDIT :
Upon doing some research, you must use the environment variables in the MYSQL cartridge when establishing a connection through openshift.
dbcon.php:
<?php
function dbopen(){
define('DB_HOST', getenv('OPENSHIFT_MYSQL_DB_HOST'));
define('DB_PORT', getenv('OPENSHIFT_MYSQL_DB_PORT'));
define('DB_USER', getenv('OPENSHIFT_MYSQL_DB_USERNAME'));
define('DB_PASS', getenv('OPENSHIFT_MYSQL_DB_PASSWORD'));
define('DB_NAME', getenv('OPENSHIFT_GEAR_NAME'));
$db= new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (!$db)
{
die('Could not connect: ' . mysql_error());
}
return($db);
}?>
MYSQL Query:
$db = dbopen();
$stmt = $db->prepare("INSERT INTO `app`(title,blog_link,job_link,description,author,status)
VALUES(?,?,?,?,?,?)");
$stmt->bind_param('ssssss',$title,$blog_link,$job_link,$description,$author,$status);
/* execute prepared statement */
$stmt->execute();
$stmt->close();

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