PHP mysqli database connection
This article will help you connect mysql database with PHP using mysqli function, MySqli is Improved version of mysql function previously provided by PHP which is deprecated in new versions of PHP.
Lets start with database connection
we need 4 things to connect to database
- Host : which system/computer has datbase
- User : what is username to connect to database
- Password : what is password to connect to database
- Database : what is the name of database we are going to connect
1 2 3 4 5 6 7 8 9 10 |
$db_host = "localhost"; $db_user = "root"; $db_pwd = ""; $db_name = "coding-sips"; $db= new mysqli($db_host,$db_user,$db_pwd,$db_name); if($db->connect_error) { echo "ERROR: (".$db->connect_errno.") ".$db->connect_error; exit(); } |
Line#5 makes connection to database using provided credentials, if connected then then “if” block will not be executed, while it got some error then error no and error message will be displayed and further execution will be stopped with “exit()” function.
Now fetch some data from database.
let say we have jobs table and we want to get all jobs with status=1 and last_date is > current date
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
$q="select * from jobs where status=1 and last_date >= CURDATE() order by id desc"; $res=$db->query($q); if($res) { if($res->num_rows>0)//1 or more records returned { while($row=$res->fetch_array()) { echo "<h2><a href='job-detail.php?id=".$row['id']."'>".$row['title']."</a></h2>"; echo "<footer>Last date: ".date("d-M-Y",strtotime($row['last_date']))."</footer>"; echo "<p>".substr($row['detail'],0,300)."</p>"; echo "<a href='apply.php?jid=".$row['id']."' class='applyBtn'>Apply Online</a>"; } } else {//0 records returned echo "<h2>There is no job available at this time</h2>"; } } else { echo "Error:".$db->error; } |
Comments
[…] 4 variables will be set instantly and we can use it in our PHP file for database connection as […]