33 - PHP Online
Form of PHP Sandbox
Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php
in the places where the PHP script should be executed.
Result of php executing
Full code of 33.php
- <?php
- class Category
- {
- private $db;
- private $primeCategories = [
- "Post",
- "Tour",
- "Accommodation",
- "Car",
- ["Gear", "Car"],
- ["Fuel", "Car"],
- ["CarType", "Car"],
- ["CarBrand", "Car"],
- ];
- public function __construct(Database $db)
- {
- $this->db = $db;
- $this->primeCategories();
- //$this->createTable();
- }
- public function createTable()
- {
- if ($this->db->query("CREATE TABLE IF NOT EXISTS `categories` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `name` varchar(255) NOT NULL,
- `ParentCategory` int(11) DEFAULT NULL,
- `lang` varchar(10) NOT NULL,
- `IsPrime` tinyint(1) NOT NULL DEFAULT 0,
- PRIMARY KEY (`id`),
- KEY `PrentCategory` (`ParentCategory`)
- ) ENGINE=InnoDB;")) {
- /* $this->db->query("ALTER TABLE `categories`
- ADD CONSTRAINT `categories_ibfk_1` FOREIGN KEY (`ParentCategory`) REFERENCES `categories` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
- COMMIT;
- ");*/
- };
- }
- public function add($name, $parentId = null, $isPrime = false, $lang = "ar")
- {
- $q = new QueryBuilder($this->db);
- if ($this->alreadyExist($name, $parentId)) {
- return json_encode(["status" => "already exist"]);
- } else {
- $q->table("categories")->insert([
- 'Name' => $name,
- 'ParentCategory' => $parentId,
- 'IsPrime' => $isPrime,
- 'lang' => $lang
- ])->execute();
- return json_encode(["status" => "success"]);
- }
- }
- function primeCategories()
- {
- $catArr = $this->primeCategories;
- for ($i = 0; $i < count($catArr); $i++) {
- if (!is_array($catArr[$i])) {
- # code...
- $this->add($catArr[$i], null, true, "");
- } elseif (is_array($catArr[$i])) {
- $parent = $this->getIdByNames($catArr[$i][1]);
- $this->add($catArr[$i][0], $parent, true, "");
- }
- }
- }
- public function combobox(string $catId, bool $multiple = true, $id = "")
- {
- $cat = !is_numeric($catId) ? $this->getIdByNames($catId) : $catId;
- $allCategories = self::getChildrenCategories($cat);
- $i = 0;
- $select = "";
- $multiAttr = $multiple ? "multiple" : null;
- $idAttr = $id == "" ? $multiple ? "categorySelect" : 'categoryAddSelect' : $id;
- $select .= "<select id='$idAttr' class='selectpicker' $multiAttr data-live-search='true' data-cat-info='$cat'>
- ";
- foreach ($allCategories as $category) {
- //$select .= ' <option value="' . $category['id'] . ">" . $category['name'] . '</option>';
- //if ($lang == $category['lang'])
- $select .= "<option value='$category[id]' data-lvl='$category[IsPrime]'> $category[name]</option>";
- }
- $select .= "
- </select>";
- return $select;
- }
- public function comboboxAll()
- {
- $q = new QueryBuilder($this->db);
- $cats = $q->select("*")->table('categories')->get();
- $options = '';
- foreach ($cats as &$item) {
- $options .= "<option value=\"{$item['id']}\">{$item['name']}</option>\n";
- }
- return "<select class='selectpicker' multiple>\n" . $options . "\n</select>";
- }
- public function categoryCheckList(int $catId)
- {
- $allCategories = self::getChildrenCategories($catId);
- $list = "<ul id='catList' style='list-style:none'>";
- $i = 0;
- foreach ($allCategories as $category) {
- $list .= "
- <li class='catCheck d-flex w-100 justify-content-between '><label for='catCheck$i' >$category[name]</label><input type='checkbox' class='check-cat' value='$category[id]' id='catCheck$i'></li>";
- $i++;
- }
- $list .= "
- </ul>";
- return $list;
- }
- public function form($catId, $id = "")
- {
- $cmb = $this->combobox($catId, false, $id);
- $cat = !is_numeric($catId) ? $this->getIdByNames($catId) : $catId;
- $div = <<<EOT
- <label data-lang="category" data-dir-dynamic> category</label>
- <button type="button" data-bs-toggle="modal" class="add-btn-cat" data-bs-target="#{$id}Modal">
- <i class="far fa-plus"></i>
- </button>
- <div class="form-group">
- <div class="modal fade" id="{$id}Modal" tabindex="-1" aria-labelledby="{$id}ModalLabel" aria-hidden="true">
- <div class="modal-dialog">
- <div class="modal-content">
- <div class="modal-header">
- <h5 class="modal-title" id="{$id}ModalLabel">Add item</h5>
- <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
- </div>
- <div class="modal-body">
- <div class="form">
- <h3>add</h3>
- <div class="col-lg-6 col-md-6 col-sm-12">
- <label for="{$id}">parent {$id} </label>
- <span id="{$id}Second"> $cmb</span>
- </div>
- <div class="col-lg-6 col-md-6 col-sm-12">
- <label for="{$id}Name"> name </label>
- <input type="text" id="{$id}Name" name="{$id}Name" />
- </div>
- </div>
- </div>
- <div class="modal-footer">
- <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
- <button type="button" class="btn btn-primary addCat" data-target-cat="$id"data-cat-info="$cat" id="addCat">Save</button>
- </div>
- </div>
- </div>
- </div>
- </div>
- EOT;
- return $div;
- }
- private $s = 0;
- function getChildrenCategories($catId = null, &$result = array(), $lvl = 0)
- {
- error_reporting(0);
- $q = new QueryBuilder($this->db);
- $children = $q->table('categories')->select('*')->where('ParentCategory', '<=>', $catId)->get();
- ($parent = $this->getById($catId));
- if ($parent) {
- $result[] = $parent;
- }
- foreach ($children as $child) {
- $child['name'] = str_repeat('-', $lvl) . $child['name'];
- //$result[] = $child;
- // echo $child['name'] . "\n";
- // $i = array_search($child, $result);
- //echo $i;
- array_push($result, $lvl);
- $this->getChildrenCategories($child['id'], $result, $lvl + 1);
- }
- return $result;
- }
- function getById($catId)
- {
- $q = new QueryBuilder($this->db);
- return $q->table('categories')->select('*')->where('id', '=', $catId)->get()[0];
- }
- public function alreadyExist(string $name, $parentId = null)
- {
- $q = new QueryBuilder($this->db);
- $res = $q->table('categories')->select("*")->where('name', '=', $name, $q::AND)->where("ParentCategory", "<=>", $parentId)->get();
- return count($res) > 0; //@todo:implement this method
- }
- public static function GetPostCategories($id, $table, Database $db)
- {
- $q = new QueryBuilder($db);
- $s = $q->table("postcategories")->select("*")->where('tragetTable', "=", $table)->where('targetPost', "=", $id)->get();
- $cat = [];
- for ($i = 0; $i < count($s); $i++) {
- $cat[$i] = (string)$s[$i]['catId'];
- }
- return json_encode($cat);
- }
- public function getPrimeCategoryByName($name)
- {
- $q = new QueryBuilder($this->db);
- $res = $q->table("categories")->select("*")->where("name", '=', $name)->limit(1)->get()[0];
- return isset($res["id"]) ? $res['id'] : false;
- }
- public function getIdByNames($name)
- {
- return self::getIdByName($name, $this->db);
- }
- public static function getIdByName($name, Database $db)
- {
- $q = new QueryBuilder($db);
- $res = $q->table("categories")->select("*")->where("name", '=', $name)->limit(1)->get();
- return isset($res[0]["id"]) ? $res[0]["id"] : "false";
- }
- }