OPP Classes with sql statement - php

I want to set a PHP variable within my SQL SELECT statement that can then be used on another page. Here is my code:
<?php
class Page extends DbConnect
{
public function getPage()
{
$sql = "SELECT * FROM pages WHERE page_name = 'Contact'";
$result = $this->connect()->query($sql);
while($row = $result->fetch())
{
echo $row['page_name'];
}
}
}
?>

You can pass a variable on a class's construct and assign it to a private or public variable
<?php
class Page extends DbConnect
{
private $page;
public function __construct($toView){
$this->page = $toView;
}
public function getPage()
{
$pageToView = $this->page;
$sql = "SELECT * FROM pages WHERE page_name = '$pageToView'";
...
}
}
<?php
// on contact page
$page = new Page('contact');
$page->getPage();
<?php
// on about page
$page = new Page('about');
$page->getPage();
You can also pass a parameter directly on a class's function
<?php
class Page extends DbConnect
{
public function getPage($pageToView)
{
$sql = "SELECT * FROM pages WHERE page_name = '$pageToView'";
...
}
}
<?php
// on contact page
$page = new Page();
$page->getPage('contact');
<?php
// on about page
$page = new Page();
$page->getPage('about');

Related

Pass data from a class to a template

I don't know how to pass data from a class to one of my class to the studentShow template file.
MODEL
<?php
class Student{
public function all(){
require_once('config/db.php');
$SQLCommand = "SELECT * FROM people";
$Query = $conn->prepare($SQLCommand);
$Query->execute();
$rows = $Query->fetchAll(PDO::FETCH_OBJ);
return $rows;
}
}
?>
index
<?php
require_once("app/Controller/StudentController.php");
$Student = new StudentController();
$Student->index();
?>
Controller
<?php
require_once("app/Student.php");
class StudentController{
public function index(){
$Student = Student::all();
include ('resource/studentShow.php');
}
}
?>
My Question is: in my Controller how to pass that $student variable to studentShow.php.
Here is the way to achieve that:
public function index() {
$student = Student::all();
extract(['student' => $student]);
ob_start();
include ('resource/studentShow.php');
return ob_get_clean();
}
Read more about ob_start, extract & ob_get_clean

sql querying by class and function

So i'm new to classes and functions and I'm trying to do one sql query for the entire class for every function to use. I'm a little confused on how it works. From other examples that I've seen the call the query every single function which seems like a lot of usage. (why not call it once and set them all) I know there is an easier way by just querying and making variables including a db file or whatever. This is just practice.
<?php
//User System
class usrsys
{
$results = mysqli_query($con, "SELECT * FROM users WHERE id = '".$_SESSION['coid']."'");
while($row = mysqli_fetch_array($results)) {
$fname = $row['fname'];
}
function username()
{
echo $_SESSION['Username'];
}
function fname()
{
echo $fname;
}
}
//Setting Variable
$user = new usrsys();
?>
Then I call the functions in the next file by:
<?php $user->fname(); ?>
class usrsys
{
public $fname;
public $con;
public function __construct() {
//load your conection class function here and pass it to the $this->con variable.
$results = mysqli_query($this->con, "SELECT * FROM users WHERE id = '".$_SESSION['coid']."'");
while($row = mysqli_fetch_array($results)) {
$this->fname = $row['fname'];
}
}
function username()
{
echo $_SESSION['Username'];
}
function fname()
{
echo $this->fname;
}
}
//Setting Variable
$user = new usrsys();
$user->fname();

Class with a db query, extending, functions and views. Am I doing it right way?

