how to properly work with sqlite in a php class - php

how to properly work with sqlite in a class
I want to make a class that, in its methods, must refer to sqlite databases, depending on the parameters.
How to organize these connections correctly?
For example, something like this
class Text {
private $lang = 'EN';
private $id;
private $text;
public function __construct($lang) {
GLOBAL $db;
$this->lang = $lang;
$db = new SQLite3("./$this->lang/text.db");
}
public function dbSelectQuery($key) {
GLOBAL $db;
$stm = $db->query("SELECT * FROM TEXT WHERE KEY = '$key'");
$result = $stm->fetchArray(SQLITE3_ASSOC);
return $result['text'];
}
public function setText($key) {
$this->text = $this->dbSelectQuery($key);
}
}

You can use string interpolation "./{$lang}/text.db" to select the db by parameter.
i also removed all the globals. You can handle it with an other private variable and donĀ“t need a GLOBAL
class Text {
private $lang = 'EN';
private $id;
private $text;
private $db;
public function __construct($lang) {
$this->lang = $lang;
$this->db = new SQLite3("./{$lang}/text.db");
}
public function dbSelectQuery($key) {
$stm = $this->db->query("SELECT * FROM TEXT WHERE KEY = '$key'");
$result = $stm->fetchArray(SQLITE3_ASSOC);
return $result['text'];
}
public function setText($key) {
$this->text = $this->dbSelectQuery($key);
}
}

Related

PHP-OOP | Not accessing database

I'm trying to make this code access a certain row in the database and pull "title" from it to update public $Title in the UserBlog class, but, it's not doing so.
The database connection is definitely working as it worked procedually, but OOP is messing it up.
$ID = $db->real_escape_string(strip_tags(stripslashes($_GET['ID']))); // Page ID
class UserBlog
{
public $Title;
public $BannerImage;
public $ID;
public function GenerateBlog() {
$FetchBlogDetails = mysqli_query($db, "SELECT * FROM UserBlogs WHERE ID = '$this->ID'");
$FBL = mysqli_fetch_object($FetchBlogDetails);
$this->Title = $FBL->Title;
}
public function FetchBlog() {
return $this->Title;
return $this->ID;
}
};
$GetBlog = new UserBlog();
$GetBlog->ID = $ID;
$GetBlog->GenerateBlog();
echo $GetBlog->Title;
echo $GetBlog->ID;
$db doesn't exist in the scope of your method. You could inject it when calling the method.
class UserBlog
{
public $Title;
public $BannerImage;
public $ID;
public function GenerateBlog($db) {
$FetchBlogDetails = mysqli_query($db, "SELECT * FROM UserBlogs WHERE ID = '$this->ID'");
$FBL = mysqli_fetch_object($FetchBlogDetails);
$this->Title = $FBL->Title;
}
//...
}
$GetBlog = new UserBlog();
$GetBlog->ID = $ID;
$GetBlog->GenerateBlog($db);

Declaring Query Objects in PHP Class Methods

I am in the process of building an object-oriented forms system. I am putting together a User class which contains about eight functions. Each function contains a MySQL query for which an object of the Query class must be instantiated.
Is there any way to keep from having to declare a new object every single time? It occurs to me that might bog down the server at some point.
The role of the User class is to extract information about the user from the database (name, email, etc). That data is then used throughout the system including to authenticate roles. Here is the User class:
class User{
protected $user_id;
protected $session_hash;
protected $user_username;
protected $user_email;
protected $user_role_id;
protected $user_role_name;
protected $user_first_name;
protected $user_last_name;
public function __construct($user_id, $session_hash){
$this->user_id = $user_id;
$this->session_hash = $session_hash;
}
public function __get($name){
return $this->name;
}
public function __set($name, $value){
$this->$name = $value;
}
public function getLoggedUserInfo(){
global $db;
$query = new Query($db->link);
if($user_matches = $query->select("SELECT name, mail FROM ".TABLE_PREFIX.".d7_users WHERE uid = '".$this->user_id."'")){
$this->user_username = $user_matches[0]['name'];
$this->user_email = $user_matches[0]['mail'];
$this->user_role_id = $this->getLoggedUserRoleId($this->user_id);
$this->user_role_name = $this->getLoggedUserRoleName($this->user_role_id);
$this->user_first_name = $this->getLoggedUserFirstName($this->user_id);
$this->user_last_name = $this->getLoggedUserLastName($this->user_id);
$user_information_arr = array(
'user_id' => $this->user_id,
'user_username' => $this->user_username,
'user_first_name' => $this->user_first_name,
'user_last_name' => $this->user_last_name,
'user_email' => $this->user_email,
'user_role_id' => $this->user_role_id,
'user_role_name' => $this->user_role_name,
);
return $user_information_arr;
}
return false;
}
private function getLoggedUserRoleId($user_id){
global $db;
$query = new Query($db->link);
if($role_id_matches = $query->select("SELECT rid FROM ".TABLE_PREFIX.".d7_users_roles WHERE uid= '".$user_id."'")){
$this->user_role_id = $role_id_matches[0]['rid'];
return $this->user_role_id;
}
return false;
}
private function getLoggedUserRoleName($role_id){
global $db;
$query = new Query($db->link);
if($role_name_matches = $query->select("SELECT name FROM ".TABLE_PREFIX.".d7_role WHERE rid = '".$role_id."'")){
return $role_name_matches[0]['name'];
}
return false;
}
private function getLoggedUserFirstName($user_id){
global $db;
$query = new Query($db->link);
if($first_name_matches = $query->select("SELECT field_first_name_value FROM ".TABLE_PREFIX.".d7_field_revision_field_first_name WHERE entity_id='".$user_id."'")){
return $first_name_matches[0]['field_first_name_value'];
}
return false;
}
private function getLoggedUserLastName($user_id){
global $db;
$query = new Query($db->link);
if($last_name_matches = $query->select("SELECT field_last_name_value FROM ".TABLE_PREFIX.".d7_field_revision_field_last_name WHERE entity_id='".$user_id."'")){
return $last_name_matches[0]['field_last_name_value'];
}
return false;
}
}
Pass the query object from an existing instance into the constructor of the User class.
protected $queryObject;
public function __construct($user_id, $session_hash, Query $query = NULL){
$this->user_id = $user_id;
$this->session_hash = $session_hash;
$this->queryObject = $query;
}

PHP - Using classes to fetch user info

Assume the connection to the database and all references to tables and cells is correct... how could I get something like this working?
class User
{
private $_display;
private $_email;
public function __construct($username)
{
$fetch_user = mysql_query("SELECT * FROM `registered_users` WHERE `user_name`='$username'");
$fetch_user = mysql_fetch_array($fetch_user);
$this->_display = $fetch_user['user_display'];
$this->_email = $fetch_user['user_email'];
}
}
$person1 = new User('username');
echo "Information: " . print_r($person1, TRUE);
the problem is it returns nothing. Doesn't thrown an error or anything when debugged. Is it viable method though? :S
Here is roughly what I would do:
<?php
class User{
private $username;
private $data;
public function __construct($username){
$this->username = $username;
if($this->valid_username()){
$this->load();
}
}
private function load(){
// Let's pretend you have a global $db object.
global $db;
$this->data = $db->query('SELECT * FROM registered_users WHERE user_name=:username', array(':username'=>$this->username))->execute()->fetchAll();
}
public function save(){
// Save $this->data here.
}
/**
* PHP Magic Getter
*/
public function __get($var){
return $this->data[$var];
}
/**
* PHP Magic Setter
*/
public function __set($var, $val){
$this->data[$var] = $val;
}
private function valid_username(){
//check $this->username for validness.
}
// This lets you use the object as a string.
public function __toString(){
return $this->data['user_name'];
}
}
How to use:
<?php
$user = new User('donutdan');
echo $user->name; //will echo 'dan'
$user->name = 'bob';
$user->save(); // will save 'bob' to the database

Code is not getting executed when I include this class PHP

