Search code examples
mysqlsql-updatewampserver

php mysql generic update query not updating data in database


I have a generic update query in a file, I know it is being called by the my projectscontroller but I do not know whether the issue is between the form and controller, form and function or function and controller.

My code is supposed to work where from the Project list form is populated with records with edit and delete buttons (this works),when the EDIT button is chosen the Editproject form will populate with the data in that line (this works). After editing the info displayed in the form the user presses save which calls the EDIT function in the project controller which in turn calls the save function then the update function and thus updates the database (this doesnt work). I am not sure where the error is as no error is occuring and i know the code is entering the EDIT function of the controller because after it does it opens the list again.

I am sure the error is some stupid typo i made somewhere, and if your wondering the save function can go to update or insert functions but the insert works perfectly fine.

This is why I'm 80% sure it has something to do with the update function itself or the way im passing the info to the update function.

Any help would be greatly appreciated, my project table create is at the end and like I said, I'm sure its as simple as a typo somewhere I am overlooking (it always is with me).

Update function (and save)

private function update($fields) {
    $query = ' UPDATE `' . $this->table .'` SET ';

    foreach ($fields as $key => $value) {
        $query .= '`' . $key . '` = :' . $key . ',';
    }

    $query = rtrim($query, ',');

    $query .= ' WHERE `' . $this->primaryKey . '` = :primaryKey';

    //Set the :primaryKey variable
    $fields['primaryKey'] = $fields['id'];

    $fields = $this->processDates($fields);

    $this->query($query, $fields);
}
public function save($record) {
    try {
        if ($record[$this->primaryKey] == '') {
            $record[$this->primaryKey] = null;
        }
        $this->insert($record);
    }
    catch (PDOException $e) {
        $this->update($record);
    }
}

Project Controller

<?php

class ProjectController {
private $employeesTable;
private $projectsTable;

public function __construct(DatabaseTable $projectsTable, DatabaseTable $employeesTable) {
    $this->projectsTable = $projectsTable;
    $this->employeesTable = $employeesTable;
}

public function list() {
    $result = $this->projectsTable->findAll();

    $projects = array();
    foreach ($result as $project) {

        $projects[] = [
            'IDP' => $project['IDP'],
            'ProjectID' => $project['ProjectID'],
            'ProjectName' => $project['ProjectName'],
            'ProjectDes' => $project['ProjectDes'],
            'ProjectStartDate' => $project['ProjectStartDate'],
            'ProjectEndDate' => $project['ProjectEndDate'],
            'ProjectStatus' => $project['ProjectStatus']
        ];

    }


    $title = 'Project list';

    $totalProjects = $this->projectsTable->total();

    return ['template' => 'projects.html.php',
            'title' => $title,
            'variables' => [
                    'totalProjects' => $totalProjects,
                    'projects' => $projects
                ]
            ];
}

public function home() {
    $title = 'Colpitts Design';

    return ['template' => 'home.html.php', 'title' => $title];
}

public function delete() {
    $this->projectsTable->delete($_POST['id']);

    header('location: index.php?action=list');
}


public function edit() {
    if (isset($_POST['project'])) {

        $project = $_POST['project'];
        $project['projectstartdate'] = new DateTime();
        $project['projectenddate'] = null;

        $this->projectsTable->save($project);

        header('location: index.php?action=list');

    }   else {

        if (isset($_GET['id'])) {
            $projects = $this->projectsTable->findById($_GET['id']);
        }
        $title = 'Edit Projects';

        return ['template' => 'editproject.html.php',
                'title' => $title,
                'variables' => [
                        'project' => $projects ?? null
                    ]
                ];
    }
}

} editproject form

<form action="" method="post">
<input type="hidden" name="project[IDP]" value="<?=$project['IDP'] ?? ''?>">
    <label for="ProjectID">Type the Project id here:</label>
    <textarea id="ProjectID" name="project[ProjectID]" rows="3" cols="40"><?=$project['ProjectID'] ?? ''?></textarea>

    <label for="ProjectStatus">Type the Project status here:</label>
    <textarea id="ProjectStatus" name="project[ProjectStatus]" rows="3" cols="40"><?=$project['ProjectStatus'] ?? ''?></textarea>

    <label for="ProjectName">Type the Project name here:</label>
    <textarea id="ProjectName" name="project[ProjectName]" rows="3" cols="40"><?=$project['ProjectName'] ?? ''?></textarea>

<label for="ProjectDes">Type the Project description here:</label>
<textarea id="ProjectDes" name="project[ProjectDes]" rows="3" cols="40"><?=$project['ProjectDes'] ?? ''?></textarea>

<input type="submit" name="submit" value="Save">

projectlist form

<p><?=$totalProjects?> projects are listed in the DanClock Database.</p>

<?php foreach($projects as $project): ?>
<blockquote>
  <p>

  <?=htmlspecialchars($project['ProjectID'], ENT_QUOTES, 'UTF-8')?>
  <?=htmlspecialchars($project['ProjectDes'], ENT_QUOTES, 'UTF-8')?>
  <?=htmlspecialchars($project['ProjectStartDate'], ENT_QUOTES, 'UTF-8')?>
  <?=htmlspecialchars($project['ProjectStatus'], ENT_QUOTES, 'UTF-8')?>

  <a href="index.php?action=edit&id=<?=$project['IDP']?>">Edit</a>

  <form action="index.php?action=delete" method="post">
<input type="hidden" name="id" value="<?=$project['IDP']?>">
<input type="submit" value="Delete">
  </form>
  </p>
</blockquote>
<?php endforeach; ?>

Projects table

CREATE TABLE `Projects` (
  `IDP` int(11) NOT NULL AUTO_INCREMENT,
  `ProjectID` int(11) NOT NULL,
  `ProjectName` varchar(50) NOT NULL,
  `ProjectDes` text,
  `ProjectStartDate` Datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `ProjectEndDate` Datetime,
  `ProjectStatus` varchar(50) NOT NULL DEFAULT 'Active',
  PRIMARY KEY  (IDP)
 ) ENGINE=InnoDB;

Solution

  • I figured out the issue, as i thought it was my update function. It wasnt as "generic" as I thought it was, or it was almost.

    this line:

        //Set the :primaryKey variable
        $fields['primaryKey'] = $fields['id'];
    

    should be:

    //Set the :primaryKey variable
    $fields['primaryKey'] = $fields[$this->primaryKey];
    

    Somethhing small that I didnt notice, now to continue on with everything else ><