Actually after fetching the data from the Database, i want to create a new Object and insert this object to the array but when i check the array it shows the NULL value
here is my code:
<?php
$query = "sql query";
$filter_Result = mysqli_query($con, $query);
$newOrders = Array();
while ($row = mysqli_fetch_array($filter_Result)) {
$order;
$orderId = $row['order_id']; //fetch row id
$temp = check_id($newOrders, $orderId);
if ($temp != null) {
$order = $temp;
} else {
echo " <br>";
$order = new Order($row['order_id'], $row['status'], $row['created_Date']);
$newOrders[] = $order;
}
$item = new Item($row['status'], $row['quantity']);
$order->AddItem($item, null);
}
function check_id($newOrders, $orderId) {
$length = count($newOrders);
for ($i = 0; $i < $length; $i++) {
if ($newOrders[$i]->$orderId == $orderId)
return $newOrders[$i];
}
return null;
}
foreach ($newOrders as $order) {
}
?>
You have a variable in your Order class
var $order_Id;
But then you try to assign value to $orderId which does not exist
$this->orderId = $orderId;
I would suggest turning all PHP errors on while developing. You can include this in your php code to see if you get any errors. It is very hard to see all the small errors with naked eye :) Let PHP do it for you.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
More about error reporting here.
You have several small mistakes, e.g. using "this" incorrectly, using different name for "orderId", plus a wrong name for the constructors. The constructor name should be "Order" or "__construct", same for "Item" constructor.
class Order {
/* Member variables */
var $orderId;
var $status;
var $createdDate;
var $items = array();
function Order($orderId, $status, $createdDate)
{
$this->orderId = $orderId;
$this->status = $status;
$this->createdDate = $createdDate;
}
function AddItem($itemId,$quantity)
{
$item = new Item($itemId,$quantity);
$items[] = $item;
}
}
$c = new Order(1, 'OK', 'today');
print_r($c);
Now i found the Solution in the PHP we have to use __construct() for the creating a Constructor....
So use it __construct instead of class name for more info visit:
__construct() vs SameAsClassName() for constructor in PHP
new_order.php
<?php
class Order {
/* Member variables */
var $order_Id;
var $status;
var $createdDate;
var $items = array();
function __Order($order_Id, $status, $createdDate)
{
$this->order_Id = $order_Id;
$this->status = $status;
$this->createdDate = $createdDate;
}
function AddItem($itemId,$quantity)
{
$item = new Item($itemId,$quantity);
$items[] = $item;
}
}
class Item {
var $productId;
var $productName;
var $quantity;
var $personalization;
function __Item($productId, $quantity)
{
$this->productId = $productId;
$this->productName = $productName;
$this->quantity = $quantity;
$this->personalization = $personalization;
}
}
?>
Related
I have a database phpmyadmin, I created a class :
<?php
class Ticket
{
private $NumDossier = 0;
private $NomTicket ="";
private $Service = "" ;
private $Impact = 0;
private $Urgence = "";
private $DateOuverture = "";
public function __construct($p_NumDossier, $p_NomTicket,$p_Service,$p_Impact,$p_Urgence,$p_DateOuverture)
{
$this->NumDossier = $p_NumDossier;
$this->NomTicket = $p_NomTicket;
$this->Service = $p_Service;
$this->Impact = $p_Impact;
$this->Urgence = $p_Urgence;
$this->DateOuverture = $p_DateOuverture;
}
public function getNumDossier()
{
return $this->NumDossier;
}
public function getNomTicket()
{
return $this->NomTicket;
}
public function getService()
{
return $this->Service;
}
public function getImpact()
{
return $this->Impact;
}public function getUrgence()
{
return $this->Urgence;
}
public function getDateOuverture()
{
return $this->DateOuverture;
}
}
?>
For all row that my query return I want to create an object and add it to a collection.
My code :
$connexion = cnx();
if($connexion) {
$requete="SELECT * FROM ticket '";
$result = mysqli_query($connexion, $requete);
$result = mysqli_query($connexion, $requete);
$row = mysqli_fetch_assoc($result);
}
$test = new Ticket(0,"","",0,"","");
while($row) {
//create object for each line and add it to an collection
}
If you have a solution/lead me to this issue.
Thanks for read !
I have to assume that the beginning part of your code is correct, so I copied that. But I changed it further on. You want to retrieve multiple rows, so I put the mysqli_fetch_assoc inside the while loop. With each new row I create a new ticket and put it in a 'collection' array.
$connection = cnx();
if ($connexion) {
$query ="SELECT * FROM ticket";
$result = mysqli_query($connection, $query);
if ($result === false) die("The query [$query] could not be executed.");
$collection = [];
while($row = mysqli_fetch_assoc($result)) {
$collection[] = new Ticket($row["NumDossier"],
$row["NomTicket"],
$row["Service"],
$row["Impact"],
$row["Urgence"],
$row["DateOuverture"]);
}
echo "<pre>";
print_r($collection);
echo "</pre>";
}
So I used a simple array for the collection. I used the default numeric array indexing because I wouldn't know what to replace it with. $row["NomTicket"] seems a logical choice.
This is the page where i call the object
<?php
$orderno = new order();
$orderno->order_no();
?>
This is the page where I created my class
class order extends db
{
function order_no()
{
$auto_gen = mysqli_query($this->connection,"SELECT MAX(Order_No) AS order_number FROM o_master");
$orderno = mysqli_fetch_array($auto_gen);
$get_orderno = $orderno['order_number'];
$prefix ="";
if($get_orderno == "")
{
$prefix = "A0001";
return $prefix;
}
else
{
$char ="A000";
$number = mysqli_query($this->connection,"SELECT MAX(Order_ID) AS order_number FROM o_master");
$o_id = mysqli_fetch_array($number);
$o_no = $o_id['order_number'];
$get_no = $o_no + 1;
$prefix = $char.$get_no;
return $prefix;
}
}
}
I am implementing a genetic algorithm. I take the classes from here,
but I don't understand how to give input to these classes. I have dynamic inputs. I have three inputs that need to be optimized. If any one knows kindly provide me the guidelines.
Here is the code
<?php
class GA {
var $population; //Objects array (same classes)
var $fitness_function; //The fitness function name (string)
var $crossover_functions; //The crossover function name (string) or array
var $mutation_function; //The mutation function name (string)
var $mutation_rate; //Mutation rate per child (%)
var $generations; //Number of generations
var $num_couples; //Number of couples for each generation
var $death_rate; //Number of killed objects for each generation
function crossover($parent1,$parent2,$cross_functions)
{
$class = get_class($parent1);
if ($class != get_class($parent2))
return false;
if (!is_array($cross_functions)) {
$cross_function = $cross_functions;
$cross_functions = array();
}
$child = new $class();
$properties = get_object_vars($parent1);
foreach ($properties as $propertie => $value)
{
if ($cross_function) $cross_functions[$propertie] = $cross_function;
if (function_exists($cross_functions[$propertie]))
$child->$propertie = $cross_functions[$propertie]($parent1->$propertie,$parent2->$propertie);
}
return $child;
}
function mutate(&$object,$mutation_function) {
$properties = get_object_vars($object);
foreach ($properties as $propertie => $value) {
$object->$propertie = $mutation_function($object->$propertie);
}
}
function fitness($object,$fitness_function) {
return $fitness_function($object);
}
//PRIVATE
function best($a, $b) {
if ($a[1] == $b[1]) return 0;
return ($a[1] < $b[1]) ? 1 : -1;
}
function select($objects,$fitness_function,$n=2) {
foreach ($objects as $object) {
$selection[] = array($object,$fitness_function($object));
}
usort($selection,array("GA", "best"));
$selection = array_slice($selection,0,$n);
foreach ($selection as $selected) {
$winners[] = $selected[0];
}
return $winners;
}
//PRIVATE
function worst($a, $b) {
if ($a[1] == $b[1]) return 0;
return ($a[1] < $b[1]) ? -1 : 1;
}
function kill(&$objects,$fitness_function,$n=2) {
foreach ($objects as $object) {
$selection[] = array($object,$fitness_function($object));
}
usort($selection,array("GA", "worst"));
$selection = array_slice($selection,0,count($selection)-$n);
$objects = array();
foreach ($selection as $selected) {
$objects[] = $selected[0];
}
}
//PRIVATE
function mass_crossover($objects,$cross_functions) {
foreach ($objects as $object) {
if (!$obj1) $obj1 = $object;
else {
$children[] = $this->crossover($obj1,$object,$this->crossover_functions);
$obj1 = null;
}
}
return $children;
}
//PRIVATE
function mass_mutation(&$objects) {
foreach($objects as $key => $object) {
if (rand(1,100) <= $this->mutation_rate) $this->mutate($objects[$key],$this->mutation_function);
}
}
function evolve() {
for ($i=0;$i<$this->generations;$i++) {
$couples = $this->select($this->population,$this->fitness_function,2*min($this->num_couples,floor(count($this->population)/2)));
$children = $this->mass_crossover($couples,$this->crossover_functions);
$this->mass_mutation($children);
$this->population = array_merge($this->population,$children);
$this->kill($this->population,$this->fitness_function,min($this->death_rate,count($this->population)-2));
}
}
}
?>
here gaexample2.php
<?php
require_once('ga.php');
class Human {
var $strength;
var $dexterity;
var $resistance;
var $intelligence;
function Human($strength=0,$dexterity=0,$resistance=0,$intelligence=0)
{
$this->strength = $strength;
$this->dexterity = $dexterity;
$this->resistance = $resistance;
$this->intelligence = $intelligence;
}
}
function debug($x) {
echo "<pre style='border: 1px solid black'>";
print_r($x);
echo '</pre>';
}
//This will be the mutation function. Just increments the property.
function inc($x) {
return $x+1;
}
//This will be the crossover function. Is just the average of all properties.
function avg($a,$b) {
return round(($a+$b)/2);
}
//This will be the fitness function. Is just the sum of all properties.
function total($obj) {
return $obj->strength + $obj->dexterity + $obj->resistance + $obj->intelligence;
}
$adam = new Human(4,2,3,1);
$eve = new Human(1,4,2,3);
$ga = new GA();
$ga->population = array($adam,$eve);
debug($ga->population);
$ga->fitness_function = 'total'; //Uses the 'total' function as fitness function
$ga->num_couples = 1; //4 couples per generation (when possible)
$ga->death_rate = 0; //No kills per generation
$ga->generations = 100; //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 = 10; //10% mutation rate
$ga->evolve(); //Run
debug($ga->population);
debug(GA::select($ga->population,'total',1)); //The best
?>
can someone help in showing the sepearte outputs of every step
The way to send values to a class is using the constructor of the class in which you can retrieve the parameters and assign it to the class variables.
Read more about constructors here.
It would be something like:
class GA {
var $population; //Objects array (same classes)
var $fitness_function; //The fitness function name (string)
var $crossover_functions; //The crossover function name (string) or array
var $mutation_function; //The mutation function name (string)
var $mutation_rate; //Mutation rate per child (%)
var $generations; //Number of generations
var $num_couples; //Number of couples for each generation
var $death_rate; //Number of killed objects for each generation
//$params would be the array of params to receive
function __construct($params) {
$this->population = $params['population'];
$this->fitness_function = $params['fitness_function'];
...
}
...
}
Here is the php code.In this code station name and ids and random passengers are produced.
<?php
include_once('RestUtils.php');
include_once('Passengers.php');
class Station implements JsonSerializable
{
private $id;
private $name;
private $passengers;
public function __construct($id, $name)
{
$this->setId($id);
$this->setName($name);
$this->passengers = array();
}
//getters and setters
public function jsonSerialize()
{
$data = array();
$data['id'] = $this->id;
$data['name'] = $this->name;
$data['passengers'] = $this->passengers;
return $data;
}
}
$stations = generateStations();
$data = RestUtils::processRequest();
switch($data->getMethod())
{
// Get item
case 'get':
if(isset($data->getRequestVars()['stationId']))
{
// Prepare information for a specific station
$station = getStationWithId($stations, $data->getRequestVars()
['stationId']);
if($station != null)
{
echo RestUtils::sendResponse(200, json_encode($station),
'application/json');
}
else
{
echo RestUtils::sendResponse(404, 'Station not found!');
}
}
else
{
// Prepare station list
echo RestUtils::sendResponse(200, json_encode($stations),
'application/json');
}
break;
}
function generateStations()
{
$stations = array();
for($i = 1; $i <= 5; $i++)
{
$stations[] = new Station($i, 'İstasyon ' . $i);
$passengerIds = array();
foreach(generatePassengers() as $j)
{
$passengerIds[] = $j->getId();
}
$stations[$i - 1]->setPassengers($passengerIds);
}
return $stations;
}
function generatePassengers()
{
$passengers = array();
$numberOfPassengers = rand(0, 20);
for($i = 0; $i < $numberOfPassengers; $i++)
{
$from = rand(0, 5);
$to = rand(0, 5);
$arrivalTime = rand(0, 100);
$waitingTime = rand(0, 100);
$passengers[] = new Passenger($i, $from, $to, $arrivalTime, $waitingTime);
}
return $passengers;
}
function getStationWithId($stations, $id)
{
foreach ($stations as $i)
{
if($i->getId() == $id)
{
return $i;
}
}
return null;
}
?>
I want to fill the combobox with the produced station name and station ids when the page is loaded using document ready function.After that when the user selects a station with name and id, he can see how many passengers are there in that station and the ids of the passengers also should be returned from Station.php.
Normally I have had this select options in html code, it just showing the stations not doing anything when choosing any of them.
<select name="selectStation" id="selectStation" ></select>
I tried the following;
$(document).ready(function() {
$.getJSON("Stations.php", function(jsonData){
$.each(jsonData, function(key,value) {
$('#selectStation')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
});
});
I got the combobox values as object Object.Why does this happen?
How can fill the combobox when the page is loaded, according to Stations.php.Thanks.Any response will be appreciated.
Okay, here's some sample code that will do what I think you want.
Note: You still have to add an Event Listener to handle the change event of the select-box. I'll leave that to you.
File 1: ajaxAfterLoad.html
<!DOCTYPE html>
<html>
<head>
<script src="script/AjaxRequest.js"></script>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
window.addEventListener('load', mInit, false);
function mInit()
{
AjaxRequest.get( { 'url':'makeJSON.php', 'onSuccess': onAjaxRequestDone } );
}
function makeSelectElementFromJSON(elemId, jsonText)
{
var srcData = JSON.parse(jsonText);
var result = newEl('select');
result.setAttribute('id', elemId);
var i, curOpt;
for (i=0; i<srcData.length; i++)
{
curOpt = newEl('option');
curOpt.setAttribute('value', srcData[i].value);
curOpt.appendChild( newTxt( srcData[i].text ) );
result.appendChild(curOpt);
}
return result;
}
function onAjaxRequestDone(req)
{
var span = newEl('span');
span.innerHTML = req.responseText;
byId('rawOutput').innerHTML = req.responseText;
byId('ajaxOutput').appendChild( makeSelectElementFromJSON('jsonSelectBox1', req.responseText) );
}
</script>
<style>
</style>
</head>
<body>
<h2>Below will be loaded by ajax</h2>
<div id='rawOutput'></div>
<div id='ajaxOutput'></div>
</body>
</html>
File 2: makeJSON.php
<?php
$resultList = null;
for ($i=0; $i<10; $i++)
{
$curItem = null;
$curItem->value = $i;
$curItem->text = "Item " . ($i+1);
$resultList[] = $curItem;
}
printf("%s", json_encode($resultList) );
?>
File 3: AjaxRequest.js
Download this file from http://ajaxtoolbox.com/request/source.php
I have some function which I use in my cart application:
session_start();
if(!isset($_SESSION['products'], $_SESSION['price'], $_SESSION['product_names'],$_SESSION['product_id'])) {
$_SESSION['products'] = 0;
$_SESSION['price'] = 0;
$_SESSION['product_names'] = array();
$_SESSION['product_id'] = array();
}
if(isset($_POST['add'])) {
$_SESSION['product_names'][] = $_POST['product_name'];
$_SESSION['products']++;
$_SESSION['price'] += $_POST['price'];
}
if(isset($_POST['empty'])) {
session_destroy();
header('Location:index.php');
}
The question is, how can I add this into a class and call it in my view page?
I mean it will still work as <?php echo $_SESSION['price']?>. How can I make this work?
Try this class you're doing in a wrong way.
session_start();
class Shopping {
public function __construct()
{
}
//get cart products
public function getCartProducts()
{
$cart = array();
if(isset($_SESSION['cart'])) {
$cart = unserialize($_SESSION['cart']);
}
return $cart;
}
//add product to cart
public function addToCart($product_details)
{
$cart = $this->getCartProducts();
$product_id = $product_details['product_id'];
$is_quantity = $this->addQuantity($product_id); //check if product already exists in session if then increase the quantity
if(!$is_quantity) {
$product_details = array(
'qty' => $product_details['qty'],
'price' => $product_details['price'],
'product_name' => $product_details['name'],
'product_id' => $product_id
);
array_push($cart, $product_details);
$_SESSION['cart'] = serialize($cart);
}
}
//add quantity if product already exists
private function addQuantity($product_id)
{
$cart = $this->getCartProducts();
$i = 0;
foreach ($cart as $product) {
if($product['product_id'] == $product_id)
{
$product['qty'] += 1;
$cart[$i] = $product;
$_SESSION['cart'] = serialize($cart);
return true;
}
$i++;
}
return false;
}
public function clearCart()
{
unset($_SESSION['cart']);
}
public function removeProduct($product_id)
{
$cart = $this->getCartProducts();
$new_cart = array();
foreach ($cart as $product) {
if($product['product_id'] != $product_id)
array_push($new_cart, $product);
}
$_SESSION['cart'] = serialize($new_cart);
}
}
$shop = new Shopping();
$shop->addToCart(array('product_id'=>1,'name'=>'test 1','price'=>'120.00','qty'=>1));
$shop->addToCart(array('product_id'=>3,'name'=>'test 2','price'=>'120.00','qty'=>1));
This is an example of my approach using session in class. References work pretty well.
class Cart {
private $container ;
public function __construct(&$container){
if (!isset($container) || !is_array($container))
$session['cart'] = array() ;
$this->container = &$container ;
}
public function productExists($id){
return (isset($this->container[$id])) ;
}
}
$cart = new Cart($_SESSION['cart']) ;
At this point all changes in container can be performed in $_SESSION['cart'] . The rest of session array is not affected, that should be safe.