If you trying to connect with the MySQL database quickly then you can use this code from below. It’s simple a MySql connection and gets result snippet code.
<?php
// Connection function
function myConnection(){
$serverName = "localhost";
$username = "root";
$password = "";
$dbName = "DB_NAME";
// Create connection
$conn = new mysqli($serverName, $username, $password, $dbName);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
// Run query
function MySqlQuery($query){
$conn = myConnection();
$result = $conn->query($query);
return $result;
}
// Formatted mySql result
function getSqlResult($query){
$conn = myConnection();
$result = $conn->query($query);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$return[] = (object)$row; // Converting data to object by use (object)
}
} else {
}
return $return;
}
// Run the query
$allUsers = getSqlResult("SELECT * FROM `users`");
// Print result
echo "<PRE>"; print_r($allUsers); echo "</PRE>";
Happy coding 🙂