db_mysql
<?php
function query($server, $user, $password, $database, $fields, $sql){
$resultSet = array();
$link = mysql_connect($server, $user, $password) or die('> 不能连接到数据库');
if($link){
mysql_select_db($database);
mysql_query("set NAMES 'gbk'");
$results = mysql_query($sql);
while($row = mysql_fetch_array($results)){
$result = array();
foreach($fields as $field){
$result[$field] = $row[$field];
}
$resultSet[] = $result;
}
mysql_close($link);
}
return $resultSet;
}
?>
db_pdo
<?php
function query($server, $user, $password, $database, $fields, $sql){
$resultSet = array();
try {
$db = new PDO("mysql:host=$server;dbname=$database", $user, $password);
$db->exec("set NAMES 'gbk'");
$rows = $db->query($sql);
foreach($rows as $row){
$result = array();
foreach($fields as $field){
$result[$field] = $row[$field];
}
$resultSet[] = $result;
}
}catch(PDOException $e){
echo 'Connection failed: '.$e->getMessage();
}
return $resultSet;
}
?>
db_adodb
<?php
require_once('adodb5/adodb.inc.php');
require_once('adodb5/adodb-exceptions.inc.php');
function query($server, $user, $password, $database, $fields, $sql){
$resultSet = array();
try{
$db = ADONewConnection("mysql://$user:$password@$server/$database?persist");
$db->Execute("set NAMES 'gbk'");
$rs = $db->Execute($sql);
while (!$rs->EOF){
$result = array();
$row = $rs->fields;
foreach($fields as $field){
$result[$field] = $row[$field];
}
$resultSet[] = $result;
$rs->MoveNext();
}
} catch(exception $e) {
print_r($e);
}
return $resultSet;
}
?>
直接print_r()的时候IE好像受不了,所以
……这样吧
<?php
require_once('db_xxx.php');
function printK(){
$server = 'localhost';
$user = 'root';
$password = '321';
$database = 'books';
$fields = array('id', 'title', 'author', 'publisher', 'prise');
$sql = 'select * from book;
$sql_w = '';
$sql_o = '';
$ks = query($server, $user, $password, $database, $fields, $sql.$sql_w.$sql_o);
foreach($ks as $k){
$kInfo = join(',', array_values($k));
echo($kInfo.'<br />');
}
}
printK();
?>