Php mysql create database if not exists - php

I want to create a database. Why is not the db created with this code?
$dbname = 'regulations_db';
$con = mysql_connect("localhost","root","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_num_rows(mysql_query("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '". $dbname ."'"))) {
echo "Database $dbname already exists.";
}
else {
mysql_query("CREATE DATABASE '". $dbname ."'",$con);
echo "Database $dbname created.";
}
This is working, but I think the first one is the best practice:
if (mysql_query("CREATE DATABASE IF NOT EXISTS regulations_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}

Just do a simple mysql_select_db() and if the result is false then proceed with the creation.
As an example, check out the first answer here by another very smart StackOverflower.
<?php
// Connect to MySQL
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Make my_db the current database
$db_selected = mysql_select_db('my_db', $link);
if (!$db_selected) {
// If we couldn't, then it either doesn't exist, or we can't see it.
$sql = 'CREATE DATABASE my_db';
if (mysql_query($sql, $link)) {
echo "Database my_db created successfully\n";
} else {
echo 'Error creating database: ' . mysql_error() . "\n";
}
}
mysql_close($link);
?>

Three steps to fix this:
Don’t specify the database name when connecting.
Your SQL statement should be CREATE DATABASE IF NOT EXISTS php1.
Call mysqli_select_db($link, 'php1') to make that the default database for your connection.

If you're using MySQLi Object-oriented method, you can use following code, this code is similar to previous answer and only the method is different, I just put this because if anyone using MySQLi Object-oriented method, you can use this code directly.
$servername = "localhost";
$username = "mysql_user";
$password = "user_password";
$dbName = "databaseName";
// Connect to MySQL
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// If database is not exist create one
if (!mysqli_select_db($conn,$dbName)){
$sql = "CREATE DATABASE ".$dbName;
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
}else {
echo "Error creating database: " . $conn->error;
}
}
Furthermore you can refer W3school site here.
Good Luck! :D

Related

PHP Mysqli_query returns successful, but no insert into my table

I have tried debugging and cannot seem to get to the bottom of this problem. My query returns successful, however nothing is inserted into my table within my database. I am working on a CRUD application to enter holdings of cryptocurrency, and this is simply the Create button. My function gets to the very end of the if statement, and Mysqli_query returns a 1. Could this be issues with permissions in PHPAdmin? Or possibly something to do with Ports?
The code below:
$con = createDB();
if (isset($_POST['create'])){
createData();
}
function createData(){
$username = textboxValue('Username');
$BTC = textboxValue('BTC');
$ETH = textboxValue('ETH');/*$ETH =(isset($_POST['ETH']) ? $_POST['ETH'] : '');*/
$DASH = textboxValue('DASH');
if($username && $BTC && $ETH && $DASH){
$sql = "INSERT INTO cryptoholdings(username,BTC_holdings,ETH_holdings,DASH_holdings)
VALUES('$username','$BTC','$ETH','$DASH')";
if($GLOBALS['con']->query($sql) ){ /*(mysqli_query($GLOBALS['con'],$sql))*/
$GLOBALS['con']->commit();
echo "Record Successfully inserted...!";
}
else{
echo "Error Recording Data <br>" . mysqli_error($GLOBALS['con']);
}
}
else{echo "Provide all data in textboxes.";
}
}
function createDB(){
$servername='localhost';
$username='root';
$password='password';
$dbname='holdings';
//create connection to our database "holdings"
$con=mysqli_connect($servername,$username,$password,$dbname);
if(!$con){
die("Connection Failed: ". mysqli_connect_error());
}
//create Database
$sql= 'CREATE DATABASE IF NOT EXISTS $dbname';
if(mysqli_query($con,$sql)){
$con = mysqli_connect($servername,$username,$password,$dbname);
$sql= 'CREATE TABLE IF NOT EXISTS cryptoholdings(
username VARCHAR(25) NOT NULL,
BTC_holdings FLOAT(11) NOT NULL,
ETH_holdings FLOAT(11) NOT NULL,
DASH_holdings FLOAT(11) NOT NULL)';
if(mysqli_query($con,$sql)){
return $con;}
else{
echo "Error when Creating Table...";
}
}
else{
echo "Error while creating Database...". mysqli_error($con);
}
}
function textboxValue($value){
$textbox = mysqli_real_escape_string($GLOBALS['con'],trim($_POST[$value]));
if(empty($textbox)){
return false;
}
else{
return $textbox;
}
}
First check that the connection was very okay by echoing something from the db or by doing sth on the db. 2nd try using another method other than the global con being used. For the purpose of testing and finding solution, I recommend you create a simpler table (of one or 2 fields) and try inserting into the fields. I recommend this method of connection below.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

Connect MYSQL using php and creating Database if not exist

Im trying to learn php with best methods and practice but im not able to get proper output as per the code as there is no error!
is it a good method to create the database if not exist because im not getting output echo "Database $dbname created successfully\n";
<?php
$user = "root";
$pwd = "";
$server = "localhost";
$dbname = "xyz";
//Connecting to MYSQL
$db_conn = mysqli_connect($server,$user,$pwd);
if (!$db_conn) {
die("Connection Error".mysqli_error());
}
echo "Connected Successfully";
$db_select = mysqli_select_db($db_conn,$dbname);
if (!$db_select) {
// If we couldn't, then it either doesn't exist, or we can't see it.
//Create Database Query
$db_create = "CREATE DATABASE $dbname";
$db_selected = mysqli_query($db_conn,$db_create);
if ($db_selected) {
echo "Database $dbname created successfully\n";
mysqli_select_db($db_conn,$dbname);
} else {
echo 'Error creating database: ' . mysql_error() . "\n";
}
}
?>
i got a solution out of it !
please check weather its a good method and best practice to add database !
$db_conn = mysqli_connect($server,$user,$pwd);
if (!$db_conn) {
die("Connection Error".mysqli_error());
}
echo "Connected Successfully";
$db_select = mysqli_select_db($db_conn,$dbname);
if (!$db_select) {
// If we couldn't, then it either doesn't exist, or we can't see it.
//Create Database Query
$db_create = "CREATE DATABASE IF NOT EXISTS $dbname";
$db_selected = mysqli_query($db_conn,$db_create);
if ($db_selected) {
echo "Database $dbname created successfully\n";
} else {
echo 'Error creating database: ' . mysqli_error() . "\n";
}
}
else{
echo "Database $dbname is connected";
}

i just want to connect mysql database from other server

example : mydatabase is on google.com/phpmyadmin
and i want to insert data from yahoo.com/insertdata.php
both domains are not on same server both domains are on different servers
so how to connect database
<?php
$server = "38.89.136.77";
$database = "dbname";
$username = "dbusers";
$password = "password";
$mysqlConnection = mysqli_connect($server, $username, $password);
if (!$mysqlConnection)
{
echo "Please try later.";
}
else
{
mysqli_select_db($database, $mysqlConnection);
echo " database is connected";
}
?>
this code is not working how can i do it get error Please try later.
Do it like this. Then you get all errors displayed.
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
?>
Then post your error here in the comments, so I can help you.

No Database Selected - Error

I work with the following example-code:
<?php
// Create connection
$conn = mysqli_connect('mysql3.00*****', 'a7552070******', 'fjewifn****');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO diequizapp(appid, itemid, data) VALUES ('John', 'bon', 'jovi')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
but I get an No Database selected back.
Can somebody please tell my why ?
I took this example from a tutorial.
Auf Wiedersehen, Andre
You need to pass the database that you want to select data from as the last parameter in mysqli_connect(host, username, password, database)
You can also take the second approach and use the mysqli_select_db($connection, DATABASE) function
you did not given the database name try like this
$dbname = "****"; //database name
$dbhost = "localhost"; // host name localhost
$dbusername = "***"; // username of the mysql
$dbpassword = "***"; // password of the mysql
$link = mysqli_connect($dbhost,$dbusername,$dbpassword,$dbname);
if (mysqli_connect_errno($link))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
then run your query........

checking if a database exists

The code below works fine except it throws a warning when connecting to a database that does not exist. This works fine in product where errors are off, but I would rather not have errors if I don't need to.
function cpanel_db_connect($dbname) {
// normalize
$dbname = convert_to_slug($dbname);
$dbname = CPANEL_USER . '_' . $dbname;
$dbuser = CPANEL_USER . '_' . CPANEL_DB_USER;
// connnect database
$mysqli = new mysqli(CPANEL_DB_HOST, $dbuser, CPANEL_DB_PASS, $dbname);
if ($mysqli->connect_error) {
return false;
}
return $mysqli;
}
It's not a good practice to suppress warnings/errors using the # sign in PHP. You could accidentally suppress an invalid username or password message and you would never know it.
A more appropriate way of checking if the database exists is creating a new instance of Mysql or Mysqli (without specifying the default database) and executing the following query (similar to Marc B's comment):
SELECT COUNT(*) AS `exists` FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMATA.SCHEMA_NAME='my_database_name'
Then you can check the value of the key exists to see if the database is there or not.
Here's a sample code:
// statement to execute
$sql = 'SELECT COUNT(*) AS `exists` FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMATA.SCHEMA_NAME="my_database_name"';
// execute the statement
$query = $mysqli->query($sql);
// extract the value
$row = $query->fetch_object();
$dbExists = (bool) $row->exists;
It is a bit longer but it's safer.
$mysqli = #new mysqli(CPANEL_DB_HOST, $dbuser, CPANEL_DB_PASS, $dbname);
The above works!
This works, just replace $dbname in this code:
if (empty (mysql_fetch_array(mysql_query("SHOW DATABASES LIKE '$dbname' ")))){
echo "DB does Not exist"; }else{ echo "DB exists!";}
Updating to MYSQLI:
$conn = new mysqli('localhost', 'root', '');
$dbname='test';
if (empty (mysqli_fetch_array(mysqli_query($conn,"SHOW DATABASES LIKE '$dbname'"))))
{
echo "DB not exist<br>";
}
else
{
echo "DB exist<br>";
}
Here's how to connect to DB server without selecting a DB, and only connecting if DB exists:
$mysqli = new mysqli($db_biz['server'], $db_biz['user'], $db_biz['password']);
$query = 'SHOW DATABASES LIKE "' . $db_biz['dbName'] . '"';
$resShowBizDB = $mysqli->query($query);
if ($resShowBizDB->num_rows == 1) { //Found database
$mysqli->select_db($db_biz['dbName']);
if ($mysqli->connect_errno) { //Check for errors
var_dump($mysqli);
echo "Failed to connect to biz database: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$mysqli->set_charset('utf8');
} else { //Didn't find DB
die('<h1>ERROR</h1><p>Found no database</p>');
}

Categories