Can Someone Explain me the below Code? - php

Now my question is:
1) what the use of Order.php and why he create? and how can i store the Refrence of $order with the Object?
2) And please describe the code(i know the comment is already there but i need help )
Now Main.php:
<?php
include("Order.php");
include("connect.php");
$query="SELECT * FROM `orders`";
$filter_Result=mysqli_query($con,$query);
$newOrders=Array();
$items = array();
while($row=mysqli_fetch_array($filter_Result))
{
$order;
$orderId= $row['id']; //fetch row id
echo "hello".$orderId;
if(in_array($orderId,$newOrders,true)){
//we already created an array object for this id..use it
$order=<get order object from $newOrders for which id is $orderId>
}
else{
$order=new Order($row['id'], $row['tableId'], $row['createdDate']);
//$newOrders.AddToArray($order);
array_push($newOrders,$order);
}
$item=new Item($row['ProductId'], $row['ProductName'], $row['Quantity']);
$Order.AddItem($item);
}
foreach($order as $newOrders)
{
//create box
}
include("Modal.php");
?>
now Order.php:
<?php
class Order {
/* Member variables */
var $orderId;
var $orderTime;
var $tableNumber;
var $items = array();
function __Order($orderId, $orderTime, $tableNumber)
{
$this->$orderId = $orderId;
$this->$orderTime = $orderTime;
$this->$tableNumber = $tableNumber;
}
function AddItem($itemId, $itemName, $quantity, $personalization)
{
$item = new Item($itemId, $itemName, $quantity, $personalization);
$items[] = $item;
}
}
class Item {
var $productId;
var $productName;
var $quantity;
var $personalization;
function __Item($productId, $productName, $quantity, $personalization)
{
$this->$productId = $productId;
$this->$productName = $productName;
$this->$quantity = $quantity;
$this->$personalization = $personalization;
}
}
?>

He created the Order.php to keep the class elements external from the main code. This is cleaner code and easier to maintain.
and how can i store the Refrence of $order with the Object? You are already storing this in $newOrders?
Added comments to each line for main.php
<?php
// these includes are just bringing in code from external files. Nothing much really to say here.
include("Order.php");
include("connect.php");
//$query is just setting up the SQL query to the database for selecting all columns from a table called orders.
$query="SELECT * FROM `orders`";
//$filter_Results is just saving the query in a variable, this is used later on to fetch the data in a while loop
$filter_Result=mysqli_query($con,$query);
//$newOrders and $items = array() is just pre-defining these variables as arrays.
$newOrders=Array();
$items = array();
//As said before, we need to use a while loop to extract the data fetched from sql where `mysqli_fetch_array` is the method of retrieving the data.
while($row=mysqli_fetch_array($filter_Result))
{
$order; //Not sure what the next line is doing.. `$order;` doesn't do anything..
$orderId= $row['id']; //Saving the column name `id` as a variable $orderID
echo "hello".$orderId; //echo out the hello# where # is the orderID
//This is checking if the orderID retrieved from sql has already been placed inside the $newOrders array returning true or false.
if(in_array($orderId,$newOrders,true)){
//Some more code needs to be added here, I'm guessing you need to add in something to find the object relating to the `orderID` that already exists in `$newOrders`
$order=<get order object from $newOrders for which id is $orderId>
}
// If $orderID not in $newOrders
else{
// Create a new instance of Order class called $order
$order=new Order($row['id'], $row['tableId'], $row['createdDate']);
//Add this order to the array $newOrders
array_push($newOrders,$order);
}
// Create a new instance of the Item class called $item takinging in the columns ProductId, ProductName, Quantity
$item=new Item($row['ProductId'], $row['ProductName'], $row['Quantity']);
// Using a method from orders called AddItem (this can be found in Order.php under the order class
$Order.AddItem($item);
}
// Looping through each order inside $newOrders (although this seems wrong, should be foreach($newOrders as $order)
foreach($order as $newOrders)
{
//create box
}
/ Finally including some more code inside the Modal.php file
include("Modal.php");
?>
Order.php
<?php
// Class called Order
class Order {
// properties of the class.
var $orderId;
var $orderTime;
var $tableNumber;
var $items = array();
// Function inside the method which fills the properties upon creating a new instance the class `$order=new Order($row['id'], $row['tableId'], $row['createdDate']);`
function __Order($orderId, $orderTime, $tableNumber)
{
// Using the parameters passed to the function to fill the properties of the class
$this->$orderId = $orderId;
$this->$orderTime = $orderTime;
$this->$tableNumber = $tableNumber;
}
//Function called AddItem which takes parameters and fills an items array however this should be using $this->
function AddItem($itemId, $itemName, $quantity, $personalization)
{
$item = new Item($itemId, $itemName, $quantity, $personalization);
$items[] = $item;
}
}
// New class called Item
class Item {
// properties of the class.
var $productId;
var $productName;
var $quantity;
var $personalization;
// Same as above: Function inside the method which fills the properties upon creating a new instance the class
function __Item($productId, $productName, $quantity, $personalization)
{
$this->$productId = $productId;
$this->$productName = $productName;
$this->$quantity = $quantity;
$this->$personalization = $personalization;
}
}
?>
To answer your question:
An array of objects just means you are creating a new instance of the object and then saving the object in an array. You are already doing this with your $newOrders array. You have created a new $order (the object) and then saved it in the array $newOrders using: array_push($newOrders,$order);
Not really sure what you are asking for here? Where has this code come from? Is this a tutorial of some sort?

