簡體   English   中英

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

[英]PHP Update and Delete Functions Don't Work

使用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);
}
}
?>

任何幫助或見解將不勝感激。

您的UPDATE語句是錯誤的。 正確的語法是:

UPDATE table_name SET column_name = some_value WHERE some_condition

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM