MuriloRM
MuriloRM

Reputation: 79

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.

Upvotes: 1

Views: 378

Answers (2)

Elymentree
Elymentree

Reputation: 853

function conexao() { 
$db = 'webservice'; 
$user = 'xxxxx';
$pass = 'xxxxx';
$host = 'localhost';

$conn = mysql_connect($host,$user,$pass);
if(!$conn){ 
$retval = 'Could not Connect' . mysql_error(); 
}
else if(!mysql_select_db($db)){ 
$retval = 'Could not select db' . mysql_error(); 
}
else{ 
$retval = 'Success'; 
}

return $retval;
} // end of function 

Now on your function call process the returns accordingly. *** mysql is deprecated use mysqli or PDO instead.

}

Upvotes: 1

Jonathan Nielsen
Jonathan Nielsen

Reputation: 1492

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.

Upvotes: 2

Related Questions