Related

Get product name and price from product collection

I am trying to get product(s) name and price from product collection for that I have created a custom script for test.
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('adminhtml');
$collection = $objectManager->create('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory')->create();
try {
echo $collection->addAttributeToSelect(['name','sku'])->getSelect();
} catch (Exception $exception) {
echo $exception->getMessage()."\n";
}
but when I run this script to check MySQL query I am getting below output:
SELECT `e`.* FROM `catalog_product_entity` AS `e`;
How can I get only product name and price instead of whole data?
As you're trying to get a product collection it's automatically going to get the main product entity table. It would need this in the query as a minimum as it needs the entity Id to be able to join with other tables to get the attributes required for the collection. You would not be able to retrieve your name attribute otherwise.
Note that this table is quite small and doesn't include any other attributes apart from the sku code.
If you dunp the data returned you'll see it doesn't actually grab all of the attributes, but it does need the main table.
If you have a specific need for only those two fields it would be better to use a custom query rather than a product collection.
I suggest you try this
public function getProductCollection()
{
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->setPageSize(3); // fetching only 3 products
foreach ($productCollection as $product) {
$productPrice = $product->getPrice();
$productName = $product->getName();
}
}
Try this,
<?php
namespace BRINDA\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $productCollectionFactory;
protected $categoryFactory;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
array $data = []
) {
$this->productCollectionFactory = $productCollectionFactory;
$this->categoryFactory = $categoryFactory;
parent::__construct($context, $data);
}
public function getProductCollection()
{
$collection = $this->productCollectionFactory->create();
$collection->setPageSize(3);
foreach ($collection as $product)
{
echo "<pre>";
print_r($product->getPrice());
print_r($product->getName());
}
return $collection;
}
}
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollection->create()->addAttributeToSelect('*')->load();
foreach ($collection as $product){
echo 'Name = '.$product->getName().'<br>';
echo 'Price = '.$product->getFinalPrice().'<br>';
echo 'Url = '.$product->getProductUrl().'<br>';
echo 'Image = '.$product->getImage().'<br>';
}
?>
Try This.....

How to create a class that will return an array or single item?

I am writing a class that I would like to be able to call later and have it return an array of values but it is returning only one.
I would like to be able to use my class like this. If I specify one user id new Blog([10]) then it shouldn't return an array but only one instance. If I specify more than one user id then it should return an array of items.
I am trying to create something similar to how Laravel works where you can say $posts = Posts::all(); or $posts = Post::where('id', 10)->first(); and in the first one it would return an array of all posts and in second it would return only one.
Example usage:
// Get one user's blog
$blog = new Blog([10]); // specify user ids
echo $blog->user->name; // Jane Smith
echo $blog->posts->title; // How to draw
echo $blog->posts->body; // In this post, I will teach you...
echo $blog->posts->created; // 2018-12-01
echo $blog->theme; // light/dark/other
echo $blog->is_awesome; // no
// Get blogs for users - 10, 20, 30
$blogs = new Blog([10, 20, 30]); // specify user ids
foreach ($blogs as $blog) {
echo $blog->user->name; // John Doe
echo $blog->posts->title; // 10 ways to live
echo $blog->posts->body; // Hello, in this post I will..
echo $blog->posts->created; // 2018-12-31
echo $blog->theme; // light/dark/other
echo $blog->is_awesome; // yes
}
My class
Class Blog
{
public $users;
public $posts;
public $comments;
public $theme;
public $is_awesome;
function __construct($users)
{
$this->users = new stdClass();
$this->users->id = $users; // array of ids
foreach ($this->users as $user) {
$this->user->name = self::getUsername($user->id) // John
$this->posts = self::getPosts($user->id); // array of posts
$this->comments = self::getComments($user->id); // array of comments
$this->theme = self::getTheme($user->id); // light/dark/other
if ($this->theme == 'dark') {
$this->is_awesome = 'yes';
} else {
$this->is_awesome = 'no';
}
}
}
}
I understand why you're trying to do, and since you asked another way, here it is. One of the approaches is to write a static method to retrieve yours blogs:
class Blog {
public static function fetchBlogsByIds() {
// [...]
}
// [...]
}
Then you call the method this way:
$blogs = Blog::fetchBlogsByIds(ids) {
$blogs = array();
foreach($ids as $id) {
$blogs[] = new Blog($id); // appending a new Blog entry
}
return $blogs;
}
You could also write a collection class named, for example BlogCollection and provide to it a constructor relying on an array of ids.
class BlogCollection {
// Builds the collection by the ids
function __construct(ids) {
// [...] similar implementation as fetchBlogsByIds() above
}
// [...]
}
Then you can retrieve your blogs this way:
blogs = new BlogCollection([10, 11]);
If you want to use foreach with your custom collection, you can make it implementing Traversable or Iterator.

