我有一個類文件和類文件內的一些代碼。 如何在多個頁面上共享代碼。 該代碼解決了使用準備語句時獲取結果集的用法PHP共享代碼
代碼是這樣的。我如何重用函數mps_fetch_assoc。我只需要在一個地方的代碼。
<?php
//http://localhost:8080/altenaontw/index.php?-action=showclient
class actions_showclient
{
// find here http://www.meetup.com/austinphp/messages/boards/thread/2022681
private function mps_fetch_assoc(&$stmt)
{
$meta = $stmt->result_metadata();
$retval[] = &$stmt;
$tmp;
$names;
while ($field = $meta->fetch_field())
{
$names[] = $field->name;
}
$tmp = $names;
for ($c = 0; $c < count($names); $c++)
{
$retval[] = &$tmp[$c];
}
call_user_func_array("mysqli_stmt_bind_result", $retval);
if ($stmt->fetch())
{
$assoc_array;
for ($c = 0; $c < count($names); $c++)
{
$assoc_array[$names[$c]] = $retval[$c + 1];
}
return $assoc_array;
}
else
{
return FALSE;
}
}
function handle($params)
{
header('Content-type: text/json; charset="UTF-8"');
$user = Dataface_AuthenticationTool::getInstance()->getLoggedInUser();
if (!$user)
{
return Dataface_Error::permissionDenied("U heeft geen toegang tot deze actie.");
}
$db = Dataface_Application::getInstance()->_conf['_database'];
echo ($db['host']);
//$mysqli = new mysqli($db['host'], $db['user'], "", $db['name']);
$mysqli = mysqli_connect($db['host'], $db['user'], "", $db['name']);
/* check connection */
if ($mysqli->connect_errno)
{
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$sql = 'SELECT * from client';
$stmt = $mysqli->prepare($sql);
if ($stmt)
{
$result = $stmt->execute();
if (!$result)
{
echo "[" . json_encode(array('dberror' => 'db_error:' . mysql_error())) . "]";
return;
}
$rows = array();
while ($row = $this->mps_fetch_assoc($stmt))
{
$rows[] = $row;
}
print json_encode($rows);
$mysqli->close();
}
}
}
?>
格式化你的代碼時,請注意:可以很容易地閱讀,甚至爲你:-) – 2013-05-05 12:08:33