I'm using mysqli with PHP, but my custom functions always require me to pass the link, which I think i read in another book is not very good. The thing is I'm not sure how to get around this.
Here is some code giving an example of what i do
// set server access variables
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'custom';
// create mysqli object
// open connection
@$mysqli = new mysqli($host, $user, $pass, $db);
// check for connection errors
if (mysqli_connect_errno())
{
die('Unable to connect to database!');
}
$query = "DELETE FROM images WHERE id='1'";
get_result_for_query($mysqli, $query);
function get_result_for_query($mysqli, $query)
{
//insert, delete
if ($result = $mysqli->query($query))
{
//note how result is not an mysqli object here, its a boolean
if ($result > 0)
{
$data = 'It worked';
}
else
$data = 'It failed';
}
else
{
echo $mysqli->error;
echo '<hr /> no results <hr />';
}
//DEBUG line in here
return 'data=' . $data . "\n<br />" . $result . ' query=' . $query . "\n<hr />";
}
I have more functions than that, but I always have to pass the link. Is that good? Or is there a better way to do this? I'd use classes but I'm not strong enough with OOP in PHP yet, that and I barely know database stuff well, so I have to learn it all slowly.