PHP Method in Class not returning data from database

Ok this should be fairly simple.
I have a table which contains content of 3 different textboxes the method inside my class should get the content to insert into textboxes.
Example TextBoxes (TextArea) where content should be entered.
My Method
public function LoadBoxes(){
$db = DB::getInstance();
$sql = "SELECT * FROM beta_letsgocontent";
$stmnt = $db->prepare($sql);
$stmnt->execute();
$boxes = $stmnt->fetchAll();
foreach ($boxes as $box) {
$data[] = array('Low' => $box['boxLow'],
'Medium' => $box['BoxMedium'],
'High' => $box['BoxHigh']);
}
return $data;
}//function
Here is my table (image below) so data / content from table should get inserted into the textboxes.
So when I do a test on content.php where I call the class method as such:
require_once('../classes/class.content.php');
$boxes = new Contents();
$boxes->LoadBoxes();
var_dump($boxes);
I get the following back:
Problem
As can be seen the array keys get returned however the data from database is not matched to array keys or returned by the method...I am stumped and have no idea what I am doing wrong here?
Any suggestions where I am going wrong? Could it be that I am not connecting to database correctly?
However if it was a database connection error I believe I would have received an error
Please keep in mind im a student and still learning.
UPDATE
Connection Schema
class Db {
private static $instance = NULL;
private function __construct() {}
private function __clone() {}
public static function getInstance() {
if (!isset(self::$instance)) {
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
self::$instance = new PDO('mysql:host=localhost;dbname=beta', 'root', '', $pdo_options);
}
return self::$instance;
}
}
UPDATE 2
I just did the following on a test.php page which returned correct results.
require('connection.php');
function LoadBoxes(){
$db = DB::getInstance();
$sql = "SELECT * FROM beta_letsgocontent";
$stmnt = $db->prepare($sql);
$stmnt->execute();
$boxes = $stmnt->fetchAll();
foreach ($boxes as $box) {
$box[] = array('Low' => $box['BoxLow'],
'Medium' => $box['BoxMedium'],
'High' => $box['BoxHigh']);
}
return $box;
}//function
print_r(LoadBoxes());
?>
2 issues primary issues;
You're returning $data from the class but not populating a variable with the returned array.
You are var dumping the object itself.
This should work;
require_once('../classes/class.content.php');
$boxes = new Contents();
$data = $boxes->LoadBoxes();
var_dump($data);

Parameters to a class constructor function

