phpvariablescomposer-phpmedoo

PHP Page Blank - Not understanding scopes


So, simply put, I feel like this code should work. Literally at this moment I am just trying to create a PHP class that takes in some information and runs a command against the database. I know the command works so it's not that, it something to do with the scope of my variables.

I'm new to PHP, and it's been interesting to handle.

<?php
require __DIR__ . '/../bin/composer/vendor/autoload.php';

$cx = new Customer();
$cx->WriteCxToDB();

class Customer {
  public $database = new medoo([
    'database_type'=>'mysql',
    'database_name'=>'dbname',
    'server'=>'localhost',
    'username'=>'dbusername',
    'password'=>'dbpassword',
    'charset'=>'utf8'
  ]);

  public function WriteCxToDB(){
    global $database;
    if($database->has("customer", [
      "OR"=>[
        "username"=>"cxusername",
        "email"=>"email@gmail.com"
      ]
      ]))
      {
      echo "User already exists";
    }else{
      $database->insert("customer", [
        "username"=>"username",
        "keyword"=>"keyword",
        "email"=>"email@gmail.com",
        "phone"=>"444-444-4444",
        "first_name"=>"First",
        "last_name"=>"Last"
    ]);
    echo "User added";
  }
  echo "Done";
  }
}
?>

I am using composer and medoo to do this database entry. I know the database code works because I've ran it on it's own and it runs fine.

What I'm struggling with the seems to be the variable $database in the code. The function call works if I remove that variable from the mix. I feel like I'm just not understanding where I am supposed to declare the variable / how to reference it from within / outside the function. Thanks.


Solution

  • As suggested in the previous example you should be using something like this and pass a db connection into the class, extending a base class would allow reuse of the db connection:

    private $database;  
    
    public function __construct($db_connection = null){
        //do stuff or set db
        $this->database = $this->db_connect;
    }
    

    OR make a method in the class to do it

     private function db_connect(){
            return new medoo([
            // required
            'database_type' => 'mysql',
            'database_name' => 'name',
            'server' => 'localhost',
            'username' => 'your_username',
            'password' => 'your_password',
            'charset' => 'utf8',    
            ]);
    
        }
    

    to check consider catching the errors. Using a unique or primary key on the DB would be a safer way of doing this otherwise you have to do validation and searching on the DB. Add the keys and check for duplicate errors.

    if($database->error()){
      //deal with return or pass to logging
    }