我是PHP初学者,也是苗条框架的新手。
阅读"连接Slim Framework和MySQL"(http://scottnelle.com/616/connecting-slim-framework-mysql/)之后,我的动机就是这样。
我跟着文章也成功了,所以我决定进一步建立功能。
以下是我的代码(大部分与文章相同),但我有两个问题:
// 'lib/mysql.php', only for database connection
<?
function connect_db() {
$server = 'localhost';
$user = 'user';
$pass = 'pass';
$database = 'slim_db';
$connection = new mysqli($server, $user, $pass, $database);
return $connection;
}
?>
// 'lib/function.php', and I try to build slim functions
<?
require 'lib/mysql.php';
function test_a() {
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim(); $app->get('/', function () use ($app) {
require_once 'lib/mysql.php';
$db = connect_db();
$result = $db->query( 'SELECT id, name, job FROM friends;' );
while ( $row = $result->fetch_array(MYSQLI_ASSOC) ) {
$data[] = $row;
}
$app->render('page_a.php', array(
'page_title' => "pag a",
'data' => $data
)
);
});
$app->run();
}
function test_b() {
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim(); $app->get('/', function () use ($app) {
require_once 'lib/mysql.php';
$db = connect_db();
$result = $db->query( /*another query*/ );
while ( $row = $result->fetch_array(MYSQLI_ASSOC) ) {
$data[] = $row;
}
$app->render('page_b.php', array(
'page_title' => "page b",
'data' => $data
)
);
});
$app->run();
}
?>
//'testpage.php' is an page contains a form and calling functions.
<?
require 'header.php';
require 'lib/function.php';
test_a();
test_b();
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
/*do something submit form*/
}
?>
<form action="" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
<? require 'footer.php' ?>