mysql_connect() not working from class - php

Just moved my site to new hosting. On the new server mysql_connect() works fine if called without using classes or inside of the method but not from the _construct. When connecting from the _construct the following error displays:
Access denied for user 'root'#'localhost' (using password: NO)...my configuration defines the user not as root but as USERNAME and does provides a password.
PHP 5.6, MySQL 5.5, Linux
Class File:
function __construct(){
error_reporting(E_ERROR);
$dbhost = 'localhost';
$dbuser = 'USERNAME';
$dbpass = 'PASSWORD';
$dbname = 'DATABASENAME';
$this->urlAppPath = "http://www.myurl.com/CD/";
// connect to the database
$this->db = mysql_connect($dbhost, $dbuser, $dbpass) or die("Connection Error: " . $SQL);
mysql_select_db($dbname);
}
function validatePerson($personID) {
$SQL = "SELECT *,COUNT(*) AS total FROM zen_customers WHERE customers_classware_id = '$personID'";
$result = mysql_query( $SQL ) or die("Could not execute query 1 . ".$SQL." ".mysql_error()." & ". $dbhost ." ".$dbuser ." ".$dbpass." ".$dbname);
}
Call Method File:
require_once('./clsCart.php');
$myclass = new clsCart();
$result2 = $myclass->validatePerson($personID);
Note
If I define and call the connection within the file that I have been trying to call the method...that is instead of calling the method it works. If I define and call the connection within the method it works...but if I define and call the connection within the construct() it does not work...error "Access denied for user 'root'#'localhost' (using password: NO)". This seems to be specific to some servers...regardless of using PHP 5.6 or lower & MySQL 5.6 or lower.
So, if I use :
$dbhost = 'localhost';
$dbuser = 'USERNAME';
$dbpass = 'PASSWORD';
$dbname = 'DATABASENAME';
// connect to the database
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Connection Error: " . $SQL);
mysql_select_db($dbname);
Outside of the class or within the method then it works...but, I should (as I have in the past) be able to connect within the construct().

This seems to be related to a server issue. From the __contruct() only the Database default user information is being recognized. Everywhere else in the applications uses the User created for the database, but the construct will only connect when using the default database user on this server. Other servers are not having this issue, such that any database user with all privileges work.

You have to use mysqli_connect. Please never use mysql_connect it deprecated in PHP 5.5.0 and onwards. If still you face issue please let us know.
Following code for mysqli_connect :
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Definition and Usage
The mysqli_connect() function opens a new connection to the MySQL server.
Syntax
mysqli_connect(host,username,password,dbname,port,socket);
Parameter Description
port Optional. Specifies the port number to attempt to connect to the MySQL server.
socket Optional. Specifies the socket or named pipe to be used.

Related

How to grants access to mysql for "root"#"localhost" in the dbh php-file?

