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));
}
Related
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.
I'm encountering an issue when I try to use php to create a database. I've google around, ensured that the user has permission to create a database and it still doesn't work.
I'm able to use PHP to create and modify tables once I create the database manually, but I'd like this code to run in PHP for personal reasons.
Here's the code, just in case I'm missing something.
*edit: grammar
<?php
$servername = "localhost";
$username = "user";
$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 inkflow_backend";
if ($conn->query($sql) === TRUE){
echo "Database created successfully, continue.";
} else{
echo "Error creating database: " . $conn->error . "Please contact the developer or your network administrator.";
}
//Close connection
$conn->close();
?>
Review the quotes that you're using when printing a link to setup2.php.
They are causing a syntax error. Just putting a backslash before them would solve the problem:
<a href=\"setup2.php\" ...
I've spent some hours on finding a suitable free web hosting service for a project's website. It's nothing overly fancy and doesn't include much more than a MySQL database connection and a very simple login system. However, I have not been able to find a single hosting service that gets the site running properly (everything is working fine locally).
In particular, the login script doesn't work online (similar problem with two web hosting services, Byethost and Web4Free.eu
<?php
error_reporting(E_ALL);
session_start();
include "db-connect.php";
if (isset($_GET['login'])) {
$login = $_GET['login'];
if ($login == 1 && isset($_POST['email']) && isset($_POST['password'])) {
$email = $_POST['email'];
$password = $_POST['password'];
$mysqli = checkDataBaseConnection();
$query = $mysqli->query("SELECT `user`.`password` FROM `user`, `alumni` WHERE `alumni`.`mail`='".$email."' AND `alumni`.`id`=`user`.`id`");
$hash_raw = $query->fetch_array();
if (!empty($hash_raw)) {
$hash = $hash_raw[0];
if (password_verify($password, $hash)) {
$_SESSION['loggedin'] = 1;
header('Location: dash.php');
exit;
}
}
}
}
?>
db-connect.php:
<?php
function checkDataBaseConnection() {
// Defining all variables, etc.
if(!isset($mysqli)) {
$mysqli = new mysqli($mysql_host, $mysql_name, $mysql_pw, $mysql_db);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!mysqli_set_charset($mysqli, "utf8")) {
printf("Error loading character set utf8: %s\n", mysqli_error($mysqli));
}
}
return $mysqli;
}
?>
Despite having set the error_reporting to E_ALL, no error is displayed after submitting an e-mail adress that is saved within the database (no matter if the password is correct or not). In fact, nothing is displayed, only a literally empty page. If the e-mail adress is not in the database, everything works fine. Even more strangely, the database connection works perfectly in another (non-login).
Is there some obvious error I have overlooked or are these problems related to some PHP settings of the hosting service? If so, can you recommend another free hosting service that is supporting these features?
Thanks a lot,
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
I am creating an install php script that creates some tables in a database and creates a config file. Everything works but I don't know how to check if their host, username and password are correct. I currently check if the database is there or not.. any help would be appreciated. This is on a WAMP server using PHP 5.4.12. The variables come from a basic form.
session_start();
$_SESSION['dbdatabase'] = $_POST['dbdatabase'];
$_SESSION['dbhost'] = $_POST['dbhost'];
$_SESSION['dbusername'] = $_POST['dbusername'];
$_SESSION['dbpassword'] = $_POST['dbpassword'];
$conn=mysqli_connect($_SESSION['dbhost'],$_SESSION['dbusername'],$_SESSION['dbpassword']);
if(!mysqli_select_db($conn, $_SESSION['dbdatabase']))
{
die ('Database does not exists. Please create a database before installing Pazzilla BackOffice.');
}
else
{
The function you are looking for is mysqli_connect_error().
<?php
$link = mysqli_connect('localhost', 'invalid_user', 'password');
if (!$link) {
die('Invalid database credentials. Mysql said: ' . mysqli_connect_error());
}
?>