mysql_*
is officially deprecated. Use either PDO
or mysqli
. This is how you do it with MySQLi library:
<?php
// Connect To Db
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Query Function
function getCategories()
{
// Init
global $mysqli;
$response = array('Student' => array());
// Query Db
$query = "SELECT * FROM Student";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$response['Student'][] = array(
'id' => $row['id'],
'name' => $row['name'],
'number' => $row['number'],
'address' => $row['address'],
);
}
$result->free(); // free up memory
}
// Finished
header('Content-Type: application/json');
exit(json_encode(response));
}
// Test
getCategories();
// Close Db Connect
$mysqli->close();
You can have this code:
// Connect To Db
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
In a file called db_connect.php and you can include it on the script you require db connection. Because the variable $mysqli
is initiated outside of the function() { ... }
scope; you need to use global $mysqli;
to get access to it. This applies regardless of the connection code being on same file or being included from external file. Happy coding.