PHP更新和删除功能不起作用

时间:2016-10-18 01:11:55

标签: php

使用MVC架构构建单页CRUD应用程序。读写工作但更新和删除不起作用。我的理解是删除功能应该与REQUEST_METHOD GET绑定,但是我不确定我是否在正确的位置(在switch语句中)或者它应该在更大的GET中有条件的。我不知道为什么更新不起作用。

模型文件

<?php
class Model {
private $connection;
function __construct($conn) {
    # intialize sql connection variable
    $this->connection = $conn;
}

# generic read from database functionality
public function read($table, $fields = '*', $limit = 1000, $sort = 'ASC', $id = null, $id_field = null) {
    $sql = "";
    $fieldString = '';
    # create string from $fields array
    if(is_array($fields)) $fieldString = implode(',', $fields); // the $fields array is in the format ['FIELD_1_NAME', 'FIELD_2_NAME', 'FIELD_3_NAME'] which is converted to the sting 'FIELD_1_NAME, FIELD_2_NAME, FIELD_3_NAME' for the SQL query
    else $fieldString = $fields;

    if(is_null($id)) {
        # get all values from MyTable, use fields array to get requested # fields and sort parameter to sort
        $sql = "SELECT $fieldString FROM $table LIMIT $limit";
    } else {
        # get a single value by id
        $sql = "SELECT $fieldString FROM $table WHERE $id_field = $id";
    }
    # SQL String test
    # echo($sql);
    if($result = $this->connection->query($sql)) {
        $results = [];
        # Generating Results as an array of Objects
        while ($row= $result->fetch_object()) {
            $results[] = $row;
        }
        return $results;
    } else {
        return false;
    }
}

# generic write to database functionality
public function write($table, $fields, $args) {
    # create string from $args array
    $argString = implode('\',\'', $args); // the $args array is in the format ['VALUE_1', ' VALUE_2', ' VALUE_3'] which is converted to the sting "'VALUE_1', 'VALUE_2', 'VALUE_3'" for the SQL query
    # create string from $fields array
    $fieldString = implode(',', $fields); // the $fields array is in the format ['FIELD_1_NAME', 'FIELD_2_NAME', 'FIELD_3_NAME'] which is converted to the sting 'FIELD_1_NAME, FIELD_2_NAME, FIELD_3_NAME' for the SQL query
    # creating the sql query
    $sql = "INSERT INTO $table ($fieldString) VALUES('$argString')";
    # SQL String test
    echo($sql);
    return($this->connection->query($sql));
}

public function update($table, $fields, $args, $id) {
    # update DB implementation
    $argString = implode('\',\'', $args);
    $fieldString = implode(',', $fields);
    $sql = "UPDATE $table SET ($fieldString) VALUES('$argString') WHERE id=$id";
    echo $sql;
    return($this->connection->query($sql));
}

public function delete($id) {
    # delete DB implementation
    $sql = "DELETE FROM Players WHERE id=$id";
    return($this->connection->query($sql));
}
}
?>

控制器文件

<?php
class Controller {
# instance of model class injected into the controller
private $model;

function __construct($model) {
    $this->model = $model;
}

# request handler method is responsible for handling all http requests
public function requestHandler($server, $get, $post, $session) {
    # call method based on request, an example is shown below
    # example API format :
    # url for get request format for get by id: index.php?get=users&id=1
    # url for get request format for get all: index.php?get=users&limit=10
    # use your own API here
    # handling GET requests
    if($server['REQUEST_METHOD'] == 'GET') {
        # replace the url parameters based on your API parameters
        if(!empty($get["get"])) {
            switch ($get["get"]) {
                case 'players':
                    echo $this->getPlayers($get["id"], $get["limit"], $get["sort"]);
                    break;
                case 'delete':
                    echo $this->deletePlayer($get["id"]);
                    break;
                default:
                    echo 'Error: Invalid Request';
                    break;
            }
        }
    }

    # handling POST requests
    elseif($server['REQUEST_METHOD'] == 'POST') {
    # if the ID_FIELD is empty it’s a create request
        if(empty($post['id'])) {
            # replace FIELD NAMES as per your field names in the database
            echo $this->addPlayer(['Player_Name', 'Age', 'City', 'Country', 'Gender', 'Handedness', 'Broom', 'Position', 'Team', 'Favorite_Color', 'Headshot'], [$post['Player_Name'], $post['Age'], $post['City'], $post['Country'], $post['Gender'], $post['Handedness'], $post['Broom'], $post['Position'], $post['Team'], $post['Favorite_Color'], $post['Headshot']]);
        }

        # if the ID_FIELD is not empty then it’s an update request
        else { 
            echo $this->updatePlayer(['Player_Name', 'Age', 'City', 'Country', 'Gender', 'Handedness', 'Broom', 'Position', 'Team', 'Favorite_Color', 'Headshot'], [$post['Player_Name'], $post['Age'], $post['City'], $post['Country'], $post['Gender'], $post['Handedness'], $post['Broom'], $post['Position'], $post['Team'], $post['Favorite_Color'], $post['Headshot']]);
        }
    }
}

# change function name to one that represents your table name 
private function getPlayers($id, $limit = 1000, $sort) {
    # get data from the model
    # replace TABLE_NAME with the table that is to be read
    # replace ID_FIELD with the name of the ID Field
    $data = $this->model->read('Players', '*', $limit, $sort, $id, 'id');
    # process/transform data or apply application logic
    # return data as JSON string
    return json_encode($data);
}

# change function name to one that represents your table name
private function addPlayer($fields, $values) {
    # replace TABLE_NAME with the table that is to be read
    return $this->model->write('Players', $fields, $values);
}

# implement update and delete
private function updatePlayer($table, $fields, $values, $id) {
    return $this->model->update($table, $fields, $values, $id);
}

private function deletePlayer($id) {
    return $this->model->delete('Players', $id);
}
}
?>

非常感谢任何帮助或见解。

1 个答案:

答案 0 :(得分:0)

您的UPDATE声明错误。正确的语法是:

UPDATE table_name SET column_name = some_value WHERE some_condition