I took good care to create this class but I am not sure what is wrong with it. The code runs perfectly if I don't have any content inside,
class TemplateOne{
}
But once I run this code it breaks,
<?php
class TemplateOne {
//Properties
protected $_bgColor;
protected $_logoImagePath;
protected $_headerText;
protected $_leftContentHeader;
protected $_rightContentHeader;
protected $_leftContentBody;
protected $_rightContentBody;
protected $_footer;
protected $_mediaIframe;
protected $_mediaHeight = '';
protected $_mediaWidth = '';
//DB communication
public $DB;
//Constructor
public function __construct(){
//Connect database in construct and close connection in destruct
$config = array();
$config['host'] = 'localhost';
$config['user'] = 'root';
$config['pass'] = 'root';
$config['database'] = 'fanpage_application';
$this->DB = new DB($config);
//init variables
populateDataFromDataBase();
}
//Functions
public function populateDataFromDataBase() {
//Get bgcolor
$this->DB->("SELECT backgroundimage FROM template_style_data WHERE styleid='#list_level'");
$data = $this->DB->Get();
foreach($data as $key => $value)
{
echo $value['backgroundimage'];
}
}
//Getters
public function getBgColor()
{
return $this->_bgColor;
}
public function getLogoImagePath()
{
return $this->_logoImagePath;
}
public function getHeaderText()
{
return $this->_headerText;
}
public function getLeftContentHeader()
{
return $this->_leftContentHeader;
}
public function getRightContentHeader()
{
return $this->_rightContentHeader;
}
public function getLeftContentBody()
{
return $this->_leftContentBody;
}
public function getRightContentBody()
{
return $this->_rightContentBody;
}
public function getFooter()
{
return $this->_footer;
}
public function getMediaIframe()
{
return $this->_mediaIframe;
}
//Setters
public function setBgColor($bgColor)
{
$this->_bgColor = $bgColor;
}
public function setLogoImagePath($logoImagePath)
{
$this->_logoImagePath = $logoImagePath;
}
public function setHeaderText($headerText)
{
$this->_headerText = $headerText;
}
public function setLeftContentHeader($leftContentHeader)
{
$this->_leftContentHeader = $leftContentHeader;
}
public function setRightContentHeader($rightContentHeader)
{
$this->_rightContentHeader = $rightContentHeader;
}
public function setLeftContentBody($leftContentHeader)
{
$this->_leftContentBody = $leftContentHeader;
}
public function setRightContentBody($rightContentBody)
{
$this->_rightContentBody = $rightContentBody;
}
public function setFooter($footer)
{
$this->_footer = $footer;
}
public function setMediaIframe($mediaIframe)
{
$this->_mediaIframe = $mediaIframe;
}
}
?>
You are missing $this-> from your call to populateDataFromDataBase.
Where is the DB class coming from? You may have to include the correct class definition file if it is not already.
$this->DB = new DB($config);
The following is not legal syntax. You will need to actually call a function by name.
$this->DB->("SELECT backgroundimage FROM template_style_data WHERE styleid='#list_level'");
Unless you have another function in the global scope named populateDataFromDataBase which is what you want to call, you will need to add $this-> before you try to call it in your constructor.
populateDataFromDataBase();
Here is your error:
$this->DB->("SELECT backgroundimage FROM template_style_data WHERE styleid='#list_level'");
This is not valid syntax, you need to call a method after $this->DB.
As far as I'm concerned there is only one possible answer: check your PHP errors http://php.net/manual/en/function.error-reporting.php
at least (in devevlopment only, don't show errors in production):
ini_set('display_errors', 1);
error_reporting(-1);

PHP5 variable scope and class construction

I'm having problems with accessing variables from my classes...
class getuser {
public function __construct($id) {
$userquery = "SELECT * FROM users WHERE id = ".$id."";
$userresult = mysql_query($userquery);
$this->user = array();
$idx = 0;
while($user = mysql_fetch_object($userresult)){
$this->user[$idx] = $user;
++$idx;
}
}
}
I'm setting this class in a global 'classes' file, and later on I pass through a user id into the following script:
$u = new getuser($userid);
foreach($u->user as $user){
echo $user->username;
}
I'm hoping that this will give me the name of the user but it's not, where am I going wrong?!
Thanks
please define your users member as public in your class like this
class getuser {
public $user = null;
//...
}
in order to access a class property, you have to declare it public or implement getters and setters (second solution is preferable)
class A {
public $foo;
//class methods
}
$a = new A();
$a->foo = 'whatever';
with getters and setters, one per property
class B {
private $foo2;
public function getFoo2() {
return $this->foo2;
}
public function setFoo2($value) {
$this->foo2 = $value;
}
}
$b = new B();
$b->setFoo2('whatever');
echo $b->getFoo2();
in your example:
class getuser {
private $user;
public function __construct($id) {
$userquery = "SELECT * FROM users WHERE id = ".$id."";
$userresult = mysql_query($userquery);
$this->user = array();
$idx = 0;
while($user = mysql_fetch_object($userresult)){
$this->user[$idx] = $user;
++$idx;
}
}
/* returns the property value */
public function getUser() {
return $this->user;
}
/* sets the property value */
public function setUser($value) {
$this->user = $value;
}
}
$u = new getuser($userid);
$users_list = $u->getUser();
foreach($users_list as $user) {
echo $user->username;
}

Categories