Trying to create a login-system, but the browser just shows the error message (Access denied for user 'root'#'localhost'). I have confirmed the password for mysql, but realized that the password to get into the server is needed, but not provided.
Part of my php-file looks like this:
<?php
session_start(); //Nevermind this indent
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = ''; //redacted, but provided
$DATABASE_NAME = 'users';
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if ( mysqli_connect_errno() ) {
exit('Failed to connect to MySQL: ' . mysqli_connect_error()); // it always catches here
}
It contains the mysqli_connect() with all the variables to the database, but not to get into the mysql server.
I'm using php 8.0 with mariaDB on Ubuntu server 20.04.
How can I provide the password, grant the access to or else to get into the mariaDB-server? I would like to keep the password if possible. And yeah, I'm a beginner.

Access denied or blank page with mysqli but not mysql

I've looked through StackOverflow for an answer to this and have so far come up empty handed. I know some have had a similar issue, but so far none of the responses to the issues have worked.
So I work on two sites, both of which are on the same host with the same PHP Admin set up (different accounts and domains, sites are not affiliated). One of them uses MySqli perfectly, without issues, while the other either gives a database selection failure, localhost access denied with password as "NO" or a blank page when I attempt to replace the MySql with MySqli.
The deprecated code:
$host = "LOCALHOST";
$usr = "USER";
$pwd = "PASSWORD";
$dbname = "DATABASE";
$connection = #mysql_connect($host,$usr,$pwd);
if(!$connection){
die("No connection.");
}
mysql_select_db($dbname,$connection);
The MySqli I am attempting (identical to the site that MySqli works perfectly on):
$host = "LOCALHOST";
$usr = "USER";
$pwd = "PASSWORD";
$dbname = "DATABASE";
$connection = mysqli_connect($host,$usr,$pwd);
if (!$connection) {
die("No connection.");
}
$db_select = mysqli_select_db($connection, $dbname);
if (!$db_select) {
die("Database selection failed: " . mysqli_error($connection));
}
So the PHP error codes did not work at all and it had nothing to do with the local host or port, so I first checked to make sure mysqli_connect was on. Next, I ran a simple test where I echoed a random word before each mysqli command.
echo 'Passed.';
global $c_mysqli;
$conn = new mysqli($host, $usr, $pwd, $dbname);
echo '<br>Passed global mysqli.';
I found that my second pass was not working, and then proceeded to do an error message. An error showed up then. However, nothing I did fixed the issue... then I realized that one of my files, the header file, is the meat and potatoes and if it were to fail then everything else would fail too.
Sure enough, one of my lines of code contained a mysql connection and not mysqli. Long story short, double check and triple check to make sure that all
$statement = mysql_query("STATEMENT");
$query = mysql_fetch_array($statement);
Appear as
$statement = $conn->query("STATEMENT");
$query = mysqli_fetch_array($statement);

Connect to AWS mysql over SSL in PHP?

I am trying to connect to (remote) AWS MYSQL database using php and ssl.
I created a database user and could connect with it from php and also on console.
Then I modified the user to use SSL with "require ssl" in the database.
I can stil connect on the console by:
mysql -h host -u username -p --ssl
But in php I get an ERROR 2002.
$con=mysqli_init();
mysqli_ssl_set($con,NULL,NULL,"cacert.pem",NULL,NULL);
$link = mysqli_real_connect($con, "host", "username", "password");
As far as I know the ssl_set parameters doesn't matter with AWS databases.
How to connect to Amazon RDS via SSL?
I think it has to do with the mysqli_ssl_set method, without it a connection is made and access is denied by database and this is the correct behaviour. It might be some configuration error on client side, but I have no idea what I shoud check.
The error is fired by mysqli_real_connect, as mysqli_ssl_set always returns true, just after it tries to connect will it receive an error.
I noticed it did not work for me until I specified the port. The following worked:
$db = mysqli_init();
$db->options(MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, true);
$db->ssl_set(NULL, NULL, 'rds-combined-ca-bundle.pem', NULL, NULL);
$db->connect($host, $user, $pass, $db, 3306);
$servername = "only-ssl-db.ct5b4uz1gops.eu-central-1.rds.amazonaws.com";
$username = "username";
$password = "password";
$dbname = "dbname";
$con = mysqli_init();
if (!$con){
die("mysqli_init failed");
}
mysqli_ssl_set($con,NULL,NULL,'rds-combined-ca-bundle.pem',NULL,'DHE-RSA-AES256-SHA');
if (!mysqli_real_connect($con,$servername, $username, $password, $dbname))
{
die("Connect Error: " . mysqli_connect_error());
}
// Some queries...
echo "Database connected";
printf("Client version: %d\n", mysqli_get_client_version());
mysqli_close($con);

Cant connect to my Bluehost SQLDatabase with php script

i wrote a php script which should connect me with my database. I also uploaded the files in the public_html section, but it always throws this error :
Warning: mysqli::mysqli(): (HY000/2002): Connection refused in /Applications/XAMPP/xamppfiles/htdocs/FoodHelperSwift/db/public_html.php on line 24
Here is the line : $this->conn = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
This is my code :
public_html
var $conn = null;
var $result = null;
public $dbhost = null;
public $dbname = null;
public $dbuser = null;
public $dbpass = null;
function __construct($dbhost, $dbuser, $dbpassword, $dbname) {
$this->dbhost = $dbhost;
$this->dbuser = $dbuser;
$this->dbpass = $dbpassword;
$this->dbname = $dbname;
}
public function openConnection()
{
$this->conn = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
echo "YESSSS";
echo $this->dbhost;
echo $this->dbuser;
echo $this->dbpass;
echo $this->dbname;
if(mysqli_connect_errno())
{
throw new Exception("Could not connect with database");
$this->conn->set_charset("utf8");
}
}
public function closeConnection()
{
if ($this->conn != null)
{
$this->conn->close();
}
}
}
and
register user
:
require("../db/public_html.php");
$dbhost = "127.0.0.1";
$dbname = "xxxxxxxx";
$dbuser = "xxxxxxxxx";
$dbpassword = "xxxxxxx";
$returnValue = array();
if(empty($_REQUEST["userEmail"]) || empty($_REQUEST["userPassword"])
|| empty($_REQUEST["userFirstName"])
|| empty($_REQUEST["userLastName"]))
{
$returnValue["status"]="400";
$returnValue["message"]="Missing required information";
echo json_encode($returnValue);
return;
}
$userEmail = htmlentities($_REQUEST["userEmail"]);
$userPassword = htmlentities($_REQUEST["userPassword"]);
$userFirstName = htmlentities($_REQUEST["userFirstName"]);
$userLastName = htmlentities($_REQUEST["userLastName"]);
$salt = openssl_random_pseudo_bytes(16);
$secured_password = sha1($userPassword . $salt);
$dao = new MySQLDAO($dbhost, $dbuser, $dbpassword, $dbname);
$dao->openConnection();
The password etc. is right and i also tried localhost, but then i got an error that he cant find the file maybe you could help me.
Most likely you're not following steps provided by your website hosting provider.
Third party hosting solutions usually require you setup your remote IP
From the error message you specified it looks like you're trying to do this from your own home XAMP web service.
First - the basics
:
localhost - won't work from home - because that's going to look for your own MySQL database not the hosted db
Second - logging in from home (or remotely)
read the docs (always a good idea) Remote access to Bluehost MySQL
Use the following configuration settings for connecting to your database
Host name = (use the server IP address)
Database name = (cpanelUsername_databaseName)
Database username = (cpanelUsername_databaseUsername)
Database password = (the password you entered for that database user)
MySQL Connection Port = 3306
TCP or UDP, either is fine.
Allowing a Remote Server to Access Your Database
Before connecting to MySQL from another computer, the connecting computer must be enabled as an Access Host.
Log into cPanel and click the Remote MySQL icon, under Databases.
Type in the connecting IP address, and click the Add Host button.
Note: You can find and add your IP address directly from this tool. Look for Your IP is: 123.123.12.123 [Add]. Clicking the [Add] link will input your IP into the field box below.
Click Add, and you should now be able to connect remotely to your database.
To troubleshoot this, strip your code down to the basics. Make yourself a little testMyDb.php file, containing only the minimal stuff. For example:
$dbhost = "127.0.0.1";
$dbname = "xxxxxxxx";
$dbuser = "xxxxxxxxx";
$dbpassword = "xxxxxxx";
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
Once you have that working, you can proceed to debug your php class and make sure you are setting things up correctly.
Your file named public_html.php contains some code that's part of a php class implementation (for example __construct()), but I don't see a class ClassName { line to set up a class definition. It's possible you've copied some fragments of code from somewhere without getting it all.
If your simple test DOESN'T work, check with bluehost's tech support krewe. You may need some special credentials or database name to connect to MySQL from one of their Windows hosts.
If you're using the MySQL server on a bluehost machine, and trying to connect to it from your local machine, that will not work (especially not with 127.0.0.1). You'll need to configure bluehost to allow remote MySQL connections, and you'll have to use the actual MySQL hostname.

On PHP, about using mysql or mysqli

I'm running MySQL server version 5.0.77 on Linux (Rocks Cluster Distro), and I'm trying to connect to the same database with both MySQL and MySQLi PHP functions. The problem is that when the MySQLi code fragment is executed it does work, but the MySQL fragment doesn't (in case it matters; not even on separate PHP files).
As shown in the code below I'm attempting a connection to the same database on the same host, using the same user and password but the MySQL function version fails.
(If it helps I've already tried the same code on MySQL server 5.6.20 running in Windows with the same details ((local)host, database, user, password) and both functions work).
What might be the problem? Any help is appreciated.
The output and code fragment is the following:
Code:
<?PHP
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tedDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Error [mysqli]: ".$conn->connect_error);
} else {
echo "Success [mysqli]";
}
echo "<br><br>";
$link = mysql_connect($servername, $username, $password)
or die("Error [mysql_connect]: ".mysql_error());
echo "Success [mysql_connect]";
?>
Output (LINUX):
Success [mysqli]
Error: Access denied for user 'root'#'localhost' (using password: NO)
Output (Windows):
Success [mysqli]
Success [mysql_connect]

Categories