Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Saturday, October 22, 2022

Connect MySQL database using PHP and Select values from Table

 I have shown how you can Connect to your MySQL database and select values from the table in that database.

Here in this example I am connecting to local host MySQL database

Connect to Database with below code

<?php 
 echo 'Hello<br>';
 $hostname='localhost';
 $username='root';
 $password='root';
 $database='test';
 $conn=new mysqli($hostname,$username,$password,$database);
  if(!$conn){
   die('Error In connection'.mysqli_connect_error());
  }else{
   echo 'Connection Success<br>';
  }
mysqli_close($conn);
?>

After running the above page in localhost server

Connect to Database and Select a value from the table.

<?php 
echo 'Hello<br>';
$hostname='localhost';
$username='root';
$password='root';
$database='test';
$conn=new mysqli($hostname,$username,$password,$database);
  if(!$conn){
    die('Error In connection'.mysqli_connect_error());
   }else{
    echo 'Connection Success<br>';
   }
  $sql = "SELECT * FROM codes";
  $result = $conn->query($sql);
 if ($result->num_rows > 0) {
  while($row = $result->fetch_assoc()) {
    echo "sl_no: " . $row["sl_no"]. " - Name: " . $row["name"]. "<br>";
  }
 } else {
 echo "0 results";
}
mysqli_close($conn);
?>

No comments:

Post a Comment