如何在请求中像参数一样发送数据库表名并在服务器上的函数中处理它?

时间:2019-05-24 08:56:44

标签: rest api slim

我有自己的API,一切都很好,但是我需要以下帮助: 我使用一个函数来获取其参数内的数据库表名称,然后根据该名称插入数据。 例如:

function InsertData( $Employee,$userId,...) {
$query = INSERT INTO $Employee(...,...,...,...) VALUES (?,?,?,...)
}


function InsertData( $Passenger,$userId,...) {
$query = INSERT INTO $Passenger(...,...,...,...) VALUES (?,?,?,...)
}
public function createPost ($tablename,$userid,$content){

    $postStatement = $this->con->prepare("INSERT INTO '.$tablename.'(userid,content) VALUES (?,?)");
    $postStatement ->bind_param("is",$userid,$content);
    if ($postStatement ->execute()){
        return DONE;
    }else{
        return NOT_DONE;
}

它总是显示消息:内部服务器错误

1 个答案:

答案 0 :(得分:0)

在您的情况下,我将尝试为每个查询创建一个自定义方法。

  1. 确保PDO引发异常:
$host = 'localhost';
$dbname = 'test';
$username = 'root';
$password = '';
$charset = 'utf8mb4';
$collate = 'utf8mb4_unicode_ci';
$dsn = "mysql:host=$host;dbname=$dbname;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_PERSISTENT => false,
    PDO::ATTR_EMULATE_PREPARES => true,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES $charset COLLATE $collate"
];

$pdo = new PDO($dsn, $username, $password, $options);

然后为每个查询创建一个方法。示例:

public function insertPassenger(string $firstName, string $lastName): int
    $row = [
        'first_name' => $firstName,
        'last_name' => $lastName,
    ];

    $sql = "INSERT INTO passengers SET first_name=:first_name, last_name=:last_name;";
    $this->pdo->prepare($sql)->execute($row);

    return (int)$this->pdo->lastInsertId();
}

public function insertReservation(int flightId, $passengerId): int
    $row = [
        'flight_id' => $flightId,
        'passenger_id' => $passengerId,
    ];

    $sql = "INSERT INTO reservations SET flight_id=:flight_id, passenger_id=:passenger_id;";
    $this->pdo->prepare($sql)->execute($row);

    return (int)$this->pdo->lastInsertId();
}