我可以为PDO或mysqli重写此函数吗?如果是,请提供一个例子。
function dbquery($query) {
global $mysql_queries_count, $mysql_queries_time; $mysql_queries_count++;
$query_time = get_microtime();
$result = @mysql_query($query);
$query_time = substr((get_microtime() - $query_time),0,7);
$mysql_queries_time[$mysql_queries_count] = array($query_time, $query);
if (!$result) {
echo mysql_error();
return false;
} else {
return $result;
}
}
function dbrows($query) {
$result = @mysql_num_rows($query);
return $result;
}
function dbarray($query) {
$result = @mysql_fetch_assoc($query);
if (!$result) {
echo mysql_error();
return false;
} else {
return $result;
}
}
<?php $result = dbquery("SELECT * FROM ".DB_THREADS." INNER JOIN ".DB_USERS." WHERE thread_lastuser=user_id ORDER BY thread_lastpost DESC LIMIT 5");
if (dbrows($result) != 0) {
while ($data = dbarray($result)) {
<?php echo $data['thread_id'];
<?php } } ?>
由于
答案 0 :(得分:3)
是的,你可以!这是让你入门的东西:
答案 1 :(得分:3)
以下是您使用PDO重写的代码:
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
die();
}
function dbquery($query) {
global $db, $mysql_queries_count, $mysql_queries_time; $mysql_queries_count++;
$query_time = get_microtime();
$result = $db->query($query);
$query_time = substr((get_microtime() - $query_time),0,7);
$mysql_queries_time[$mysql_queries_count] = array($query_time, $query);
if (!$result) {
echo $db->errorCode();
return false;
} else {
return $result;
}
}
function dbrows($query) {
global $db;
$result = $db->exec($query);
return $result;
}
function dbarray($results) {;
$result = $results->fetch(FETCH_ASSOC);
if (!$result) {
echo $results->errorCode();
return false;
} else {
return $result;
}
}
<?php $results = dbquery("SELECT * FROM ".DB_THREADS." INNER JOIN ".DB_USERS." WHERE thread_lastuser=user_id ORDER BY thread_lastpost DESC LIMIT 5");
if (dbrows($results) != 0) {
while ($data = dbarray($results)) {
<?php echo $data['thread_id'];
<?php } } ?>
我尽可能少地改变,只是为了向您展示PDO的功能,所以我没有做出一些可能的改进。有关详细信息,请查看the documentation for PDO。