简体   繁体   中英

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.

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.

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.

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM