Warning: mysqli_select_db() expects parameter 1 to be mysqli, null given - php

I keep getting an error message.
<?php
mysqli_connect("localhost", "root", "");
mysqli_select_db("account");
?>
Here is the error message I get when I try to load it in the browser:
Warning: mysqli_select_db() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\MyWebsite\TechanexSiteBase\connect.php on line 4.

Complete Guide
Note :
With mysqli you can specify the Database Name in mysqli_connect()
You have to use mysqli_connect_error(), not mysqli_error(), to get the
error from mysqli_connect(), because the latter requires you to supply
a valid connection.
<?php
// Creating a database connection
$connection = mysqli_connect("localhost", "root", "", "databse_name");
if (!$connection) {
die("Database connection failed: " . mysqli_connect_error());
}
// Selecting a database
$db_select = mysqli_select_db($connection, "databse_name");
if (!$db_select) {
die("Database selection failed: " . mysqli_connect_error());
}
?>
Just do copy and paste & Then change the database name

The question body makes no sense, as the code is inconsistent with the error message. For the code present, the error message would have been Warning: mysqli_select_db() expects parameter 1 to be mysqli, string given.
That aside, it seems this question attracts many visitors who are genuinely getting the error from the question title. For them, here is a complete and proper guide on How to connect using mysqli:
$host = '127.0.0.1';
$db = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$mysqli = mysqli_connect($host, $user, $pass, $db);
mysqli_set_charset($mysqli, $charset);
} catch (\mysqli_sql_exception $e) {
throw new \mysqli_sql_exception($e->getMessage(), $e->getCode());
}
By following this routine, one would never ever get an error like this. As well as many other errors that would be induced by the code suggested in the other answers.
Important advantages of this code are
as you can see, there is no need to call mysqli_select_db() function at all, as the database name could be supplied already in mysqli_connect().
the proper error reporting mode is set, and therefore the actual error message will be reported, explaining why mysqli_connect() returned null, hence you'll be able to fix the error.
the proper charset must be always set
and the connection error should be handled properly. Some mysqli internals is not what you really want for the site visitors to see.
The detailed explanation of all these issues could be found in the article linked above.

You can establish your connection by a single line as follows.
<?php
$con = mysqli_connect("localhost", "root", "","account");
?>
Here, localhost=server address; root=user name; ""=password; account=your database name.
or
<?php
$con = mysqli_connect("localhost", "root", "","account");
?>
There is also another way like you tried:
<?php
$con = mysqli_connect("localhost", "root", ""); //connection
mysqli_select_db($con, "account"); //Mysqli_select_db() function expects exactly 2 parameters.
?>

You can add your db name into mysqli_connect("localhost", "root", "", "account"); as fourth element

Yuu can create mysqli connection as follows:
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

Related

php - mysqli - create database if does not exist [duplicate]

This question already has answers here:
Turning query errors to Exceptions in MySQLi [duplicate]
(3 answers)
Closed 1 year ago.
I am using PHP and mysqli and trying to create the DB if it does not exist in my dbLogin file. Seems like it should be a fairly simple thing to do. It seems to be getting hung up on the first creation attempt with an error and won't move past or catch the error.
Here is my very simple code:
<?php
$con = '';
try {
$con = new mysqli("host", "user", "pass", "db");
}
catch(Exception $e) {
echo "Error: $e<br />";
$con = new mysqli("host", "user", "pass");
$con->query("CREATE DATABASE IF NOT EXISTS db;");
}
/* check connection */
if ($con->connect_errno) {
printf("Connect failed: %s\n", $con->connect_error);
exit();
}
?>
Now, when I run the code above, all I get is the following error:
Warning: mysqli::__construct(): (HY000/1049): Unknown database
'db' in xyz\DBLogin.php on line 6 Connect
failed: Unknown database 'db'
Line 6 is the line inside the try block. It does not create the database and does not move past the error.
Your problem is that mysqli::__construct only generates a warning if it can't connect to the database, and you can't directly catch a warning. Now you can workaround that (for example, see this question) but it's probably simpler to do something like this:
$con = new mysqli("host", "user", "pass");
if ($con->connect_errno) {
printf("Connect failed: %s\n", $con->connect_error);
exit();
}
if (!$con->select_db('db')) {
echo "Couldn't select database: " . $con->error;
if (!$con->query("CREATE DATABASE IF NOT EXISTS db;")) {
echo "Couldn't create database: " . $con->error;
}
$con->select_db('db');
}
//check if the database exist - PHP
$cons = '';
$cons = new mysqli("host", "user", "pass");
$okk = mysqli_query($cons, "SHOW DATABASES LIKE 'db'");
$okkno = mysqli_num_rows($okk);
if($okkno <=0){
$fanya = mysqli_query($cons, "CREATE DATABASE IF NOT EXISTS db;");
echo "Database created successifully";
}

