11

I come across this:-

PHP Error handling: die() Vs trigger_error() Vs throw Exception

and understood that throw exception is better

How can i replace die and use throw exception here in this code:-

<?php
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_db = "localhost";
$database_db = "database";
$username_db = "root";
$password_db = "password";
$db = mysqli_connect($hostname_db, $username_db, $password_db) or die("Unable to connect with Database"); 
?>
1
  • Was asking myself the same thing. Thanks for posting this question :) Commented Sep 29, 2012 at 4:54

2 Answers 2

16
try
{
    if ($db = mysqli_connect($hostname_db, $username_db, $password_db))
    {
        //do something
    }
    else
    {
        throw new Exception('Unable to connect');
    }
}
catch(Exception $e)
{
    echo $e->getMessage();
}
Sign up to request clarification or add additional context in comments.

8 Comments

i need to replace die("Unable to connect with Database"); with your code? Also can you tell me what is @$_POST['variable']
You should replace your last line with this. @ - is enabling silent mode, no error will be echoed but still logged in your server's error.log file. I guess you know what $_POST['variable'] is.
one more thing, as i have added the code in an include_db file for database connection... so what i should put in the area //do something because it just need to do connect or show the error...
You can leave that empty, if there's no error the execution will continue with code what is after the try...catch block.
see this file is my database connection file, which i include on every page of my website.... these codes are just to connect with the database other things i do on their respective pages.
|
3

It is documented here https://www.php.net/manual/en/mysqli.error.php

if (mysqli_connect_errno()) {
    throw new RuntimeException("Connect failed: %s\n", mysqli_connect_error());
}

1 Comment

ok $db = mysqli_connect($hostname_db, $username_db, $password_db) or die("Unable to connect with Database"); I have to replace with this $db = mysqli_connect($hostname_db, $username_db, $password_db); if (mysqli_connect_errno()) { throw new RuntimeException("Connect failed: %s\n", mysqli_connect_error()); }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.