I'm trying to adapt a class of mine that handles tags for events stored in a JSON file. You can create tags, delete them, restore them, view them, etc. In the code below for this library you can see that I retrieve the array from the file during the constructor function so I use it and manipulate it throughout my classes' functions.
class tagHandler {
private $tagsFile = "/home/thomassm/public_html/functions/php/tags.json";
private $LstTags;
private $LstReturn;
function __construct() {
$this->LstTags = array();
if(!file_exists ($this->tagsFile)){
$fHND = fopen($this->tagsFile, "w");
$tmpArray = array(array("EID","EName","EColor", "EDel"));
fwrite($fHND, json_encode($tmpArray));
fclose($fHND);
}
$encodedInput = file ($this->tagsFile);
$this->LstTags = json_decode($encodedInput[0], true);
if(!$this->LstTags) $this->LstTags = array();
}
function __destruct(){
$this->update();
}
public function update(){
$this->LstTags = array_values($this->LstTags);
$fHND = fopen($this->tagsFile, "w");
fwrite($fHND, json_encode($this->LstTags));
fclose($fHND);
//empty memory region
$this->LstTags = array();
$encodedInput = file ($this->tagsFile);
$this->LstTags = json_decode($encodedInput[0], true);
}
//More functions that use the collected array here.
I am trying to adapt the class to deal with people signed up to my events. Each event has a record in my database that will store a field for an array of males who sign up and females who sign up. I wish for the constructor class to get the arrays(s) from the record so they can be manipulated like the previous class. The issue is to get the array I have to search the DB for a record with the Event ID (EID) and that will require a variable passed to the constructor function. To make things worse, this parameter has to be able to change in a loop. For example, the page listing all the events will have to use this class in a loop going through each record, so it can retrieve the array to manipulate it and then show it in a table / fullcalendar before repeating the process to get the next event. I have put the code I have so far below. Its not complete (some variables haven't been renamed to male and female, etc) and may be completely wrong, but it will give you a base to explain from.
class signupHandler {
private $LstMaleS;
private $LstFemaleS;
private $LstReturn;
function __construct($IntEID) {
$this->LstTags = array();
$StrQuery = "SELECT MaleS, FemaleS FROM tblEvents WHERE EID = ?";
if ($statement = TF_Core::$MySQLi->DB->prepare($StrQuery)) {
$statement->bind_param('s',$IntEID);
$statement->execute ();
$results = $statement->get_result ();
}
$this->LstTags = json_decode($encodedInput[0], true);
if(!$this->LstTags) $this->LstTags = array();
}
Thanks,
Tom
function decodeNames($StrNames){
$this->LstNames = array();
$this->LstNames = json_decode($StrNames, true);
if(!$this->LstNames) $this->LstNames = array();
$this->LstNames = array_values($this->LstNames);
}
function update(){
$this->LstNames = array_values($this->LstNames);
return json_encode($this->LstNames);
}
public function addSignUp($StrNames, $StrUsername, $StrStatus){
$this->decodeNames($StrNames);
$BlnPresent = false;
for($i = 0; $i < count($this->LstNames); $i++){
if($this->LstNames[$i][0] == $StrUsername){
$this->LstNames[$i][1] = $StrStatus;
$BlnPresent = true;
}
}
if($BlnPresent == false){
array_push($this->LstNames, array($StrUsername, $StrStatus, date("Y-m-d H:i:s")));
}
return $this->update();
}
I have decided to pass the encoded JSON array to the class each time I call a function from it. Before every function it is decoded and turned into an array and at the end it is then re-encoded and returned back to the file calling it. Now I no longer have any constructor or destruct functions.

How to store the class object array value into database and retrieve theses value from the database

I am working in a class which has dynamic arrays. I need to store the results of these dynamic arrays of the class in the database.
<?php
require_once('ag.php');
class H
{
var $Voltage;
var $Number;
var $Duration;
function H($Voltage=0,$Number=0,$Duration=0)
{
$this->Voltage = $Voltage;
$this->Number = $Number;
$this->Duration = $Duration;
}}
//This will be the crossover function. Is just the average of all properties.
function avg($a,$b) {
return round(($a*2+$b*2)/2);
}
//This will be the mutation function. Just increments the property.
function inc($x)
{
return $x+1*2;
}
//This will be the fitness function. Is just the sum of all properties.
function debug($x)
{
echo "<pre style='border: 1px solid black'>";
print_r($x);
echo '</pre>';
}
//This will be the fitness function. Is just the sum of all properties.
function total($obj)
{
return $obj->Voltage*(-2) + $obj->Number*2 + $obj->Duration*1;
}
$as=array();
for($i=0;$i<$row_count;$i++)
{
$adam = new H($fa1[$i],$fb1[$i],$fcc1[$i]);
$eve = new H($fe1[$i],$ff1[$i],$fg1[$i]);
$eve1 = new H($fi1[$i],$fj1[$i],$fk1[$i]);
$ga = new GA();
echo "Input";
$ga->population = array($adam,$eve,$eve1);
debug($ga->population);
$ga->fitness_function = 'total'; //Uses the 'total' function as fitness function
$ga->num_couples = 5; //4 couples per generation (when possible)
$ga->death_rate = 0; //No kills per generation
$ga->generations = 10; //Executes 100 generations
$ga->crossover_functions = 'avg'; //Uses the 'avg' function as crossover function
$ga->mutation_function = 'inc'; //Uses the 'inc' function as mutation function
$ga->mutation_rate = 20; //10% mutation rate
$ga->evolve(); //Run
echo "BEST SELECTED POPULATION";
debug(GA::select($ga->population,'total',3)); //The best
$as=array((GA::select($ga->population,'total',3))); //The best
}
?>
$as is an array which contains the value I need to store in the database. Kindly help me in that. This $as array contains the values of $adam,$eve,$eve1 after computation.
To store an array in a database you can use the PHP serialize function
$serialized_array = serialize($as); // This can now be stored in the database
Then when you retrieve it from the database use unserialize
$back_to_array = unserialize($result_from_database); //You now have the array again
Also consider using PHP5 notation for class declarations such as declaring function and member variables as public/protected/private and using function __construct() instead of function your_class_name
<?php
//serialize and store the value into the database
//however to storing the object into the db is not good practice
$val = serialize($$as);
$sql = "insert into table_name field_name values('$val')";
//execute the query
$query = mysqli_query($connection_variable, $sql) or die('error in query');
//while retrieving use unserialize($str) function
unserialize($val);

Categories