views:

19

answers:

3

Hello, I am new to php syntax and am looking for advice on creating the most acceptable or correct code. I focus on front end design, but I like to make sure my code is proper. I am in a digital media program, my instructor has given us this code for connecting to our MYSQL databases.

<?php
mysql_connect("localhost", "root", "root")or die("Cannot Connect to DB");
mysql_select_db("Example")or die("cannot select the DB Example ");
?>

However when I look at connect scripts online they set the mysql_connect function as a variable lets say $connect and run an if statement stating; if not $connect produce error, and the same for mysql_select_db. They also close the script with mysql_close($connect); like below

<?php
$connect = mysql_connect("localhost", "root", "root");
if (!$connect)
  {
  die('Could not connect: ' . mysql_error());
  }

$db_selected = mysql_select_db("Example", $connect);

if (!$db_selected)
  {
  die ("Can\'t use test_db : " . mysql_error());
  }

mysql_close($connect);
?> 

Is either one better? What problems can I have if I dont close the connect with mysql_close?

A: 

Is this for Homework?

EDIT: Go and accept some of your questions. 47% accept rate is to low. So not lot would help you.

streetparade
no we've been using his connect script for a while, but I have posted his code online before and its got torn apart. I just should read a book myself.
Anders Kitson
@streetparade: this should be a comment, not an answer.
Max Shawabkeh
@Max or Community wiki? :-)
streetparade
Anyway i would look at the php manual.
streetparade
Ok I didn't know that's what acceptance rate meant. I had tried to answer this question myself before I posted it. I went through the php manual, but it only ever gives me options nothing straightforward. Like you should do this because.
Anders Kitson
+1  A: 

The other mysql_*() functions will use the connection created by the latest call to mysql_connect() or mysql_pconnect(). If for some reason you want more than one connection, trusting the implicit connection object in this manner will fail. Better is to store the connection object yourself and passing it in wherever you need it.

Ignacio Vazquez-Abrams
+1  A: 
  1. Regarding using an if instead of an or, it doesn't matter. The or short-circuits, so if the connection worked, die(...) won't be executed. Using either is a matter of preference. If you want to use the or version while keeping the result of the mysql_connect() call, simply assign the whole expression to a variable:

    $connection = mysql_connect(...) or die('Connection failed.');
    
  2. mysql_close() should be used after you're done with all your database communication.

Max Shawabkeh
Thanks Max, what resource would you recommend for php development, other than the php manual? If you do at all.
Anders Kitson