Last active
December 10, 2015 13:58
-
-
Save walterdavis/4444209 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Product extends MyActiveRecord{ | |
function sell($q){ | |
if($this->quantity - $q >= 0){ | |
$this->quantity -= $q; | |
}else{ | |
$this->add_error('quantity', 'You can only purchase ' . $this->quantity . ' of this item'); | |
} | |
} | |
} | |
// Handle a form submission, if it exists | |
if(isset($_POST['order'])){ | |
$errors = $order = array(); | |
foreach($_POST['order'] as $key => $val){ | |
if($product = MyActiveRecord::FindById('Product', $key)){ | |
$product->sell($val); | |
if(count($product->get_errors()) > 0){ | |
$errors[$key] = $product->get_errors(); | |
}else{ | |
$product->save(); | |
$order[] = urlencode($product->name . ':' . $val); | |
} | |
} | |
} | |
if(count($errors) > 0){ | |
//show errors (ugly style) | |
die(print_r($errors, true)); | |
}else{ | |
header('Location: http://your.mals.cart.server/order_page?order[]=' . implode('&order[]=', $order); | |
} | |
} | |
// Show a list of products for sale with a form to buy them | |
function q($id){ | |
if(isset($_POST['order'][$id])) | |
return $_POST['order'][$id]; | |
return ''; | |
} | |
$products = MyActiveRecord::FindAll('Product', 'quantity > 0', 'name ASC'); | |
$out = '<!DOCTYPE html><html><head><meta charset="utf-8" /><title>Store</title></head><body><form action="" method="post"><ul>'; | |
foreach($products as $product){ | |
$out .= '<li>' . $product->name . ': ' . $product->price . '<br />' . $product->description . '<br /><input name="order[' . $product->id . ']" value="' . q($product->id) . '" /></li>'; | |
} | |
print $out . '</ul><p><input type="submit" value="Place Order"/></p></form></body></html>'; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment