为什么我不能使用PHP Slim框架连接到数据库?

时间:2016-12-22 12:54:13

标签: php slim

我是PHP Slim框架的新手,我编写了连接数据库的代码,但它在控制台中显示以下错误(数据库存在,仍然出错):

enter image description here

这是我的代码:

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require '../vendor/autoload.php';

function dbConnect(){
    $host='127.0.0.1';
    $user='root';
    $pass='';
    $dbname='testdbmysql';
    $pdo= new PDO("mysql:host=$host; dbname= $dbname", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    return $pdo;
}

$app = new \Slim\App;
$app->post('/hello/{id}', function (Request $request, Response $response, $args) {
    echo "hello";
    $names = $request->getParsedBody();
    $db=dbConnect();
    $names_arr=[];
    $names_arr['name1']= filter_var($names['name1'], FILTER_SANITIZE_STRING);
    $names_arr['name2']= filter_var($names['name2'], FILTER_SANITIZE_STRING);
    $response->getBody()->write("Hello , ".$names_arr['name1']);
    $query=mysqli_prepare($db, "INSERT into info(fname, lname) VALUES(?, ?)");
    mysqli_stmt_bind_param($query, "ss", $names_arr['name1'], $names_arr['name2']);
    $result=mysqli_stmt_execute($query);
    $rows=mysqli_stmt_insert_id($query);
    echo "Rows: ".$rows;
    return $response;
});
$app->run();
?>

当我在互联网上搜索时,我找到了由Laravel框架引起的相同错误的解决方案,但不是关于Slim。有什么我可以做的吗?

1 个答案:

答案 0 :(得分:1)

你应该删除空白

def binsearch(pylist, element):
    if len(pylist) == 0:
        return False
    elif len(pylist) == 1 and pylist[0] == element:
        return True
    else:
        mid = len(pylist) / 2 - 1
        if element > pylist[mid]:
            binsearch(pylist[mid:], element)
        else:
            binsearch(pylist[:mid], element)

错误输出也显示空白。所以这应该是错误的。

另外,不要混淆PDO和mysqli。您正在将PDO-Connection传递给mqsqli函数,这就是为什么你得到&#34;期待的mysqli,得到了PDO。&#34;

我会坚持使用mysqli并通过mysqli_connect()建立连接。