Die and Exit Functions in PHP Programming Languages. This tutorial is for Die & Exit Functions. They are very useful functions that you should get to use into your program so you can cover the script at any point where you made fatal error and which you don’t want to execute . Let see how it works:-
Code for die function (Screenshot1):-
Screenshot1 |
<?php echo 'Hello'; die(); echo ' World'; ?>
Output Screenshot2
Screenshot2 |
In this example I had echo out “Hello” and “World”. But in output its just echoing out me “Hello” because of using Die Function. I have kill the code after die()
keyword with brackets,when you write the function from that point it will kill rest of the page.
Code for exit function(Screenshot3):-
Screenshot3 |
<?php echo 'Hello'; exit(); echo ' World'; ?>
Output (Screenshot4):-
Screenshot4 |
In this example doing same thing using exit() with brackets.
Code for die or exit function(Screenshot5):-
Screenshot5 |
<?php echo 'Hello'; die('ERROR. PAGE HAS ENDED.'); echo ' World'; ?>
Output (Screenshot6):-
Screenshot6 |
In this example you can also echo out string or error in die functions keyword. Similarly you can do it with exit function as well.
Die and Exit functions are used in database connections. Let see it in example for connecting it with mysql database where ” mysql_connect(); ” function is used.
Code for Connect Mysql database (Screenshot7)
Screenshot7 |
<?php mysql_connect('localhost','root','') or die ('Could not connect to database.''); echo 'connected!'; ?>
output (Screenshot8):-
Screenshot8 |
In this example I have connected mysql database with my localhost of xampp. Now you don’t worry about connections of database which we will see it later on. Here we use function name ” mysql_connect(‘localhost’,'username’,'password’) ” where it depends on server my server which is localhost ,my username is root and my password is blank. Now in this example I have used die function if any of my variables like username, server , or password mismatch or database is not connected successfully it will show me error “Could not connect to database”.But here it is connected.
Code for connect mysql database with die or exit functions (Screenshot9):-
Screenshot9 |
<?php mysql_connect('localhost','alex','') or die ('Could not connect to database.''); echo 'connected!'; ?>
Output Screenshot10
Screenshot10 |
Code for connect mysql database with die or exit functions (Screenshot11):-
Screenshot11 |
<?php @mysql_connect('localhost','alex','') or die ('Could not connect to database.''); echo 'connected!'; ?>
output (Screenshot12):-
Screenshot12 |
In this example we just output our own error for that we just popin @ before function. So, This is user-friendly way to connecting to database or the killing page. In this we can also use exit function instead of die function. It will exactly to the same thing which we done with die functions.
No comments:
Post a Comment
Thanks For Comment Will get you Soon..