dongli564510 2014-11-24 16:52
浏览 51

构建函数使用slim框架并找不到404页面

I'm a PHP beginner and new on slim framework.

Here is my motivation after reading "Connecting Slim Framework and MySQL"(http://scottnelle.com/616/connecting-slim-framework-mysql/).

I've followed the article also succeed, so I decided to go further and build functions.

Below are my code(mostly same as the article), but I have two problem:

  1. Is it a proper way using function contains slim in my 'lib/function.php' ?
  2. After I submit form in my 'testpage.php', the result 'test_a();' and 'test_b();' all show '404 page not found' error, but they run OK after reload 'testpage.php' and first load 'testpage.php'.

// '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' ?>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
    • ¥15 如何在scanpy上做差异基因和通路富集?
    • ¥20 关于#硬件工程#的问题,请各位专家解答!
    • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
    • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
    • ¥30 截图中的mathematics程序转换成matlab
    • ¥15 动力学代码报错,维度不匹配
    • ¥15 Power query添加列问题
    • ¥50 Kubernetes&Fission&Eleasticsearch
    • ¥15 報錯:Person is not mapped,如何解決?