Error creating a MySQL database via PHP in WampServer

4

I have a problem when creating the database, on the net I found little content about, only meeting how to mount database by phpMyAdmin, but it is via script that I want to create. >

I have the following code:

<?php

$mysqli = new mysqli("localhost","root","");

if($mysqli-> connect_error){
    echo "Não foi possível conectar.";
}

$create_db = "CREATE DATABASE 'my_db'";

if($mysqli->query($create_db)){
    echo "conexão bem sucedida";
}
else{
    echo "falha na conexão";
}

?>

The WampServer does not point to syntax errors. I always have a "connection failure" answer, what's wrong?

    
asked by anonymous 28.09.2014 / 14:52

3 answers

9

Well, beating the eye saw some problems in your query.

  • You do not need to put the bank name in single quotation marks.
  • If the database already exists, it will return an error as expected. You must give DROP otherwise you will not be able to create it (do not do this in production) or add IF NOT EXISTS to your query to avoid an error if the database is already created. >

    I changed your code by putting full error messages at the time of running the script.

    <?php
    
    // MySQLi usando try catch
    mysqli_report(MYSQLI_REPORT_STRICT); 
    
    try 
    {
        $mysqli = new mysqli("localhost","root","");
    
        $mysqli->query("CREATE DATABASE IF NOT EXISTS my_db;");
    
        echo "Database criada com sucesso!";
    } 
    catch (Exception $e) 
    {
        echo "Alguma coisa de errada aconteceu. Detalhes: " . $e->message;
    }
    
        
  • 28.09.2014 / 15:20
    8

    I created this and it worked. If you do the same and it does not work, you have a problem with your MySQL installation or configuration. Just look at the error provided by MySQL to be sure. But, possibly, this is not the case. It's possible to be just a syntax problem, I did not use the apostrophe in the name in the database.

    <?php
    
    $mysqli = new mysqli("localhost","root","uma_senha_aqui");
    
    if($mysqli-> connect_error){
        echo "Não foi possível conectar.";
    }
    
    $create_db = "CREATE DATABASE IF NOT EXISTS my_db";
    
    if($mysqli->query($create_db)){
        echo "criação ok";
    }
    else{
        echo "falha na criação:" . $mysqli->error;
    }
    
    ?>
    

    I placed it on GitHub for future reference .

    I printed the $mysqli->error to have information to work with. When you just write that it failed, you do not know why it failed and it's harder to solve a problem.

        
    28.09.2014 / 15:13
    -1

    Just take the simple quotation marks that will work normally, your code is bandaged, except for those quotes.

        
    16.12.2018 / 12:45