PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, March 16, 2022

[FIXED] Create DB if not exists using mysqli + php

 March 16, 2022     database, mysqli, php     No comments   

Issue

I am trying to create a database using mysqli if the database name doesn't exist using the following code:

<?php

$link = mysqli_connect("localhost", "root", "", "php1") ; 
if(mysqli_connect_errno()){
    echo mysqli_connect_error();
    $query = "CREATE DATABASE php1";
    if(mysqli_query($link, $query)){
        echo "Success";
    } else {
        echo "Failure";
    }
}


?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>        
        <a href="signup.php"><button type="button">Sign Up!</button></a>
        <a href="login.php"><button type="button">Log In</button></a>
    </body>
</html>

The code checks the db & it doesn't exists. Next I want to create the database if it does not exist but I am getting the following error always:

Warning: mysqli_connect(): (HY000/1049): Unknown database 'php1' in E:\xampp\htdocs\PhpProject1\index.php on line 3

Unknown database 'php1'

Warning: mysqli_query() expects parameter 1 to be mysqli, boolean given in E:\xampp\htdocs\PhpProject1\index.php on line 7

Failure

This way I can't get the new DB created. Does anybody has any idea how to correct this?


Solution

Three steps to fix this:

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


Answered By - Nate
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing