connect to database
//DEFINE etc... function connect(){ //global $dbc; $dbc = mysqli_connect(HOST, USERNAME, PASSWORD, DB) or die('Cannot connect to MySQL! '.mysqli_connect_error()); return $dbc; }
The function I use to connect to the database with mysqli is this:
function open_database() {
global $hostname, $username, $password, $database, $db;
$db = new mysqli($hostname, $username, $password, $database);
if (mysqli_connect_error()) {
echo "<p>Can't connect with database<br/>Error message: ".mysqli_connect_error()."</p>";
echo "<p>Please contact the database administrator.</p>\n";
exit();
}
else {
set_charset_utf8();
}
} The line set_charset is used to communicate using utf-8. And to do a query I use this function:
function do_query($query) {
global $db;
$result = $db->query($query);
if ($db->errno) {
echo "<p>Error message: ".$db->errno." ".$db->error."</p>";
echo "<p>Please contact the database administrator.</p>\n";
exit();
}
return $result;
} So from your main php code you call these function like so:
open_database();
$result = do_query("SELECT * FROM atable WHERE acondition ='".$condition."'");
$num_results = $result->num_rows;
if ($num_result == 0) {
echo "<p>No results from query</p>";
}
else {
// we have some data to display / process
.....
I forgot, $hostname, username, password and database come from an include (db.php) that looks like this:
<?php
$hostname = 'aserver';
$database = 'yourdatabase';
$username = 'you';
$password = 'strongplease';
?>