How to establish connection in php mysqli?

Submitted 3 years, 6 months ago
Ticket #375
Views 418
Language/Framework Other
Priority Low
Status Closed

Anyone please help me in establishing connection in php to localhost...

Thanks in advance........

Submitted on Mar 19, 21
add a comment

1 Answer

Verified

Use PDO instead: PDO (https://www.php.net/manual/ro/book.pdo.php)

If you still need to use MySQLi, try this:

<?php
// database credentials
$servername = "localhost";
$username = "username";  // default is "root"
$password = "password";  // default is "" (empty password)
$dbname = "database_name"; 

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
} 

// database table
$table_name = "my_test_table";

// create a query
$sql = "SELECT * FROM " . $table_name;

$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
  }
} else {
  echo "0 results";
}
$conn->close();

?>

Submitted 3 years, 6 months ago


Latest Blogs