Correct way to use die()?

Discussion in 'PHP' started by Tony Brar, Jul 18, 2012.

  1. #1
    Is this the correct way to use die()?

    $con = mysql_connect("localhost","tonybrar","***********") or die('Error: ' . mysql_error());
    PHP:
    Thanks in advance,

    Tony
     
    Solved! View solution.
    Tony Brar, Jul 18, 2012 IP
  2. #2
    If you are looking for a connection script that has die() in it you seem to have it right. The way I do it is a bit longer but it does the same thing:

    
     <?php 
    $link = mysql_connect('localhost', 'DBUSER', 'DBPASS '); 
    if (!$link) { 
        die('Could not connect: ' . mysql_error()); 
    } 
    mysql_select_db('DB'); 
    ?> 
    
    PHP:
    If you are looking to use die() to confirm a query you could use something like this function

    
    function confirm_query($result_set){
    	if(!$result_set){
    		die("Database query failed: ".mysql_error());	
    	}
    }
    
    
    $query = mysql_query("SOME QUERY HERE");
    confirm_query($query);
    
    PHP:
     
    j_o, Jul 18, 2012 IP
  3. Microsuck

    Microsuck Greenhorn

    Messages:
    49
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    8
    #3
    Yes, that is correct.
     
    Microsuck, Jul 18, 2012 IP
  4. Tony Brar

    Tony Brar Active Member

    Messages:
    220
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    75
    #4
    Thanks, j_o told me what I wanted and more. Best answer given!
     
    Tony Brar, Jul 20, 2012 IP
  5. BRUm

    BRUm Well-Known Member

    Messages:
    3,086
    Likes Received:
    61
    Best Answers:
    1
    Trophy Points:
    100
    #5
    As some advice you should not use mysql_* any more as it is deprecated. Use PDO or mysqli_* to interact with databases.

    An example to get you started:

    
    $db = new PDO("mysql:dbname=databasename;host=127.0.0.1", "username", "password");
    $q = $db->prepare("SELECT * FROM table WHERE condition = 'predicate'");
    $q->execute();
    $row = $q->fetch(PDO::FETCH_ASSOC);
    
    Code (markup):
     
    BRUm, Jul 21, 2012 IP