mysqli_connect() expects parameter 1 to be string, array given - php

I have an issue with mysqli_connect expecting the parameter to be a string and apparently an array is given
I have a php file that writes the mysqli_connect information to a file from variables "userconnection.txt"
'localhost','root','','forum'
Then I have a standard php connection.php file with the added userconnection.txt file for the host user and password.
<?php
$connectionlink = file('userconnection.txt');
$connection = mysqli_connect($connectionlink);
if (!$connection) {
die('Connect Error: ' . mysqli_connect_error());
}
?>
It spits out the error:
Warning: mysqli_connect() expects parameter 1 to be string, array given in /Applications/XAMPP/xamppfiles/htdocs/forum/install files/connection.php on line 4
Connect Error:

This will not work and is actually a security risk.
Security
The txt file might be accessibe from your website via some URL. An attacker who know that URL (not difficult at all) can get the file and now has your login credentials.
Save the file outside your webroot or change it's extension and contents so they arent publcly avaiable. maybe a PHP file?
Error
You have two problems. First one is that file returns all lines of the file as individual lines and not as one string. Use file_get_contents instead.
Anyways, if you do this, you will still have all three parameters in one single variable of type string. But the mysqli_connect function needs three seperate variables and not one. You can fix this with a explode.
Quick and dirty Solution
$filecontents = file_get_contents('userconnection.txt');
$connectionvars = explode("," $filecontents);
$connection = mysqli_connect($connectionvars[0], $connectionvars[1], $connectionvars[2]);
if (!$connection) {
die('Connect Error: ' . mysqli_connect_error());
}
Better but more complex solution
Create a PHP file with your connection variables:
<?php
$DBHost = "host";
$DBUser = "user";
$DBPass = "pass";
change your connection file to this:
<?php
require("connectionsettings.php");
$connection = mysqli_connect($DBHost, $DBUser, $DBPass);
if (!$connection) {
die('Connect Error: ' . mysqli_connect_error());
}

Because file functions return value is an array. Say var_dump($connectionlink);
That is much more better, if you store your parameters in variables or in constants. Use .php instead .txt, and include that file.
For example:
include('connection.php');
$link = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME) or die("Error " . mysqli_error($link));
and in your connection.php
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'username');
define('DB_PASS', 'password of the user');
define('DB_NAME', 'name of your database');

The problem is in line with $connection = mysqli_connect($connectionlink). Because variable isn't a string (In this case it's '$connectionlink'), so it shows the error.
In my situation I changed it to $connection = mysqli_query($connectionlink) and it solve everything.

Related

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

mysql_connect() not working from class

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.

Open DB Connection within PHP Function

I wrote an addon module for our WHMCS billing system a long time ago that we recently realized was causing some issues. Essentially each module's PHP file is loaded regardless if it is actually used or not, where this is how their "hook" system is setup.
When I wrote the module, I included my "db_config.php" file at the top in the global space, which I now realize is causing this database to load every page and is apparently being written to when it shouldn't be. As this is the case, I would like to open the Database connection at the top of the function and close it at the end of the function.
I've never seen this done before nor can I find much information on it. The contents of my db_config.php appear as follows and I am wondering if I can just include_once() inside of the function?
<?php
// Connection's Parameters
$hostname = "xxx.xxx.xxx.xxx";
$database = "database";
$username = "username";
$password = "password";
// Connection
$tca_conn = mysql_connect($hostname, $username, $password);
if(!$tca_conn)
{
die('Cannot Establish Connection to Database : ' . mysql_error());
}
$tca_db = mysql_select_db($database, $tca_conn);
if (!$tca_db)
{
die ('Cannot Select Database : ' . mysql_error());
}
?>
Try this one.It might work for you.
$tca_db = mysql_select_db($database);
instead of
$tca_db = mysql_select_db($database, $tca_conn);

PHP getting data from SQL from database

