Skip to content

Instantly share code, notes, and snippets.

@aslamdoctor
Last active August 29, 2022 07:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aslamdoctor/4f2105eaa7fc657f51d8864c18831638 to your computer and use it in GitHub Desktop.
Save aslamdoctor/4f2105eaa7fc657f51d8864c18831638 to your computer and use it in GitHub Desktop.
Very Simple CRUD Class using PHP
<?php
class CRUD {
protected $conn;
protected $tablename = 'MY_DEFAULT_TABLENAME';
function __construct() {
$this->conn = new mysqli( 'HOST', 'USERNAME', 'PASSWORD', 'DB_NAME' );
if ( $this->conn->connect_error ) {
die( $this->conn->connect_error );
}
}
public function set_table( $tablename ) {
$this->tablename = $tablename;
}
public function create( $data ) {
$fields = '';
$values = '';
foreach ( $data as $field => $value ) {
$fields .= $field . ',';
$values .= "'$value',";
}
$fields = rtrim( $fields, ',' );
$values = rtrim( $values, ',' );
$query = "INSERT INTO $this->tablename ($fields) VALUES($values);";
$result = mysqli_query( $this->conn, $query ) or die( mysqli_error( $this->conn ) );
return $result;
}
public function update( $data, $id ) {
$update_str = '';
foreach ( $data as $field => $value ) {
$update_str .= "$field = '$value',";
}
$update_str .= 'date_updated = NOW(),';
$update_str = rtrim( $update_str, ',' );
$query = "UPDATE $this->tablename SET $update_str WHERE ID='$id';";
$result = mysqli_query( $this->conn, $query ) or die( mysqli_error( $this->conn ) );
return $result;
}
public function delete( $id ) {
$query = "DELETE FROM $this->tablename WHERE ID='$id';";
$result = mysqli_query( $this->conn, $query ) or die( mysqli_error( $this->conn ) );
return $result;
}
public function get( $id ) {
$query = "SELECT * FROM $this->tablename WHERE ID='$id';";
$result = mysqli_query( $this->conn, $query ) or die( mysqli_error( $this->conn ) ) or die( mysqli_error( $this->conn ) );
$row = mysqli_fetch_assoc( $result );
return $row;
}
public function getAll() {
$query = "SELECT * FROM $this->tablename ORDER BY full_name;";
$result = mysqli_query( $this->conn, $query ) or die( mysqli_error( $this->conn ) ) or die( mysqli_error( $this->conn ) );
return $result;
}
}
<?php
require_once 'CRUD.php';
$crud = new CRUD();
// To set Tablename
$crud->set_table('Customers');
// Create record
$crud->create(
array(
'full_name' => 'John Doe',
'phone' => '12345678910',
)
);
// Update records
$crud->update(
array(
'phone' => '7891011',
),
1
);
// Delete Record
$crud->delete( 1 );
// Get Single Record
$customer = $crud->get( 2 );
if ( $customer ) {
print_r( $customer );
} else {
echo 'Not found';
}
// Get All Records
$customers = $crud->getAll();
if ( $customers->num_rows > 0 ) {
while ( $row = $customers->fetch_assoc() ) {
print_r( $row );
echo '<hr/>';
}
} else {
echo 'No records found';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment