Pergunta

I'm trying to learn this stuff. Please be gentle.

Something is wrong here:

$dbhost = "localhost";
$dbname = "something_dbname"; 
$dbuser = "something_user";
$dbpass = "pwpwpwpw";
$dberror1 = "Could not connect to the database!";
$dbconnected = "you are connected!";

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ($dberror1);
$select_db = mysql_select_db($dbname . $dbconnected) or die ($dberror1);

where is my mistake? I want $dbconnected to show... I can just as easily use

echo "hello";

it shows that I connect but I'm trying to get familiar with using multiple variables.

would this be better?

$dbhost = "localhost";
$dbname = "something_dbname"; 
$dbuser = "something_user";
$dbpass = "pwpwpwpw";
$dberror1 = "Could not connect to the database!";
$dbconnected = "you are connected!";

if ($mysqli = new mysqli($dbhost, $dbuser, $dbpassword, $dbname))
echo $dbconnected;
else die($dberror1);
Foi útil?

Solução

Right now you are trying to connect to a database called something_dbnameyou are connected. The . concatenates variables into one string.

To fix your immediate problem, try this:

First, define $dbhost - I don't see it in your code.

Then change the last line to this:

$select_db = mysql_select_db($dbname) or die ($dberror1);

Then, just echo $dbconnected;

If you are not connected, the page will have called die, and will never reach the line that echos $dbconnected. If you are connected, the program will proceed to this next line and echo your success message.

Or you can do it more explicitly like this:

if ($select_db = mysql_select_db($dbname))
    echo $dbconnected;
else die($dberror1); 

To fix the bigger problem, DON'T use mysql_*. Read this for more information.

mysqli or pdo are far better options, and you can accomplish the same task easier, for instance, connecting to a db with mysqli is just:

$mysqli = new mysqli($dbhost, $dbuser, $dbpassword, $dbname);

Or you can do it procedural style, which is closer to your current code. The following snippet is from the php manual, on the page I linked in the comment below.

$link = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname);

if (!$link) {
    die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
}

echo 'Success... ' . mysqli_get_host_info($link) . "\n";

mysqli_close($link);

Outras dicas

I'd strongly recommend using PDO. The connection string is similar and can be done using:

// I do not see $dbhost defined in your code. Make sure you have it defined first
try {
    $conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo $dbconnected; // will print out the connection success message
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

To answer your question about not using mysql_* functions, you can check out this

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top