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";
}
Related
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 3 years ago.
I am able to connect to my database, as it says Connection Successful when I go to the page. The problem is that I'm still not able to run a query against my database and have the results display.
I've tried following the instructions that were given to me in my class and kept getting HTTP 500 Error. So, I started to search the internet and have my config file set up differently than what my instructor said and was able to get it to say that the connection is successful.
Here is the main file:
<?php
$configd = include('config2.php');
$conn = mysqli_connect($configd['dbhost'], $configd['dbuser'], $configd['dbpass'], $configd['dbname']);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql = "SELECT Last_Name, First_Name FROM sample";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Last Name: " . $row["Last_Name"]. "<br>";
echo "First Name: " . $row["First_Name"]. "<br><hr>"
}
} else {
echo "0 results";
}
$conn->close();
?>
Here is the config file:
<?php
return array(
dbhost => 'localhost',
dbuser => 'cdefauw',
dbpass => 'sherbert00',
dbname => 'sample',
);
?>
When this is run, it's supposed to show a query of all of the first and last names that are within the sample database I made on phpmyadmin. When I run it right now, all I get is HTTP Error 500. If I remove the if ($result->num_rows >0) statement, then it says connection successful.
check like this
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
or
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 4 years ago.
$serverName = 'servername';
$uid = 'username';
$pwd = 'password';
$conn = new mysqli($serverName, $uid, $pwd );
if (!$conn) {
echo "Connection failed: " ;
}
else
{
echo "Connected successfully";
}
This is my code. It gets connected to the database. I just want to confirm the code is right, because when i try doing this
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
it throws me connection failed error.
So, is my code connected to the server or not? because when i run a query it does not show me anything.
Code for the query:
$sql = "SELECT max([line_nbr]) FROM [dbo].[so_audit]";
$res = $conn->query($sql);
var_dump($res);
please advise
you are not trying to connect to sql server u should use sqlsrv_connect instead of mysqli
so u need to specify the server name and an array containin connection info for that your code should look like this :
$srv ="servername"
$info=array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $srv, $info);
if (!$conn) {
echo "Connection failed: " ;
}
else
{
echo "Connected successfully";
}
I have a need to copy some rows from a database to a different database. I am experiencing difficulty. I have found several methods except none of the seem to work. The php version I am using is 5.4.
Both connections are in the same server, however everything else is different
This is the php code that I have found and it doesnt seem to work at all, I am unable to select from the first database
// Create connection
$wpdb = mysql_connect($servername, $username, $password);
// Check connection
if ($wpdb->connect_error) {
die("Connection failed: " . $wpdb->connect_error);
}
echo "Connected local successfully\n";
//$starttime = date("h:i:sa");
$mydb = mysql_connect('localhost','dbname','dbpassword', true);
// Check connection
if ($mydb->connect_error) {
die("Connection failed: " . $mydb->connect_error);
}
echo "Connected to Integrity successfully\n";
mysql_select_db($database, $wpdb);
mysql_select_db('wordpress_0', $mydb);
you can try with PDO.that provide a common interface to talk with many different databases.
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user',
'password');
I refuse to offer support for mysql_ syntax, so I'll offer the upgraded version.
Almost entirely copied from the php manual... http://php.net/manual/en/mysqli.select-db.php
Code:
/* attempt and check connection including first database selection "test" */
if (!$mysqli = new mysqli("localhost", "root", "", "test")) {
// never show the actual error to the public
echo "<div>Database Connection Error: " , $conn->connect_error , "</div>";
exit();
}
/* return name of current default database */
if (!$result = $mysqli->query("SELECT DATABASE()")) {
// never show the actual error to the public
echo "<div>Syntax Error: " , $conn->error , "</div>";
} else {
echo "<div>Default database is: " , $result->fetch_row()[0] , "</div>";
$result->close();
}
/* change db to "mysql" db */
$mysqli->select_db("mysql");
/* return name of current default database */
if (!$result = $mysqli->query("SELECT DATABASE()")) {
// never show the actual error to the public
echo "<div>Syntax Error: " , $conn->error , "</div>";
} else {
echo "<div>Default database is: " , $result->fetch_row()[0] , "</div>";
$result->close();
}
$mysqli->close();
Output:
Default database is: test
Default database is: mysql
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();
}
I was running an example from a mysqli tutorial.
$mysqli = new mysqli("localhost", "user", "password", "database");
if($mysqli->connect_errno)
{
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ) "
. $mysqli->connect_error;} echo $mysqli->host_info . "\n";
}
I was getting the error:
Warning: mysqli::mysqli(): (42000/1049): Unknown database 'world' in /home/...
What should I do to create the database?
You have to use this:
$mysqli=new mysqli("localhost","user","password") or die(".........");
if($mysqli->query("Create database if not exists MyDB")){
"Failed creating new database: ".$mysqli->connect_errno();
die();
}
$mysqli->select_db("MyDB");
$mysqli->close();
try something like this
$mysqli = new mysqli("localhost", "user", "password");
in this way you are connected to database
and put this query using mysqli Create Database database1