Jump to content

Assign variables to connect to mySQL?


spode

Recommended Posts

Hey guys, first just wanted to say, great site and I'm already learning a ton. However, in the book I bought (PHP for the WWW by Larry Ullman) it looks like he assigns the connection as a variable. Let me explain by example.

 

<?php
$host = "localhost";
$username = "imcool";
$password = "123456";
$database = "acoolone";

if ($dbc = mysql_connect ($host, $username, $password))
	{
	echo "Connected";
	if (!mysql_select_db ($database))
		{
		die ('<p>Could not select the database because: <b>' . mysql_error() . '</b></p>');
		}
	}
	else
	{
	die ('<p>Could not connect to MySQL because: <b>' . mysql_error() . '</b></p>');
	}
?>

 

To me (as a n00bie) it looks like he's assigning the variable $dbc inside the if statement arguments. Am I right? If so is it neccessary?

 

However, I notice in many scripts you guys do it like so:

 

<?php
   
   $host = 'localhost';      
   $user = 'username';
   $password = 'password';
   $dbName = 'databasename';

   $conn = mysql_connect($host, $user, $password) or die(mysql_error());
   $db = mysql_select_db($dbName, $conn) or die(mysql_error()); 

 

Could someone explain the difference, and what is going on?

 

Thanks for the help!

Link to comment
https://forums.phpfreaks.com/topic/52403-assign-variables-to-connect-to-mysql/
Share on other sites

The first example gives you more opportunity to customize your error output rather than just calling die() and showing the default mysql_error().

 

But why are you using things like $dbc = .....I still don't understand why it's being assigned as a variable

 

mysql_connect returns a connection resource which can later optionally be passed to mysql_query. Assigning your connection resource to a variable isn't really required, though it can come in handy when dealing with multiple databases.

if ($dbc = mysql_connect ($host, $username, $password))

 

is equivalent to

$dbc = mysql_connect ($host, $username, $password);
if ($dbc)

 

As you observed, the assigment is done in the if(). The value of an assignment is the value assigned to the left-hand variable.

 

The alternative method relies on evaluation using an "or" condition. Consider

 

if (a or b)

 

if a is true, there is no need to evaluate b as the condition is already satisfied. So with

 

$conn = mysql_connect($host, $user, $password) or die(mysql_error());

 

if connection ok it's value is assigned to $conn

if the connect fails and returns false then the "die()" is evaluated.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.