I have just a little progress in practicing. Most of my code works but I am not sure if I do things the right way?
Please, can you tell me if I do mistakes and correct me.
First, I create autoload functions:
function autoload_models($model) {
if (file_exists(MODELS_PATH . $model . '.php')) {
require_once MODELS_PATH . $model . '.php';
return true;
} else {
return false;
}
}
spl_autoload_register('autoload_models');
function autoload_controllers($controller) {
if (file_exists(CONTROLLERS_PATH . $controller . '.php')) {
require_once CONTROLLERS_PATH . $controller . '.php';
return true;
} else {
return false;
}
}
spl_autoload_register('autoload_controllers');
I have a class like this:
class Category {
public $db;
public $rows;
public $id;
public function build_category() {
global $db;
global $rows;
$db = new Database();
$db->query("SELECT * from categories");
$rows = $db->resultset();
}
public function category_items() {
global $db;
global $rows;
global $id;
$db = new Database();
$db->query("SELECT * from posts WHERE category_id = '$id'");
$rows = $db->resultset();
}
}
I extend with another class (still have some issues here. Nothing prints):
class Category_Items extends Category {
public $db;
public $rows;
public $id;
public function display_category_items() {
// Call the parent class function
parent::category_items();
global $rows;
global $id;
// Check if the page parameter is integer
if (ctype_digit($_GET['id'])) {
$id = $_GET['id'];
} else {
print "Illegal category page parameter";
}
foreach ($rows as $row) {
print "test";
print $row['post_title']; // This does not work yet. Nothing prints
}
}
}
Class for building a menu with categories (Everything works here):
class Categories_Menu extends Category {
public $db;
public $rows;
public function build_category_menu() {
parent::build_category();
global $rows;
foreach ($rows as $row) {
require VIEWS_PATH . 'categories/categories_menu.php';
}
}
}
And finally instances:
$category_menu = new Categories_Menu();
$category_menu->build_category_menu();
$category_items = new Category_Items();
$category_items->display_category_items();
Thank you for your time and help!
Where do the global variables come from?
Anyway, you should get rid of them.
I guess your rows var does not get changed, after any interaction. Using globals also will not be relevant in extending classes.
Your public properties and globals mentioned, does no interact each other. Thus, the object members seems to be totally useless.
What I would suggest in simple schems would be
class Model {
protected $_db;
public function __construct(Database $db) {
$this->_db = $db;
}
}
class Category extends Model {
public $_rows;
public $_id;
public function build_category() {
$this->_db->query("SELECT * from categories");
$this->_rows = $this->_db->resultset();
}
public function category_items() {
$this->_db->query("SELECT * from posts WHERE category_id = '{$this->_id}'");
$this->_rows = $this->_db->resultset(); // here you will overwrite $_rows ?
}
class Categories_Menu extends Category {
public $_rows;
public function build_category_menu() {
$this->build_category();
foreach ($this->_rows as $row) {
require VIEWS_PATH . 'categories/categories_menu.php';
}
}
}
class Category_Items extends Category {
public $_rows;
public $_id;
public function display_category_items() {
if (ctype_digit($_GET['id'])) { // just intval it, or use is_int?
$this->_id = $_GET['id'];
} else {
print "Illegal category page parameter";
}
// You assign value to $_id, then call the function that requires it
$this->category_items();
foreach ($this->_rows as $row) {
print "test";
print $row['post_title'];
}
}
}

php - print_r() with an array of data

Working in Joomla, I have my model and view set up, but when the page is loaded, no data appears.
Model:
class mlsModelmls extends JModel
{
/**
* Gets the info
*/
function mlsdata($column)
{
$db =& JFactory::getDBO();
$query = "
SELECT *
FROM ".$db->nameQuote('#__mls')."
WHERE ".$db->nameQuote('MSTMLSNO')." = ".$db->quote('4112065').";
";
$db->setQuery($query);
$row = $db->loadRow();
print_r($row[$column]);
}
}
View:
class mlsViewmls extends JView
{
function mlsnum($tpl = null)
{
$model = &$this->getModel();
$mlsnum = $model->mlsdata(MSTMLSNO);
$this->assignRef( 'mlsnum', $mlsnum );
$agentuid = $model->mlsdata(MSTLISTBRD);
$this->assignRef( 'agentuid', $agentuid );
$listdt = $model->mlsdata(MSTLISTDT);
$this->assignRef( 'listdt', $listdt );
/** Some more assignRef() */
parent::display($tpl);
}
}
TMPL:
<h2 class="price">
<?php echo $this->mlsnum; ?>
</h2>
When the page is loaded, the TMPL looks fine, but no data appears for the <?php echo $this->mlsnum; ?> reference call.
Does each assignRef() need it's own function?
Try to change
print_r($row[$column]);
to this:
return $row[$column];
And this one
parent::display($tpl);
to
return parent::display($tpl);
Otherwise it's just no-result.
Your mlsdata() method doesn't returning anything, therefore you are assigning nothing to the template variable.
Add return $row and remove the print_r.
Try changing your model function to this:
function mlsdata($column) {
$db =& JFactory::getDBO();
$query = " SELECT * FROM ".$db->nameQuote('#__mls')." WHERE ".$db->nameQuote('MSTMLSNO')." = ".$db->quote('4112065').";
$db->setQuery($query);
$row = $db->loadRow();
return $row;
}

php5 access another class from an object

I'm new to OOP. I created this class called Site that is extended but many other classes with common queries and excutions.
This particular class "Pagination" , I need its methods to be accessed from other instances and access to data sent to it "internally". It's probably bad written but I'd like some help.
<?php
class Site {
public $lang;
public $user_agent;
public $user_lang;
public $url;
public $bots;
public $total_items;
public $itemsPerPage;
public $page;
class Products extends Site {
function getProducts($last = false, $id = false, $cat = false, $active_only = false, $lang_pref = false, $itemsPerPage = false, $page =false){
//code
//prepare paging
if(!empty($itemsPerPage)){
//count total product
$count = mysql_query(
"SELECT COUNT(*)
FROM products_list
".#$cat_to_choose."
".#$lang."
")
or die(mysql_error());
$count = mysql_fetch_row($count);
$total_items = $count[0];
// set vars for Pagination class
$this->total_items = $total_items;
$this->itemsPerPage = $itemsPerPage;
$this->page = mysql_real_escape_string($page);
//send data to class Pagination
$pagination = new Pagination();
$start = $pagination->createPagination();
$limit = "LIMIT ".$start.", ".$itemsPerPage;
}
//code
}
//other classes
class Pagination extends Site {
function createPagination(){
// get total pages by dividing
$this->total_pages = $this->total_items/$this->itemsPerPage;
//round to highest integer
$this->total_pages= ceil($this->total_pages);
switch($this->page){
case "0":
case null:
case "1":
$start = 0;
break;
default :
$start = ($this->page-1)*($this->itemsPerPage);
break;
}
return $start;
}
public function htmlPagination(){
if($this->page == 0){
$this->page = 1;
}
$pagination = array(
"total_pages" => $this->total_pages,
"current_page" => $this->page,
"total_items" => $this->total_items
);
return $pagination;
}
}
}
PHP CODE
$products_object= new Products();
$products = $products_object->getProducts(false,false,$cat, true, $site->lang, $itemsperpage, #$_GET["pag"]);
Once I did this, how do I access htmlPagination with the data processed in the Products instance?
You could set the pagination as a field of the products object and retrieve it with a get method or by defining it as public and reading it directly.
In products:
class Products
{
...
private $pagination;
public function getProducts(...)
{
...
$this->pagination = new Pagination();
...
}
public function getPagination()
{
return $this->pagination;
}
}
Then later:
$product->getPagination()->htmlPagination();
to retrieve the html pagination.

Categories