<?php
class OrdersModel
{
public static function wishlistcreate($item, $user, $username){
$database = DatabaseFactory::getFactory()->getConnection();
$btc = System::bitcoinconnect();
//get the wishlist product, where username and still for sale
$wishlist = $database->prepare("SELECT * FROM products INNER JOIN wishlist ON wishlist.wishlist_product=products.id WHERE wishlist_username=? AND products.enddate > NOW() AND products.quantity > 0 AND products.enabled=1");
$wishlist->execute(array($user));
$product = $wishlist->fetch();
if($product):
$get_user_information = $database->prepare("SELECT * FROM users WHERE username=?");
$get_user_information->execute(array($user));
$user_result = $get_user_information->fetch();
$createorder = $database->prepare("INSERT INTO orders(orders_username,orders_amount,orders_product,orders_firstname, orders_lastname, orders_address1, orders_address2, orders_zipcode, orders_city, orders_country, orders_btcaddress, orders_status,orders_wishlist, orders_wishlist_user) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
//get btc address, check it's valid, then if isset run query below
$createorder->execute(array($username->username, $product->price + $product->shippingcost, $product->wishlist_product, $user_result->firstname, $user_result->lastname, $user_result->address1, $user_result->address2, $user_result->zipcode, $user_result->city, $user_result->country, $btc->getnewaddress(), 0, 1, $user,));
else:
echo 'nahhh'; //dbg
//error, item has ended or item not in users watch list.
endif;
}
I am getting the error:
Fatal error: Cannot redeclare class Bitcoin
Which is a class in a another file, here's is my $btc function:
public static function bitcoinconnect() {
include Config::get('PATH_LIBS')."jsonRPCClient.php";
//connect to bitcoin rpc use https ALWAYS!!
$bitcoin = new Bitcoin("yadda");
return $bitcoin;
}
I am using an mvc so each function counts as a page, but I have used
$btc = System::bitcoinconnect();
in another function/page, how can I go about only declaring the above code for all of that file so I don't get the cannot redeclare class.
public static function bitcoinconnect() {
include_once Config::get('PATH_LIBS')."jsonRPCClient.php";
//connect to bitcoin rpc use https ALWAYS!!
$bitcoin = new Bitcoin("yadda");
return $bitcoin;
}
Related
I'm having a problem with some PHP / MySQL code.
I need a view called gameview for a Star Wars game I'm writing.
If I created the view in MySQL then the code runs perfectly. However, I need this view to be dropped every time the game starts. So if I start without the view "gameview" present in the DB, the page cannot be displayed due to the view not existing. However, the moment I manually add the view into MySQL, it works. I can't see why.
Class code
<?php
class gameView
{
protected $Conn;
public function __construct($Conn)
{
$this->Conn = $Conn;
}
public function dropGameView()
{
$drop = "DROP VIEW if EXISTS gameview;";
$stmt = $this->Conn->prepare($drop);
$stmt->execute(array());
}
public function createGameView()
{
$view = "CREATE VIEW gameview AS SELECT id, name, image, quote FROM person;";
$stmt = $this->Conn->prepare($view);
$stmt->execute(array());
}
public function useGameView()
{
$query = "SELECT * from gameview";
$stmt = $this->Conn->prepare($query);
$stmt->execute(array());
$gameView = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $gameView;
}
}
?>
PHP code
<?php
$gameView = new gameView($Conn);
$finalCharacter = $gameView->useGameView();
$smarty->assign('game_view', $finalCharacter);
?>
Well.... stone the crows. I thought this would be too simple to work, but it did!
<?php
$gameView = new gameView($Conn);
$dropGameView = $gameView->dropGameView();
$smarty->assign('drop_gameview', $dropGameView);
$createGameView = $gameView->createGameView();
$smarty->assign('create_gameview', $createGameView);
$finalCharacter = $gameView->useGameView();
$smarty->assign('game_view', $finalCharacter);
?>
Now to crack on and use the view.
This is my code in my class
<?php
class PerClass
{
private $sql_connection = null;
private $localAf = '9929292F';
function __construct($env) {
// Nasty globals, sorry
global $_config;
$host = "localhost";
$user = "user";
$pass = "pass";
$db = "kModule";
// Build sql connection
$this->sql_connection = new mysqli($host, $user, $pass, $db);
// Check connection
if ($this->sql_connection->connect_error) {
die("Connection failed: " . $this->sql_connection->connect_error);
}
}
public function getOrders($sSettingsId) {
$query = <<<SQL
SELECT * FROM `scrub_order_log` WHERE `scrub_settings_id` = {$sSettingsId} AND `order_date` BETWEEN (NOW() - INTERVAL (SELECT `c_h_days` FROM `scrub_settings` WHERE `id` = {$sSettingsId}) DAY) AND NOW() ORDER BY `order_date` DESC;
SQL;
$result = $this->sql_connection->query($query);
$resp = null;
while ($row = $result->fetch_assoc()) {
$resp[] = $row;
}
return $resp;
}
}
?>
I am trying to get the output as shown in code below
<?
$details = $PerClass->getOrders('1');
print_r($details);
?>
But unfortunately I am getting following erro
Fatal error: Call to a member function getOrders() on null in /home/domn/public_html/stage/stage_test.php on line 37
Tried different ways but I think I am doing something wrong
The code that calls the getOrders method is missing the object instantiation.
<?
// add this here
$PerClass = new PerClass();
$details = $PerClass->getOrders('1');
print_r($details);
?>
now, because the constructor method of your PerClass expects you to pass in a value as an argument, this is going to result in the following warning:
WARNING Missing argument 1 for PerClass::__construct()
In order to resolve this warning you have two options:
Pass the value of the $env parameter when you instantiate the object i.e. $PerClass = new PerClass('value_to_be_passed'); or
Get rid of the $env argument in your constructor since - from what I can see - it is not used anywhere i.e. from function __construct($env) { ... } to function __construct() { ... }.
See this link for an interested discussion about using global in PHP.
I hope you could help me with this problem:
I tried to implement a pattern MVC in php + HTML5 + css. Now, apart the model, i have a problem when i try to instantiate an PHP object in one of my Controller.
In particular, i have to print the data about the authenticated user, stored in one object, $userObject, that i tried to instantiate with the DataBase data.
So I declared it, i initialized it at Null and, after, i tried to instantiate it with his constructor.
After, when i try to use it, PHP tells me: " Call to a member function getEmail() on a non-object in C:\Users\1USER\Documents\EasyPHP-DevServer-14.1VC11\data\localweb\projects\ammPHP\PHP\Controller\LoginController.php on line 99"
I show you the extract of codes about the problems:
/**the function handle_input rappresent the core of my controller, that popolates the variables of the master.PHP to make a virtual page and to visualize the user's profile.**/
private function handle_input(&$request, &$session)
{
$userObject = null;
$mysqli = new mysqli();
//login module: it verify the user data and modify the $_SESSION's array
//It makes also an object of class AuthenticatedUser that full with the database Data about the logged user.
if(isset($request["userid"]) && isset($request["password"]))
{
if($this->login($request["userid"], $request["password"]))
{
$session["loggedIn"] = true;
$mysqli->connect("localhost", "root", "password", "database");
$userid = $request["userid"];
$password = $request["password"];
$query = "SELECT * FROM loggeduser WHERE (userID = '$userid') AND (passwd = '$password');";
$result = $mysqli->query($query);
//errors checking salted
while($user = $result->fetch_object())
{
$userObject = new AuthenticatedUser($userid, $password, $user -> email, $user -> nome, $user -> cognome, $user -> dataNascita, $user -> città , $user -> CAP, $user -> indirizzo, $user -> cellulare);
}
}//user is logged-in
else if(isset($request["logout"]))
{
$this->logout();
}
//Master.php dedicated module: It verify that user is logged-in, then initialize
//the variables to popolate the master PHP and to make the virtual page of the profile's user.
if(isset($_SESSION["loggedIn"]) && $_SESSION[ "loggedIn"])
{
//CONTROLLO SULLE PAGINA RICHIESTE
if ($request["subpage"] == "profile")
{
$style = "PHP/view/LoggedUserStyle.php";
$header = "PHP/view/Header.php";
$loginFormContent = "PHP/view/loggedUserMenu.php"; //modificato col menù per utenti autenticati
$slideshow = null;
$userProfile = "PHP/view/userProfile.php";
**$user = $userObject -> getEmail(); //Here the problem, PHP tells me that $userObject is not an object! :/**
$payments = null;
$orders = null;
$notFoundContent ="PHP/view/content-not-found.php";
$footer="PHP/view/footer.php";
include("master.php");
}
[...]
}//closing function handle_input
I have successfully implemented the pagination box in a component front end listing template. however, when i try to set the limit of listing items, it won't work, i wonder what is missed out.
in the model
var $_total = null;
/**
* Pagination object
* #var object
*/
var $_pagination = null;
function __construct(){
parent::__construct();
$mainframe = JFactory::getApplication();
// Get pagination request variables
$limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
$limitstart = JRequest::getVar('limitstart', 0, '', 'int');
// In case limit has been changed, adjust it
$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
$this->setState('limit', $limit);
$this->setState('limitstart', $limitstart);
}
function _buildQuery(){
$query = ' SELECT * '
. ' FROM #__event '
.'Where published = 1'
;
return $query;
}
function getData() {
// if data hasn't already been obtained, load it
if (empty($this->_data)) {
$query = $this->_buildQuery();
$this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
}
return $this->_data;
}
function getTotal(){
// Load the content if it doesn't already exist
if (empty($this->_total)) {
$query = $this->_buildQuery();
$this->_total = $this->_getListCount($query);
}
return $this->_total;
}
function getPagination(){
// Load the content if it doesn't already exist
if (empty($this->_pagination)) {
jimport('joomla.html.pagination');
$this->_pagination = new JPagination($this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
}
return $this->_pagination;
}
in the views/view.html.php (full version of this document)
class EventViewListing extends JViewLegacy
{
// Overwriting JView display method
function display($tpl = null)
{
$model= & JModelLegacy::getInstance('Event','EventModel');
$pagination = $model->getPagination();
$this->assignRef('pagination', $pagination);
$JDoc =& JFactory::getDocument();
$db = JFactory::getDBO();
$sql = "SELECT * FROM #__event WHERE published = 1 ORDER BY id DESC";
$db->setQuery($sql);
$rows = $db->loadObjectList();
$sql2 = "SELECT * FROM #__user_usergroup_map WHERE group_id = 5 or group_id = 8";
$db->setQuery($sql2);
$rows2 = $db->loadObjectList();
$this->assignRef('rows',$rows);
$this->assignRef('rows2',$rows2);
// $JDoc->setTitle(' ');
// Display the view
parent::display($tpl);
}
}
in the default.php
<form action="<?php echo JRoute::_('index.php?option=com_event'); ?>" method="post" name="adminForm">
<?php echo $this->pagination->getListFooter(); ?>
<input type="submit" name="submit" value="GO!" />
</form>
hope someone could help
thank you!
The limits need to also be used in the queries to limit the number of records that are displayed to the page that you are on. Typically this can be done in the setQuery function, which allows a second and third parameter to set the limit size and start position.
$sql = "SELECT * FROM #__event WHERE published = 1 ORDER BY id DESC";
$db->setQuery($sql, $model->getState('limitstart'), $model->getState('limit'));
$rows = $db->loadObjectList();
// I'm not sure what this query is for, but since it probably isn't supposed to be limited to a set number of items, don't update it's setQuery call.
$sql2 = "SELECT * FROM #__user_usergroup_map WHERE group_id = 5 or group_id = 8";
$db->setQuery($sql2);
$rows2 = $db->loadObjectList();
I think that fixes the problem that you are having.
That being said, you have a host of minor issues that are making this a lot harder for you or just using outdated practices:
$limitstart = JRequest::getVar('limitstart', 0, '', 'int');
Using JRequest::getVar() is deprecated and likely to be removed in future versions of Joomla. Instead use this:
$limitstart = JFactory::getApplication()->input->get('limitstart', 0, 'INT');
Note that the parameters have changed slightly. This uses a different class to parse input to the application.
$this->assignRef('rows',$rows);
The above is unnecessary anymore (was only needed back in PHP4 from what I understand). Instead just do $this->rows = $rows;
Finally, the big overall issue is that you aren't really using Joomla's help.
Your model should just be extending from the class JModelList since you are trying to create a list of events. If you extend from that class and name your functions properly, Joomla will do most of the work:
Rename _buildQuery to getListQuery.
Pretty much delete every other function in your model, since Joomla has all of them in JModelList doing basically the same things.
Update your view to this:
class EventViewListing extends JViewLegacy
{
// Overwriting JView display method
function display($tpl = null)
{
$JDoc = JFactory::getDocument();
$db = JFactory::getDBO();
$this->pagination = $this->get('Pagination');
$this->rows = $this->get('Items');
$sql2 = "SELECT * FROM #__user_usergroup_map WHERE group_id = 5 or group_id = 8";
$db->setQuery($sql2);
$this->rows2 = $db->loadObjectList();
// $JDoc->setTitle(' ');
// Display the view
parent::display($tpl);
}
}
$this->get() in the JViewLegacy class will call the model (with the same name as the view) and run the method of that model that starts with get followed by whatever word is in the function, so $this->get('Pagination') calls the models getPagination function.
And again, all of the functions that you are adding in the model exist already in libraries/legacy/model/list.php, so just use them!
So I'm working on a simple user class in php, which has a class variable which contains the mysqli object, however I keep getting the error:
Fatal error: Call to a member function real_escape_string() on a non-object in */classes/user.php on line X
I've checked everything, it should work, but it doesn't. Somehow. This is my code:
namespace bibliotheek;
class user
{
private $mysql;
private $logged_in = false;
private $user_data = null; //ARRAY: user_id, e-mail, password, bevoegdheid, naam, achternaam, adres, postcode, stad
function __construct(\mysqli $mysql, $salt)
{
$this->mysql = $mysql;
}
public function login($email, $pass, $hash = false)
{
$email = $this->mysql->real_escape_string($email);
if($hash == false)
$pass = sha1($this->salt.$pass);
$query = "SELECT *
FROM gebruikers
WHERE gebruikers.email = '$email' AND gebruikers.password = '$pass'";
$result = $this->mysql->query($query);
$user_data = $result->fetch_assoc();
if($user_data == null)
return;
$this->logged_in = true;
$this->user_data = $user_data;
$this->create_cookies($email, $pass);
}
}
And this is how the mysqli object gets passed to the class:
$mysql = new mysqli($cfg['mysql_server'], $cfg['username'], $cfg['password'], $cfg['database']);
$user = new bibliotheek\user($mysql, $cfg['salt']);
the mysql login data is correct, I've made sure of that.
I must be missing something really obvious here, but I just can't see it. Any help is greatly appreciated. Thanks!
And this is how it should be
error_reporting(E_ALL);
$mysql = new mysqli($cfg['mysql_server'], $cfg['username'], $cfg['password'], $cfg['database']);
if ( !$mysql )
{
throw new Exception(mysqli_connect_error()));
}
$user = new bibliotheek\user($mysql, $cfg['salt']);
I'm really f-ing stupid, I compacted my code a bit when I posted it on here and I left out this part:
$this->mysql = $mysql;
$this->mysql = $salt;
Kill me now.