Skip to content

Instantly share code, notes, and snippets.

@TerryFunggg
Created October 19, 2021 09:31
Show Gist options
  • Save TerryFunggg/469cd40ab2cdb752b29c89c6eab9dd32 to your computer and use it in GitHub Desktop.
Save TerryFunggg/469cd40ab2cdb752b29c89c6eab9dd32 to your computer and use it in GitHub Desktop.
Simple php model
<?php
class Customer
{
private $id;
private $fields;
public function __construct()
{
$this->id = null;
$this->fields = array(
'code' => '',
'usrname' => '',
'usrpwd' => '',
'token' => '',
'name' => '',
'title' => '',
'first_name' => '',
'last_name' => '',
'email' => '',
'mobile' => '',
'address' => '',
'status' => '',
'created_at' => '',
);
}
public function __get($field)
{
if($field == 'id') {
return $this->id;
}else {
return $this->fields[$field];
}
}
public function __set($field, $value)
{
if($field == 'id') {
$this->id = $value;
}else {
$this->fields[$field] = $value;
}
}
public static function getByusrpwd($usrpwd)
{
$c = new Customer();
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$sql = "SELECT * FROM customer WHERE usrpwd = '$usrpwd' ";
$result = $conn->query($sql);
if(mysqli_num_rows($result)){
$row = mysqli_fetch_assoc($result);
foreach ($row as $key => $value) {
$c->$key = $value;
}
}
$conn->close();
return $c;
}
public static function getByCode($code)
{
$c = new Customer();
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$sql = "SELECT * FROM customer WHERE code = '$code' ";
$result = $conn->query($sql);
if(mysqli_num_rows($result)){
$row = mysqli_fetch_assoc($result);
foreach ($row as $key => $value) {
$c->$key = $value;
}
}
$conn->close();
return $c;
}
public function save()
{
if(!is_null($this->id)) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$keys = array_keys($this->fields);
$last_key = array_pop($keys);
$sql = "UPDATE customer SET";
foreach ($keys as $index => $key) {
$sql .= " " . $key . "='" . $this->$key . "', ";
}
$sql .= $last_key . "='" . $this->$last_key . "' ";
$sql .= " WHERE id = '$this->id'";
$result = $conn->query($sql);
$conn->close();
return $result;
}
// TODO: when id is null, create a new user into DB.
}
}
@TerryFunggg
Copy link
Author

TerryFunggg commented Nov 8, 2021

$sql = "UPDATE customer SET $key[0] = {$this->$key}";
for (int i = 1; i < count($key); i++) {
 $sql .= ", $key = { $this->$key}";
}
$sql .= " WHERE id = '$this->id'";

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment