Jump to content

Borkg85

Members
  • Posts

    17
  • Joined

  • Last visited

Everything posted by Borkg85

  1. I've finished this project, and I wanted to thank @mac_gyver for the assistance, as he helped me learn a lot throughout the process... I will post the finished code here, maybe someone will find it useful... This is the create.php $table = 'skandi'; $fields = []; $fields['sku'] = ['label' => 'SKU','validation' => ['required']]; $fields['name'] = ['label' => 'Name','validation' => ['required']]; $fields['price'] = ['label' => 'Price','validation' => ['required']]; $fields['productType'] = ['label' => 'Product Type','validation' => ['required'], 'options' => ['dvd', 'book', 'furniture']]; $fields['size'] = ['label' => 'size','validation' => ['required']]; $fields['weight'] = ['label' => 'weight','validation' => ['required']]; $fields['height'] = ['label' => 'height','validation' => ['required']]; $fields['length'] = ['label' => 'length','validation' => ['required']]; $fields['width'] = ['label' => 'width','validation' => ['required']]; //Instantiate post $product = new Post($db, $table, $fields); $post = []; // array to hold a trimmed working copy of the form data $errors = []; // array to hold user/validation errors if ($_SERVER["REQUEST_METHOD"] === "POST") { //Get raw data $json = json_decode(file_get_contents("php://input"), true); // trim all the input data at once $post = array_map('trim', $json); foreach ($fields as $field => $arr) { if (isset($arr['validation']) && is_array($arr['validation'])) { foreach ($arr['validation'] as $rule) { switch ($rule) { case 'required': if (!$post[$field]) { $errors[$field] = "{$arr['label']} is required"; } if (isset($arr['options']) && is_array($arr['options'])) { if (empty($post[$field])) { $errors[$field] = "{$arr['label']} must be one of the following: " . implode(', ', $arr['options']); } } break; } } } } if (empty($errors)) { $result = $product->create($post); if (isset($result['success']) && $result['success'] === true) { $response = [ 'success' => true, 'message' => "Created Successfully" ]; } else { $response = [ 'success' => false, 'errors' => $result['errors'] ]; } } else { $response = [ 'success' => false, 'errors' => $errors ]; } echo json_encode($response); } and the create method in post.php public function create ($data) { $set_terms = []; $params = []; foreach(array_keys($this->fields) as $field) { $set_terms[] = "`$field`=?"; $params[] = $data[$field]; } $params = array_values($params); $query = "INSERT INTO `$this->table` SET " . implode(',',$set_terms); $stmt = $this->conn->prepare($query); try { $stmt->execute($params); return ["success" => true]; } catch (PDOException $e) { if ($e->errorInfo[1] == 1062) { $errors = []; if (stripos($e->errorInfo[2] , 'sku') !== false) { $errors['sku'] = "SKU is already in use. "; } if (stripos($e->errorInfo[2] , 'name') !== false) { $errors['name'] = "Name is already in use. "; } return ["success" => false, "errors" => $errors]; } else { return ["success" => false, "errors" => ["sku" => $e->getMessage(), "name" => $e->getMessage()]]; } } }
  2. Hi, So ignoring my previous post, since I cannot find an option to delete it, however I did managed to fix the issues and make it work. I then deleted it all and am currently trying to make the tablemodel work, but I cannot seem to do so with my limited knowledge. Should I be doing the read/insert/delete methods in the tablemodel abstract class, like it was shown in the @gizmola example? abstract class Product { private $conn; protected $table; protected $primaryKeys = []; protected $uniqueKeys = []; protected $attributes = []; private $data = []; protected function getTable() { return $this->table; } protected function getPrimaryKeys() { return $this->primaryKeys; } protected function setAttributes(array $attributes) { $this->attributes = $attributes; } public function getAttributes() { return array_merge($this->primaryKeys, $this->attributes); } public function setDatabaseConnection($conn) { $this->conn = $conn; } protected function getDatabaseConnection() { if (!$this->conn) { throw new \Exception('Database Connection Uninitialized'); } return $this->getDatabaseConnection; } } or maybe something like this, only thing to note is that the productType is a column with type dvd, book, furniture with which I should connect the size, weight...? Maybe this would be one way to go about that issue and then making insert methods for dvd, book, furniture classes... public function productType(array $array) { if (isset($array)) { if (array_key_exists('size', $array)) { $this->productType = 'dvd'; } elseif (array_key_exists('weight', $array)) { $this->productType = 'book'; } elseif (array_key_exists('height', $array)) { $this->productType = 'furniture'; } } } class Post extends Product { private $conn; protected $table = 'skandi'; protected $primaryKeys = ['id']; protected $uniqueKeys = ['sku', 'name']; protected $attributes = ['price', 'productType', 'size', 'weight', 'height', 'length', 'width']; public function read(): array { $query = 'SELECT * FROM '. $this->getTable() .' ORDER BY id DESC' ; $stmt = $this->conn->prepare($query); // $stmt->execute(); $data = []; while($result = $stmt->fetchAll(PDO::FETCH_ASSOC)){ $product=new Post(); $product->setAttributes($result); $data[]=$product; } return $data; } this is the display index page, which maybe could be done by echoing this into the read method... $products = new Post($db); foreach($products->read() as $product) { echo "<table>"; echo "<tbody>"; echo "<tr class='content'>"; echo "<th> <input type='checkbox' name='checkbox[]'> </th>"; echo "<td style='visibility: hidden'></td>"; echo "<td>" . implode(',', $products->getAttributes())."</td>"; echo "</tr>"; echo "</tbody>"; echo "</table>"; } ?> Any advice, including some tutorials would be great as I am struggling to complete this task.
  3. No, that was my question/'attempt' if maybe that is the way to go at, with regards to the dropdown menu values. My mistakes mentioned before were fixed, the code you provided is of course working. My learning resources are videos and forums, and I try to make sense of that... I am open to suggestions in that regard, since i kinda find this very intriguing...
  4. I did that, however I totally omitted the fact that I need to add the parameters, and spent several hours, trying to find what is the problem, after which I just had to post here and realize the stupid mistake I made... I wanted to post before all this, if maybe adding different foreach loops is a viable solution with regards to the dropdown menu and the values included there? foreach(array_keys($this->productType) as $type) { $set_terms[] = "`$type`=?"; $params[] = $data[$type]; } And also now, my read() and delete() methods aren't functioning, due to undefined variables, I will try to solve this somehow... Thank you for the support so far, it is invaluable to me, since it's hard to find good quality instructions that help me learn and do better.
  5. With the code as is provided it outputs the following in the network tab of the console... Warning: Undefined property: Post::$fields in models\post.phpon line 55 Fatal error: Uncaught TypeError: array_keys(): Argument #1 ($array) must be of type array, null given in models\post.php:55 Stack trace: #0 models\post.php(55): array_keys(NULL) #1 api\post\create.php(127): Post-&gt;create(Array) #2 {main} thrown in models\post.phpon line 55
  6. Yes, as I was writing your suggestions, I noticed that. I will try to see, how and if I could correct this. In another note according to the task using switch is not allowed, if/else conditionals are ok, but not if used to often... Yes, I totally misunderstood that, I'm sorry.
  7. So @mac_gyver I've succeeded at putting this together in the create.php... <?php //Headers header('Access-Control-Allow-Origin: *'); header('Content-Type: application/json, true'); header('Access-Control-Allow-Methods: POST'); header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With'); include_once '../../config/database.php'; include_once '../../models/post.php'; //Instantiate db $database = new Database(); $db = $database->connect(); //Instantiate post $product = new Post($db); //Get raw data $json = json_decode(file_get_contents("php://input"), true); $post = []; $errors = []; $post = array_map('trim', $json); if ($post['sku'] === '' || $post['name'] === '' || $post['price'] === '' || $post['productType'] === '' || $post['size'] === '' || $post['weight'] === '' || $post['height'] === '' || $post['length'] === '' || $post['width'] === '') { $errors['sku'] = 'Sku is required'; $errors['name'] = 'Sku is required'; $errors['price'] = 'Sku is required'; $errors['productType'] = 'Sku is required'; $errors['size'] = 'Sku is required'; $errors['weight'] = 'Sku is required'; $errors['height'] = 'Sku is required'; $errors['length'] = 'Sku is required'; $errors['width'] = 'Sku is required'; } $product->sku = $post['sku']; $product->name = $post['name']; $product->price = $post['price']; $product->productType = $post['productType']; $product->size = $post['size']; $product->weight = $post['weight']; $product->height = $post['height']; $product->length = $post['length']; $product->width = $post['width']; if(empty($errors)){ try { $product->create(); $response = [ 'message' => "Created Successfully", 'status' => 200 ]; echo json_encode($response); } catch (\Throwable $e) { $query = "SELECT DISTINCT sku, name FROM ' . $this->table . '"; $stmt = $this->conn->prepare($query); // $stmt->execute(['sku', 'name']); if($stmt->execute(['sku']) == 1062) { $errors['sku'] = 'sku already in use'; } else if ($stmt->execute(['name']) == 1062) { $errors['name'] = 'name already in use'; } else { $response = [ 'message' => $e->getMessage() ]; echo json_encode($response); } } } //Create It doesn't give me any errors in the network tab, however when I alert the (data) in ajax I get [object, Object], so I'm guessing there is something seriously wrong. I am currently searching how to output the error messages from php through ajax... $(document).ready(function () { // $("#apiform").validate({ // rules: { // sku: { // required: { // depends:function(){ // $(this).val($.trim($(this).val())); // return true; // } // }, // minlength: 9, // }, // name: { // required: true, // maxlength: 20, // }, // price: { // required: true, // maxlength: 5, // }, // productType: { // required: true, // }, // size: { // required: true, // maxlength: 4, // }, // weight: { // required: true, // maxlength: 4, // }, // height: { // required: true, // maxlength: 3, // }, // width: { // required: true, // maxlength: 3, // }, // length: { // required: true, // maxlength: 3, // } // }, // messages: { // sku: { // required: "Please, enter valid SKU", // minlength: "Please enter at least 9 characters" // }, // name: { // required: "Please, enter valid name", // maxlength: "Please enter " // }, // price: { // required: "Please, enter price", // maxlength: "" // }, // productType: { // required: "Please select an option from the list", // }, // size: { // required: "Please, provide the size of the DVD", // maxlength: "" // }, // weight: { // required: "Please, provide the weight", // maxlength: "" // }, // height: { // required: "Please, provide the required dimension", // maxlength: "" // }, // width: { // required: "Please, provide the required dimension", // maxlength: "" // }, // length: { // required: "Please, provide the required dimension", // maxlength: "" // } // } // }); $("#saveBtn").click(function (e) { e.preventDefault(); if (!$("#apiform").valid()) { return false } else { //serialize form data var url = $("form").serialize(); //function to turn url to an object function getUrlVars(url) { var hash; var myJson = {}; var hashes = url.slice(url.indexOf("?") + 1).split("&"); for (var i = 0; i < hashes.length; i++) { hash = hashes[i].split("="); myJson[hash[0]] = hash[1]; } return JSON.stringify(myJson); } //pass serialized data to function var test = getUrlVars(url); //post with ajax $.ajax({ type: "POST", url: "/api/post/create.php", data: test, contentType: "application/json; charset=UTF-8", success: function (data) { // location.reload(); alert("successfully posted"); }, error: function (data) { alert("SKU and or Name already exists"); }, }); }; }); });
  8. Elaborate, if you will... I would like to know what should I be doing differently, so I can improve the code and of course learn.
  9. So I've managed to do some changes and I will post the code... post.class for now with only the read option... class Post { //DB private $conn; private $table = 'skandi'; //Properties public function __construct($db) { $this->conn = $db; } public function read() { $query = 'SELECT p.id as id, p.sku, p.name, p.price, p.productType, p.size, p.weight, p.height, p.length, p.width FROM '. $this->table .' p ORDER BY p.id DESC'; $stmt = $this->conn->prepare($query); $stmt->execute(); return $stmt; } product.class, I would like to use the productType == 'dvd, book or furniture' to display the values only when there is one in the product show class, however I cannot be using if/else conditionals... I could do separate methods like getDVD(), getBook(), instead of the getproductType(), might be more manageable... abstract class Product { private $sku; private $name; protected $price; protected $productType; public function __construct($sku, $name, $price) { $this->sku = $sku; $this->name = $name; $this->price = $price; // $this->productType = $productType; } public function setSku($sku) { $this->sku = $sku; } public function getSku() { $this->sku; } public function setName($name) { $this->name = $name; } public function getName() { $this->name; } public function setPrice($price) { $this->price = $price; } public function getPrice() { return '$this->price $'; } public function getproductType(){ } } interface HaveSize { public function getSize(); } trait Withsize { public function setSize($size) { $this->size = $size; } public function getSize() { $this->size; } function getproductType() { return "$this->size KG"; } } interface HaveWeight { public function getWeight(); } trait WithWeight { public function setWeight($weight) { $this->weight = $weight; } public function getWeight() { $this->weight; } function getproductType() { return "$this->weight KG"; } } interface HaveFurniture { public function getHeight(); public function getLength(); public function getWidth(); } trait WithFurniture { public function setHeight($height) { $this->height = $height; } public function setLength($length) { $this->length = $length; } public function setWidth($width) { $this->width = $width; } public function getHeight() { $this->height; } public function getLength() { $this->length; } public function getWidth() { $this->width; } function getproductType() { return "$this->height CM x $this->length CM x $this->width CM"; } } one of the producttype classes... class DVD extends Product implements HaveSize { private $size; public function __construct($sku, $name, $price, $size) { parent::__construct($sku, $name, $price); $this->size = $size; } use Withsize; } the productshow.class class ProductShow extends Post { public function showAllProducts(){ $allProducts = array(); $stmt = $this->read(); foreach($stmt as $result){ $book = new Book($result['sku'], $result['name'], $result['price'], $result['weight']); array_push($allProducts, $book); } $stmt = $this->read(); foreach($stmt as $result){ $dvd = new Dvd($result['sku'], $result['name'], $result['price'], $result['size']); array_push($allProducts, $dvd); } $stmt = $this->read(); foreach($stmt as $result){ $furniture = new Fur($result['sku'], $result['name'], $result['price'], $result['height'], $result['width'], $result['length']); array_push($allProducts, $furniture); } foreach($allProducts as $product){ echo "<table> <tbody> <tr class='content'> <th> <input type='checkbox' name='checkbox[]' > </th> <td>" .$product->getSku(). "</td> <td>" .$product->getName(). "</td> <td>" .$product->getPrice(). "</td> <td>" .$product->getproductType(). "</td> <td>" .$product->getproductType(). "</td> <td>" .$product->getproductType(). "</td> </tr> </tbody> </table>"; } } } and the result that I'm getting is presented in the image...
  10. Hi, sorry for my late input, I am also trying to do the same task as a simple php rest api using ajax and javascript. Thank you all for the helpful advices, since it really gives me an insight trying to make sense of the OOP principles, classes, abstract, setters, getters, inheritance, polymorphism, and this is a test task for a job that I applied that needs to be done with OOP. The interfaces and traits were connected to 3 different classes, that should have get all the values and list them in an index.php table. However with this current setup that won't work, since the functions and certain properties don't make sense and are just badly written. I definitively will be trying to make this work in the coming days...
  11. Hi @mac_gyver I placed the data from json into an array, and that seems to have solved the issue, since it is printing success message and status: 200; Although not completely sure why, and the same principle doesn't work for the delete.php, but I won't bother you with that. Here is the corrected code... <?php //Headers header('Access-Control-Allow-Origin: *'); header('Content-Type: application/x-www-form-urlencoded'); header('Access-Control-Allow-Methods: POST'); header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With'); include_once '../../config/database.php'; include_once '../../models/post.php'; //Instantiate db $database = new Database(); $db = $database->connect(); //Instantiate post $product = new Post($db); //Get raw data $json = json_decode(file_get_contents("php://input")); $data = []; if(isset($json)) { $data = [ 'sku' => $json->sku, 'name' => $json->name, 'price' => $json->price, 'productType' => $json->productType, 'size' => $json->size, 'weight' => $json->weight, 'height' => $json->height, 'width' => $json->width, 'length' => $json->length, ]; } else { echo json_encode(array('message' => 'Error')); exit(); } $product->sku = $data['sku']; $product->name = $data['name']; $product->price = $data['price']; $product->productType = $data['productType']; $product->size = $data['size']; $product->weight = $data['weight']; $product->height = $data['height']; $product->length = $data['length']; $product->width = $data['width']; //Create try { $product->create(); $response = [ 'message' => "Created Successfully", 'status' => 200 ]; echo json_encode($response); } catch (\Throwable $e) { $response = [ 'message' => $e->getMessage() ]; echo json_encode($response); } With regards to the example, where should I incorporate this, create another class/validate.php file which would be somehow connected with the post.php. With regards to the error messages placement, could they be somehow connected with the jquery.validate, since my form is in a .html file... Here it is... <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js" type="text/javascript"></script> <script src="ajaxCall.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script> <link rel="stylesheet" href="style.css" /> <head> <body> <header> <h2>Product List</h2> <nav> <button class="add-btn" id="saveBtn" type="submit" name="save" value='save' form="apiform">Save</button> <button id="cancelBtn" action="action" type="button" value="Cancel" onclick="location.href='ajaxCall.html'" > CANCEL </button> </nav> </header> <section> <section class="product-form"> <form id="apiform" name="apiform"> <div class="input-data"> <label id="sku-label" for="sku">SKU</label> <input type="text" name="sku" id="sku" class="form-control" placeholder="#sku" autocomplete="on"/> <div class="input-data"> <label id="name-label" for="name">Name </label> <input type="text" name="name" id="name" class="form-control" placeholder="#name" autocomplete="on" /> </div> <div class="input-data"> <label id="price-label" for="price">Price ($)</label> <input type="number" name="price" id="price" class="form-control" placeholder="#price" autocomplete="on" /> </div> <div class="input-switcher"> <label for="productType">Type Switcher</label> <select id="productType" name="productType" value="productType" onchange="selectChanged()" > <option value="" style="visibility: hidden;">Please select</option> <option value="dvd">DVD</option> <option value="book">Book</option> <option value="furniture">Furniture</option> </select> </div> <div id="dvd"> <div class="data-input product"> <label for="size">Size (MB):</label> <input type="number" id="size" name="size" class="form-control " autocomplete="on"> <p class="describe">Please provide size in (MB)</p> </div> </div> <div id="book"> <div class="data-input product"> <label for="weight">Weight (KG):</label> <input type="number" id="weight" name="weight" class="form-control " autocomplete="on"> <p class="describe">Please provide weight in KG</p> </div> </div> <div id="furniture"> <div class="data-input product"> <label for="height">Height (CM):</label> <input type="number" id="height" name="height" class="form-control " autocomplete="on"> <p class="describe">Please provide measurements in (CM)</p> </div> <div class="data-input product"> <label for="length">Length (CM):</label> <input type="number" id="length" name="length" class="form-control" autocomplete="on"> <p class="describe">Please provide measurements in (CM)</p> </div> <div class="data-input product"> <label for="width">Width (CM):</label> <input type="number" id="width" name="width" class="form-control " autocomplete="on"> <p class="describe">Please provide measurements in (CM)</p> </div> </div> </form> </section> <script text="type/javascript"> function selectChanged() { var sel = document.getElementById("productType"); let dvd = document.getElementById("dvd"); let book = document.getElementById("book"); let furniture = document.getElementById("furniture"); for (var i = 1; i < 4; i++) { dvd.style.display = sel.value == "dvd" ? "block" : "none"; book.style.display = sel.value == "book" ? "block" : "none"; furniture.style.display = sel.value == "furniture" ? "block" : "none"; } } </script> Cannot be thankful enough for the help so far...
  12. Hi, thanks to everyone for the support so far. I have succeeded in solving the jquery/ajax validate/post data with a trim value example that I found in the stackoverflow forums, I don't know if its valid, and I would like to do it better in PHP, as well as the setting of the sku and name as unique constraints and try/catching them... It is working although the JSON does report that Product is not created, but it does appear in the database. I don't know what's causing this. Also I wanted to ask @mac_gyver if you could point me to some materials so I could better understand the trim and validate server side before using. the post.php for the create function... public function create () { try { $query = 'INSERT INTO ' . $this->table . ' SET sku = :sku, name = :name, price = :price, productType = :productType, size = :size, weight = :weight, height = :height, length = :length, width = :width'; $stmt = $this->conn->prepare($query); $stmt->bindParam(':sku', $this->sku); $stmt->bindParam(':name', $this->name); $stmt->bindParam(':price', $this->price); $stmt->bindParam(':productType', $this->productType); $stmt->bindParam(':size', $this->size); $stmt->bindParam(':weight', $this->weight); $stmt->bindParam(':height', $this->height); $stmt->bindParam(':length', $this->length); $stmt->bindParam(':width', $this->width); $stmt->execute(); } catch (PDOException $e) { if(str_contains($e, '1062 Duplicate Entry')) { // header('Location: ajaxProd.html'); } { echo $e->getMessage(); } } } the create.php... <?php //Headers header('Access-Control-Allow-Origin: *'); header('Content-Type: application/json'); header('Access-Control-Allow-Methods: POST'); include_once '../../config/database.php'; include_once '../../models/post.php'; //Instantiate db $database = new Database(); $db = $database->connect(); //Instantiate post $product = new Post($db); //Get raw data $data = json_decode(file_get_contents("php://input")); $product->sku = $data->sku; $product->name = $data->name; $product->price = $data->price; $product->productType = $data->productType; $product->size = $data->size; $product->weight = $data->weight; $product->height = $data->height; $product->length = $data->length; $product->width = $data->width; //Create if($product->create()) { echo json_encode( array('message' => 'Product Created') ); } else { echo json_encode( array('message' => 'Product Not Created') ); } and last the ajax/jquery validate/post... $(document).ready(function () { $("#apiform").validate({ rules: { sku: { required: { depends:function(){ $(this).val($.trim($(this).val())); return true; } }, minlength: 9, }, name: { required: true, maxlength: 20, }, price: { required: true, maxlength: 5, }, productType: { required: true, }, size: { required: true, maxlength: 4, }, weight: { required: true, maxlength: 4, }, height: { required: true, maxlength: 3, }, width: { required: true, maxlength: 3, }, length: { required: true, maxlength: 3, } }, messages: { sku: { required: "Please, enter valid SKU", minlength: "Please enter at least 9 characters" }, name: { required: "Please, enter valid name", maxlength: "Please enter " }, price: { required: "Please, enter price", maxlength: "" }, productType: { required: "Please select an option from the list", }, size: { required: "Please, provide the size of the DVD", maxlength: "" }, weight: { required: "Please, provide the weight", maxlength: "" }, height: { required: "Please, provide the required dimension", maxlength: "" }, width: { required: "Please, provide the required dimension", maxlength: "" }, length: { required: "Please, provide the required dimension", maxlength: "" } } }); $("#saveBtn").click(function (e) { e.preventDefault(); if (!$("#apiform").valid()) { return false } else { //serialize form data var url = $("form").serialize(); //function to turn url to an object function getUrlVars(url) { var hash; var myJson = {}; var hashes = url.slice(url.indexOf("?") + 1).split("&"); for (var i = 0; i < hashes.length; i++) { hash = hashes[i].split("="); myJson[hash[0]] = hash[1]; } return JSON.stringify(myJson); } //pass serialized data to function var test = getUrlVars(url); //post with ajax $.ajax({ type: "POST", url: "/api/post/create.php", data: test, ContentType: "application/json", success: function () { alert("successfully posted"); }, error: function () { alert("SKU and or Name already exists"); }, }); }; }); });
  13. Hi, first off thanks for the great insights, since I am in a learning stage they are very welcomed... I attempted with the COUNT (*) query, however I guess I am doing something wrong, because it's duplicating existing data. With regards to the validation, I was thinking of doing jQuery validation for required inputs, before posting. I will provide the changes here, I cannot seem to find edit option in my original post so I don't have to double post code... public function create () { try { $query = 'SELECT COUNT(*) FROM ' . $this->table . ' WHERE sku = "$this->sku"'; $stmt = $this->conn->prepare($query); // $stmt->bindParam(':sku', $this->sku); $stmt->execute(); $data = $stmt->fetch(PDO::FETCH_COLUMN); if ($data > 0) { throw new Exception('SKU already exists'); } $query = 'INSERT INTO ' . $this->table . ' SET sku = :sku, name = :name, price = :price, productType = :productType, size = :size, weight = :weight, height = :height, length = :length, width = :width'; $stmt = $this->conn->prepare($query); $stmt->bindParam(':sku', $this->sku); $stmt->bindParam(':name', $this->name); $stmt->bindParam(':price', $this->price); $stmt->bindParam(':productType', $this->productType); $stmt->bindParam(':size', $this->size); $stmt->bindParam(':weight', $this->weight); $stmt->bindParam(':height', $this->height); $stmt->bindParam(':length', $this->length); $stmt->bindParam(':width', $this->width); if($stmt->execute()) { return true; } } catch (PDOException $e) { echo $e->getMessage(); } }
  14. Hi, quite new to the PHP OOP principles, and am working on a task that requires implementing classes, abstract classes, setters/getters... So I have the products.class with the setters and functions and another product.abstract class with the getters and the reason for this is cause of a third process.class that should insert data into database. Is there a way for this to be done a bit more compact. Any tip or trick would be appreciated. Thanks... Here is the code... class Products extends Dbh { private $sku; private $name; private $price; private $size; private $weight; private $height; private $length; private $width; public function __construct($id = 0, $sku = "", $name = "", $price = "", $size = "", $weight = "", $height = "", $length = "", $width = "") { $this->id = $id; $this->sku = $sku; $this->name = $name; $this->price = $price; $this->size = $size; $this->weight = $weight; $this->height = $height; $this->length = $length; $this->width = $width; } public function setSku($sku) { $this->sku = $sku; } public function setName($name) { $this->name = $name; } public function setPrice($price) { $this->price = $price; } public function setSize($size) { $this->size = $size; } public function setWeight($weight) { $this->weight = $weight; } public function setHeight($height) { $this->height = $height; } public function setLength($length) { $this->length = $length; } public function setWidth($width) { $this->width = $width; } public function setId($id) { $this->id = $id; } public function getBook() { try { $stmt = $this->connect()->prepare('SELECT * FROM skandi WHERE weight != 0'); $stmt->execute(); $results = $stmt->fetchAll(); return $results; } catch (Exception $e) { return $e->getMessage(); } } public function getDVD() { try { $stmt = $this->connect()->prepare('SELECT * FROM skandi WHERE size != 0'); $stmt->execute(); $results = $stmt->fetchAll(); return $results; } catch (Exception $e) { return $e->getMessage(); } } public function getFur() { try { $stmt = $this->connect()->prepare('SELECT * FROM skandi WHERE height != 0'); $stmt->execute(); $results = $stmt->fetchAll(); return $results; } catch (Exception $e) { return $e->getMessage(); } } public function insertData() { try { $stmt = $this->connect()->prepare("INSERT INTO skandi(sku, name, price, size, weight, height, length, width) VALUES(?,?,?,?,?,?,?,?)"); $stmt->execute([$this->sku, $this->name, $this->price, $this->size, $this->weight, $this->height, $this->length, $this->width]); } catch (Exception $e) { return $e->getMessage(); } } public function fetchAll() { try { $stmt = $this->connect()->prepare("SELECT * FROM skandi"); $stmt->execute(); return $stmt->fetchAll(); } catch (Exception $e) { return $e->getMessage(); } } public function delete() { try { $stmt = $this->connect()->prepare("DELETE FROM skandi WHERE id = ?"); $stmt->execute([$this->id]); return $stmt->fetchAll(); } catch (Exception $e) { return $e->getMessage(); } } public function checkItemExists() { try { $stmt = $this->connect()->prepare("SELECT * FROM skandi WHERE sku = ?"); $stmt->execute([$this->sku]); $result = $stmt->fetchAll(); if(count($result) == 0) { return false; } else { return true; } }catch (Exception $e) { return $e->getMessage(); } } } the abstract class abstract class Product { private $sku; private $name; private $price; public function getSku() { return $this->sku; } public function getName() { return $this->name; } public function getPrice() { return $this->price; } abstract function getAttributes(); } interface HaveSize { public function getSize(); } trait Withsize { public function getSize() { $this->size; } function getAttributes() { return "$this->size KG"; } } interface HaveWeight { public function getWeight(); } trait WithWeight { public function getWeight() { $this->weight; } function getAttributes() { return "$this->weight KG"; } the process class.. $products = new Products; if (isset($_POST['submit'])) { $products->setSku($_POST['sku']); $products->setName($_POST['name']); $products->setPrice($_POST['price']); $products->setSize(!empty($_POST['size'])) ? $_POST['size'] : NULL; $products->setWeight(!empty($_POST['weight'])) ? $_POST['weight'] : NULL; $products->setHeight(!empty($_POST['height'])) ? $_POST['height'] : NULL; $products->setLength(!empty($_POST['length'])) ? $_POST['length'] : NULL; $products->setWidth(!empty($_POST['width'])) ? $_POST['width'] : NULL; $products->insertData(); }
  15. Hi, Because I am in a learning stage, do I catch the duplicate error in ajax or in the post php and relay message via ajax?
  16. Hi, This is a simple REST API for listing, creating and deleting products in/from database. I am having issues with validating/checking if certain values duplicate or if certain input field is not filled... I've attempted doing that with rowCount for the duplicate, in the php file, however I think there must be a better way for this, however I am having issues finding out how to do that... here is the post.php $query_check = 'SELECT * FROM skandi WHERE sku = :sku'; $stmt_check = $this->conn->prepare($query_check); $stmt_check->bindParam(':sku', $this->sku); $stmt_check->execute(); if ($stmt_check->rowCount() > 0) { echo 'product name already exists!'; } else { $query = 'INSERT INTO ' . $this->table . ' SET sku = :sku, name = :name, price = :price, productType = :productType, size = :size, weight = :weight, height = :height, length = :length, width = :width'; $stmt = $this->conn->prepare($query); $this->sku; $this->name; $this->price; $this->productType; $this->size; $this->weight; $this->height; $this->length; $this->width; $stmt->bindParam(':sku', $this->sku); $stmt->bindParam(':name', $this->name); $stmt->bindParam(':price', $this->price); $stmt->bindParam(':productType', $this->productType); $stmt->bindParam(':size', $this->size); $stmt->bindParam(':weight', $this->weight); $stmt->bindParam(':height', $this->height); $stmt->bindParam(':length', $this->length); $stmt->bindParam(':width', $this->width); if($stmt->execute()) { return true; } else { ini_set('display_errors',1); return false; } } this is the ajaxcall for posting... $(document).ready(function () { $("#saveBtn").click(function (e) { e.preventDefault(); //serialize form data var url = $("form").serialize(); //function to turn url to an object function getUrlVars(url) { var hash; var myJson = {}; var hashes = url.slice(url.indexOf("?") + 1).split("&"); for (var i = 0; i < hashes.length; i++) { hash = hashes[i].split("="); myJson[hash[0]] = hash[1]; } return JSON.stringify(myJson); } //pass serialized data to function var test = getUrlVars(url); //post with ajax $.ajax({ type: "POST", url: "/api/post/create.php", data: test, ContentType: "application/json", success: function () { alert("successfully posted"); }, error: function () { console.log("Could not be posted"); }, }); }); }); Any assistance, suggestion will be welcomed, thanks...
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.