Code:
db.php
<?php
$link_id = mysql_pconnect($server, $username, $password);
mysql_select_db($link_id, $db);
?>
page.php
<?php
require_once("db.php");
$results = mysql_query($sql, $link_id);
?>
Quick and dirty, you should make a db class to do this, and build in input cleaning functionality etc into it.
Edit: At work now, here's my db class. Username etc are hard coded, easy enough to change that.
Code:
class db {
private $linkId;
private $preparedQuery;
private $resultId;
function __construct() {
$this->linkId = mysql_pconnect("localhost", "support", "password");
mysql_selectdb("support", $this->linkId);
$this->preparedQuery = "";
}
private function clean_input($string) {
return mysql_real_escape_string($string, $this->linkId);
}
function prepare($sql_query, $values = "") {
if (is_array($values)) {
foreach ($values as $key => $value) {
$safe_value = $this->clean_input($value);
$sql_query = str_replace($key, $safe_value, $sql_query);
}
$this->preparedQuery = $sql_query;
} else {
$this->preparedQuery = $sql_query;
}
}
function execute($debug = FALSE) {
if ($this->preparedQuery) {
if ($debug == TRUE) {
echo $this->preparedQuery;
}
$this->resultId = mysql_query($this->preparedQuery, $this->linkId);
if ($this->resultId) {
return $this->resultId;
} else {
return false;
}
} else {
return false;
}
}
function error() {
echo mysql_error($this->linkId);
}
function num_rows($resultId = "") {
if ($resultId) {
return mysql_num_rows($resultId);
} else {
return mysql_num_rows($this->resultId);
}
}
function fetch_assoc($resultId = "") {
if ($resultId) {
return mysql_fetch_assoc($resultId);
} else {
return mysql_fetch_assoc($this->resultId);
}
}
}
$db = new db();
$sql_query = "SELECT * FROM foo WHERE var=¶m";
$sql_param = array("¶m"=>"blah");
$db->prepare($sql_query, $sql_param);
$result = $db->execute();