MySQL error message, mysql_connect(), any way to fix it?

So this is the error message:
PHP Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
This is the affected piece of code:
class wdClient {
var $dbLink; // The database link
var $prefix; // Table prefix
var $script; // The script running
/**
* Construct a new directory object.
*/
function wdClient() {
error_reporting(E_ALL ^ E_NOTICE);
$this->prefix = WDDBPREFIX;
// Connect to the database
$this->dbLink = mysql_connect(WDDBHOST, WDDBUSER, WDDBPASSWD);
// Select the database
mysql_select_db(WDDBNAME, $this->dbLink) or die('Sorry, The site is currently unavailable!');
}
where WDDBPREFIX, WDDBHOST, WDDBUSER, WDDBPASSWD, WDDBNAME are already defined in a config file.
I have tried simply using mysqli_connect instead of mysql_connect but it's not working.
Note: Never use MySQL, use this method!
//MySQLi information
$db_host = "localhost";
$db_username = "username";
$db_password = "password";
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die("Error " . mysqli_error());
//select MySQLi dabatase table
$db = mysqli_select_db($connection, "table") or die("Error " . mysqli_error());
Good luck!
well, as pointed in here http://php.net/manual/en/function.mysqli-connect.php , you should make something like this:
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
Apparently, in your case it will look like this:
$link = mysqli_connect(WDDBHOST, WDDBUSER, WDDBPASSWD, WDDBNAME);
And then you can continue with your code...
if (!link){
die('Sorry, The site is currently unavailable!');
} else{
// write your SQL here and fetch it
}

Can't induce error on $db_connect->select_db($name); ? PHP

I am a student.
I'm trying to deliberately induce an error in
$db_connect->select_db($db_name);
to check the error handling, but it won't give out an error?
The actual database name is 'cart', but i am using 'cartxx' to try and induce an error, but nothing happens, it runs as if there is no error. I don't have a database named 'cartxx'.
<?php
session_start();
$host = 'localhost'; // connects to the host server
$db_name = 'cartxx'; // name of the database we are connecting to
$db_username = 'root'; // username for database
$db_password = ''; // password for database
$db_connect = new mysqli($host, $db_username, $db_password); // connect to mysql
// If error
if (mysqli_connect_errno()) {
echo('Connection to database failed: ' . mysqli_connect_error());
exit();
}
// Select database
$db_connect->select_db($db_name);
// If error
if (mysqli_connect_errno()) {
echo 'Connection to database {$db_name} has failed: ' . mysqli_connect_error();
exit();
}
Thanks.
you need to pass default db name in connection string directly. if you need connect to one more database you can use select statment
$db_connect = new mysqli($host, $db_username, $db_password, $db_name);
for more :- http://php.net/manual/en/function.mysqli-connect.php
mysqli::selectdb will NOT return false if you give him an incorrect database name.
This function suits better a "i want to switch from database X to database Y" scenario, and will stay connected to database X if database Y is not found.
You can check the manual for this function.
A better way to select the database at connection is to use the mysqli constructor.

mysql_* to MySQLi

I recently learned that mysql_* has been depreciated and i have a quick question on how to rewrite something.
$db = mysql_connect("localhost","root","PASSWORD");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("FormData" ,$db);
I have tried rewriting it like this...
$mysqli = new mysqli("localhost", "root", "PASSWORD", "FormData", $db);
if(!$db) die("Error connecting to MySQL database.");
But when it posts my form i get the "Error connecting to MySQL database." error. I was able to fix it by just using this but i wanted to know how to add in the Error connecting.
$mysqli = new mysqli("localhost", "root", "PASSWORD", "FormData");
Any help would be great as i try to learn all of the new MySQLi stuff!
PHP website
Straight from php.net
<?php
$mysqli = new mysqli('localhost', 'fake_user', 'my_password', 'my_db');
// Works as of PHP 5.2.9 and 5.3.0.
if ($mysqli->connect_error) {
die('Connect Error: ' . $mysqli->connect_error);
}
?>
Edit:
The below will also allow you to do it your way.
$mysqli = mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');
Then you can:
if (!$mysqli) {
//handle the error
}
Consider PDO if possible. They are kind similar to me.
$mysqli = new mysqli("localhost", "root", "PASSWORD", "FormData", $db);
if(!$db) die("Error connecting to MySQL database.");
should be
$mysqli = new mysqli("localhost", "root", "PASSWORD", "FormData");
if($mysqli->connect_error) die("Error connecting to MySQL database.");
the parameters for mysqli() are:
[ string $host = ini_get("mysqli.default_host") [, string $username = ini_get("mysqli.default_user") [, string $passwd = ini_get("mysqli.default_pw") [, string $dbname = "" [, int $port = ini_get("mysqli.default_port") [, string $socket = ini_get("mysqli.default_socket") ]]]]]]
Not sure why you were trying to use the $db variable to set the port for the connection and then checking if the port variable is true...
For future reference the best place to look first, would be the docs
EDIT
As #Touch pointed out, you must check if error exists and not just that object exists. Edited code to reflect this.
Using mysqli:
define('DB_HOST', 'localhost');
define('DB_NAME', 'some_database_name');
define('DB_USER', 'some_user');
define('DB_PASS', 'some_password');
$Connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (!$Connection->connect_errno)
{
//do your prepared stuffs
}
else
{
die("Database Connection error:".$Connection->connect_error);
}
or using PDO
try
{
$PDOConnection = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.'', DB_USER, DB_PASS);
$PDOConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//do your prepared stuffs
$PDOConnection = null;
}
catch(PDOException $e)
{
die('ERROR: ' . $e->getMessage());
}
I wrote a class called better_mysqli that extends mysqli making it easier to use.
The following example shows the answer to your question and also shows basic usage of the better_mysqli class. You can view a detailed example with lots of comments here: detailed usage of better_mysqli
<?php
include_once('better_mysqli.php'); // can be obtained from: http://pastebin.com/ATyzLUfK
// THIS NEXT PART ANSWERS YOUR QUESTION
// THIS NEXT PART ANSWERS YOUR QUESTION
// THIS NEXT PART ANSWERS YOUR QUESTION
// THE ONLY DIFFERENCE IN THE CONNECTION WHEN USING better_mysqli AND mysqli
// is $mysqli = new better_mysqli(...) and $mysqli = new mysqli(...)
// == Instantiate the mysqli database object (aka open the database) ==
$mysqli = new better_mysqli('your_server', 'your_user', 'your_pass', 'your_db_name');
if (mysqli_connect_errno()) {
error_log(sprintf("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error()));
exit;
}
// == select example ==
unless( $sth = $mysqli->select('select * from table1 where col1=? and col2=?', $row, array('col1_placeholder_value', 'col2_placeholder_value'), $debug_level=0, $verbose_debug_output)){
if($debug_level>0){ echo $verbose_debug_output;}
// .. do your error handling here
}
while($sth->fetch()){
echo $row['col1'] .', '. $row['col2'] .', and '. $row['col_etc'] .' are accessed like that.<br>';
}
// == insert example ==
$statement = "insert into table1 (col1, col2, date_col, col_etc) values (?, ?, NOW(), ?)";
unless( $mysqli->insert($statement, array('col1_insert_value', 'col2_insert_value', 'col_etc_value'), $debug_level=0, $verbose_debug_output, $id_of_new_record) ){
if($debug_level>0){ echo $verbose_debug_output;}
// .. do your error handling here
}
// == update example ==
unless($mysqli->update("update table1 set col1=? where col2=?", array('col1_value', 'col2_value'), $debug_level=0, $verbose_debug_output) ){
if($debug_level>0){ echo $verbose_debug_output;}
// .. do your error handling here
}
// == delete example ==
unless( $mysqli->delete("delete from table1 where col1=? where col2=?", array('col1_value', 'col2_value'), $debug_level=0, $verbose_debug_output) ){
if($debug_level>0){ echo $verbose_debug_output;}
// .. do your error handling here
}
// in all cases statements are prepared just once and cached so if you reuse any statement the already prepared statement handle is automatically used
?>

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