phpmysqlmysql-connect

Establish connection to a database


I've installed a LAMP server in a Oracle VM VirtualBox using Ubuntu 14.0 desktop recently so I could learn about PHP interactions with MySQL databases.

I cannot establish a connection with my database. It doesn't give any error messages even if I use a wrong username. I know I've set up LAMP correctly because I've run other PHP files on localhost.

This is my script:

<?php 
function conexao() {
$db = 'webservice';
$user = 'xxxxx';
$pass = 'xxxxx';
$host = 'localhost';
$conn = mysql_connect($host,$user,$pass);
mysql_select_db($db);   
}
conexao();
?>

I'm supposed to get a message when my connection info are wrong, right? Well, nothing happens, just like when every info is okay.


Solution

  • you could try this script that i am using to connect to my db

    <?php
    define("HOST", "localhost"); // The host you want to connect to.
    define("USER", "username"); // The database username.
    define("PASSWORD", "password"); // The database password. 
    define("DATABASE", "webservice"); // The database name.
    
    date_default_timezone_set('Europe/Stockholm');
    
    $con = mysqli_connect(HOST, USER, PASSWORD, DATABASE);
    
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error() . "\n";
    }
    mysqli_set_charset($con, "utf8");
    ?>
    

    If this doesn't work it's probably an error with the request where you're calling the script.