I'm trying to convert my php code into OOP. I'm using Datatables with jquery en ajax + JSON to load projects into a table. But i want to convert this code into OOP, but i always get a invalid json response. Im new into writing OOP, so could anyone help me out whats wrong with my code? I am trying to build one class around this codet. Can anybody help or make a skeleton for me, so i know what i do wrong? This is the code :

    /**
    * Class project
    */


    class Project {

        private $sql


    // Get project (and id)
    $project = '';
    $id  = '';
    if (isset($_GET['project'])){
      $project = $_GET['project'];
      if ($project == 'get_projecten' ||
          $project == 'get_project'   ||
          $project == 'add_project'   ||
          $project == 'edit_project'  ||
          $project == 'delete_project'){
        if (isset($_GET['id'])){
          $id = $_GET['id'];
          if (!is_numeric($id)){
            $id = '';
          }
        }
      } else {
        $project = '';
      }
    }

    // Prepare array
    $mysql_data = array();

    // Valid job found
    if ($project != ''){

      // Connect to database
      $db_connection = mysqli_connect($db_server, $db_username, $db_password, $db_name);
      if (mysqli_connect_errno()){
        $result  = 'error';
        $message = 'Failed to connect to database: ' . mysqli_connect_error();
        $project    = '';
      }

      // Execute job
      public function get_projecten ($project == 'get_projecten'){

        // Get projecten
        $sql= "SELECT * FROM projects ORDER BY projectid";
        $query = mysqli_query($db_connection, $sql);

        if (!$query){
          $result  = 'error';
          $message = 'query error';
        } 
        else {
          $result  = 'success';
          $message = 'query success';

          while ($project = mysqli_fetch_array($query)){
            $test = '<a href="tasks.php" data-name="' . $project['projectnaam'] . '">' . $project['projectnaam'] . '</a>';
            $functions  = '<div class="function_buttons"><ul>';
            $functions .= '<li class="function_edit"><a data-id="'   . $project['projectid'] . '" data-name="' . $project['projectnaam'] . '"><span>Edit</span></a></li>';
            $functions .= '<li class="function_delete"><a data-id="' . $project['projectid'] . '" data-name="' . $project['projectnaam'] . '"><span>Delete</span></a></li>';
            $functions .= '</ul></div>';

            $mysql_data[] = array(
              "projectid"      => $project['projectid'],
              "projectnaam"    => $test,
              "startdatum"     => $project['startdatum'],
              "einddatum"      => $project['einddatum'],
              "omschrijving"   => $project['omschrijving'],
              "functions"      => $functions

            );
          }
        }

      } public function get_project ($project == 'get_project'){

        if ($id == ''){
          $result  = 'error';
          $message = 'id missing';
        } else {
          $sql = "SELECT * FROM projects WHERE projectid = '" . mysqli_real_escape_string($db_connection, $id) . "'";
          $query = mysqli_query($db_connection, $sql);
          if (!$query){
            $result  = 'error';
            $message = 'query error';
          } else {
            $result  = 'success';
            $message = 'query success';
            while ($project = mysqli_fetch_array($query)){
              $mysql_data[] = array(
                "projectid"      => $project['projectid'],
                "projectnaam"    => $project['projectnaam'],
                "startdatum"     => $project['startdatum'],
                "einddatum"      => $project['einddatum'],
                "omschrijving"   => $project['omschrijving']
              );
            }
          }
        }

      } public function add_project ($project == 'add_project'){

        // Add project

        $projectid = $_GET['projectid'];
        $projectnaam =$_GET['projectnaam'];
        $startdatum =$_GET['startdatum'];
        $einddatum =$_GET['einddatum'];
        $omschrijving =$_GET['omschrijving'];


        $sql = "INSERT INTO projects (projectid, projectnaam, startdatum, einddatum, omschrijving) VALUES (".$projectid.",'".$projectnaam."', '".$startdatum."', '".$einddatum."', '".$omschrijving."')";

        $query = mysqli_query($db_connection, $sql);    
        if (!$query){
          $result  = 'error';
          $message = 'query error';
        } else {
          $result  = 'success';
          $message = 'query success';
        }

      } 


     public function edit_project ($project == 'edit_project'){

        // Edit project
        if ($id == ''){
          $result  = 'error';
          $message = 'id missing';

        } else {

             $projectid = $_GET['projectid'];
             $projectnaam =$_GET['projectnaam'];
             $startdatum =$_GET['startdatum'];
             $einddatum =$_GET['einddatum'];
             $omschrijving =$_GET['omschrijving'];


          $sql = "UPDATE projects SET projectnaam='".$projectnaam."', startdatum='".$startdatum."', einddatum='".$einddatum."', omschrijving='".$omschrijving."' WHERE projectid =".$projectid;

          $query  = mysqli_query($db_connection, $sql);
          if (!$query){
            $result  = 'error';
            $message = 'query error';
          } else {
            $result  = 'success';
            $message = 'query success';
          }
        }

      } 

      public function delete_project ($project == 'delete_project'){

        // Delete project
        if ($id == ''){
          $result  = 'error';
          $message = 'id missing';
        } else {
          $sql = "DELETE FROM projects WHERE projectid = '" . mysqli_real_escape_string($db_connection, $id) . "'";
          $query = mysqli_query($db_connection, $sql);
          if (!$query){
            $result  = 'error';
            $message = 'query error';
          } else {
            $result  = 'success';
            $message = 'query success';
          }
        }

      }

      // Close database connection
      mysqli_close($db_connection);

    }


    // Prepare data
    $data = array(
      "result"  => $result,
      "message" => $message,
      "data"    => $mysql_data
    );


    // Convert PHP array to JSON array
    $json_data = json_encode($data);
    echo $json_data;    

?>

Wrapping functional (or procedural) code in a class , isn't OOP. Let's talk a bit about separation of concerns. Logical you would have an object that handles the db operation in the lowest level (connect with the db / execute + prepare statements and all those things). Then you would have some objects that represent data – structures in Java their name are POJO's (Plain Old Java Objects) in PHP I call them PPO (Plain PHP Objects). For example as I can understand from your code your “project” object has id , name , startDate , endDate and 'omschrijving' (any English words for that?) , that are the properties , of course the PPO has getters and setters. Then you have the data workers , those takes the db object , have as private properties the SQL statements that are going to work in those and public methods to make this happen. If you want to go one step ahead you have instantiators , to map db data to PPO objects or lists of them.

All those might seem complex the first time that you read it , but I am sure that while you are trying those you will understand how much less code you have to write and how flexible your code is.

@see
https://www.daniweb.com/programming/web-development/tutorials/437592/introduction-to-phps-object-orientation by priteas )

https://www.daniweb.com/programming/web-development/threads/499320/common-issues-with-mysql-and-php by diafol )

https://www.daniweb.com/programming/web-development/tutorials/500118/a-simple-data-layer-for-oop-php-applications

https://www.daniweb.com/programming/web-development/tutorials/500310/object-instantiators-from-data-layer-for-php-oop-applications

https://www.daniweb.com/programming/web-development/tutorials/500538/the-indexed-objects-list-model-ilm-for-oop-php-applications

I uggest you to look at this example
Click Here

it is a complete php app written in oop logic with mvc pattern
it helped me to understand how to organize php code in oop logic.
for interaction with database look at idiorm code.
hth

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.