Hey I'm wanting to retrieve some data from the a database. But it seems whenever I enter my credentials into the SQL database to retrieve the data I get the following error:
Since i presume this is a similar use case as your last question
Your php file is missing the configuration of the connection:
<?php
$dbuser = "******";
$dbpass = "*******";
$db = "SSID";
$connect = OCILogon($dbuser, $dbpass, $db);
if (!$connect) {
echo "An error occurred connecting to the database";
exit;
}
So it knows which connection you are using and passing to the checkUserPass() function.
UPDATE:
For the table name you need to pass $dbtable as you can see in the function declaration
function checkUserPass($connect,$username, $password, $dbtable)
so either set a $dbtable variable before calling the function:
$dbtable="register_table";
or send it immediately as a string:
function checkUserPass($connect,$username, $password, "register_table")

Check if connected to database (right username/password, host)

I would love to check if i can connect to database using given username, password, and database host.
So far i was trying:
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$conndatabase = mysql_select_db($dbname);
if(!mysql_ping($conn) || !$conndatabase){
//do something when cant connect
} else {
//do something when you connected
}
It works when i give bad $dbname, cuz it cant select this database. But when i give wrong host, username or password, it will give me white page with errors. For example:
Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'rootx'#'localhost' (using password: YES) in C:\xampp\htdocs\strony\planer\config\opendb.php on line 6
Warning: mysql_ping() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\strony\planer\grupy.php on line 3
Question:
Is there a way to check if i can connect using given data without errors? It just gives errors before getting to mysql_ping()
EDIT
After trying Mike Brant solution, i think i could have explained it wrong. I am trying to connect to database, and if it lets me, it shows user page he wanted to access, but when it's impossible, it redirects him to the other page, to modify database information.
if(!$conndatabase){
header('Location: index.php');
}
I am using that for checking if database exists. But if i try if(!$conn) or something similar, its too late, because i got errors displayed on $conn = mysql_connect($dbhost, $dbuser, $dbpass). So i cant redirect, as it gives me
Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'root'#'localhost'~~
Warning: Cannot modify header information - headers already sent by~~
Yes. Just test the value of $conn. If it is false then the connection failed, and you shouldn't even try to proceed to the db selection step.
Your code might look like this:
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (false === $conn) {
throw new Exception('Could not connect to database: ' . mysql_error());
}
$db_select = mysql_select_db($dbname. $conn);
if (false === $db_select) {
throw new Exception('Could not select database: ' . mysql_error($conn));
}
The PHP documentation is very clear on this: http://php.net/manual/en/function.mysql-connect.php
By the way, you should look at using mysqli or PDO as mysql_* functions are deprecated.
Try to debug your connection with something like
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link){
die('Could not connect: ' . mysql_error());
}
In this way you can easilly check if connection is estabilished otherwise you will print an error.
Then I would like to remember you that mysql_ functions are deprecated so i would advise you to switch to mysqli or PDO
When you look on my edit in question, you can see those answers didn't solve my problem completely. I still lacked some way to avoid errors. That's where i used error_reporting(0);.
I am not sure if that's best solution, but it works like a charm for me.
So the code for everything i tried to achieve looks like that:
opendb.php file
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password123';
$dbname = 'databasename';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$conndatabase = mysql_select_db($dbname);
?>
And there on the site i am checking connection:
<?php
error_reporting(0);
include 'opendb.php';
if(!mysql_ping($conn) || !$conndatabase){
header('Location: index.php'); //or any other site where you can config your database connection information.
}
So yeah, thats complete solution to my problem. I guess i could use !$conn instead of !mysql_ping($conn) with same result.
As has already been said, it’s the first example on the PHP manual page for the mysql_connect function.
Secondly, you should be either using the mysqli_ functions or PDO, as the mysql_ functions are deprecated and currently being phased out.
To check a connection with PDO:
try {
$db = new PDO('mysql:host=127.0.0.1;dbname=dbname', 'user', 'pass');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
header('HTTP/1.1 500 Internal Server Error');
die($e->getMessage());
}

Categories