PHP basic database connection and record listing

Database name: contact

Table schema: friendslist {ID, fullname, email, phoneno, DOB}

The PHP code:

<?php
//1. establish connection to database server
//since it is on XAMPP, so no password for root
//BAD practice
$db=mysqli_connect("localhost","root","","contact");

//2. check the connection
if($db==false){
echo "Database connection fail!<br>";
echo "Error: ".mysqli_connect_error($db);
}
else{//if can connect
echo "Yeay... Connected to database<br>";

//3. sql command to SELECT all data
$sql="SELECT * FROM friendslist";

//4. send sql command to database server
$rs=mysqli_query($db, $sql);

//5. display records
if ($rs==false){
echo "SQL Error".mysqli_error($db);
}
else{//display SQL error message
while ($record=mysqli_fetch_array($rs)){
echo "ID:".$record['ID']."<br>";
echo "Fullname:".$record['fullname']."<br>";
echo "Email:".$record['email']."<br>";
echo "Phone:".$record['phoneno']."<br>";
echo "Birth date:".$record['DOB']."<br>";
echo "<hr>";
}
}
}
?>

Popular Posts

WorldConferences.net