I have a problem. I want some data out my database.
I have two page's a categorie.php here I want that he shows everything out the database. And I have a second page. Here are my classes. I have trying a foreach on the categorie.php but if I do that, than shows he 1 thing out the database 4 times the same and not the another data.
Below you can see my code.
I hope that you can help me.
Thank you.
This is my categorie.php
<?php
require_once '../app/functions/second.php';
require_once '../app/db/dbpassword.php';
require_once 'include/head.php';
if (isset($_GET['categorie']) && !empty($_GET['categorie'])) {
$id = $_GET['categorie'];
$dbh = new PDO("mysql:host=$host; dbname=$dbname;", $usernamedb,
$passworddb);
$cate = new Categorie($dbh);
$cate->loadCate($id);
// $page->loadId($id);
$categorie = $cate->getCategorie();
$titel = ucwords($categorie);
?>
<h2 class="center_h2"><?= $titel ?></h2>
<?php foreach ($cate as $key) {
$titelart = $cate->getTitel();
$beschrijving = $cate->getBeschrijving();
$plaatje = $cate->getImage();
$id = $cate->getId();
var_dump($titelart);
} ?>
<?php
} else {
echo "Dit bericht is verwijderd of is verplaats.";
}
require_once 'include/footer.php';
?>
This is my class page
<?php
class Categorie {
protected $dbh;
public function __construct($new_dbh){
$this->dbh = $new_dbh;
}
public function loadCate($cate){
$query = $this->dbh->prepare('SELECT * FROM schilderijen WHERE categorie=?');
$query->execute(array($cate));
while ($row = $query->fetch(PDO::FETCH_OBJ)) {
$this->id = $row->id;
$this->categorie = $row->categorie;
$this->titel = $row->titel;
$this->beschrijving = $row->beschrijving;
$this->plaatje = $row->plaatje;
}
}
public function getId(){
return $this->id;
}
public function getCategorie(){
return $this->categorie;
}
public function getTitel(){
return $this->titel;
}
public function getBeschrijving(){
return $this->beschrijving;
}
public function getImage(){
return $this->plaatje;
}
}
?>
Ok so you have a problem with the use of your class. In the while after your SQL request, you apply the value the instance variable like $this->id = $row->id; but this variable will be rewrite with the next row value.
Use a static function for your SQL request and return an array of Categorie like that :
class Categorie {
protected $id, $categorie, $title, $beschrijving, $plaatje;
public function __construct($id, $categorie, $title, $beschrijving, $plaatje){
$this->id = $id;
$this->categorie = $categorie;
$this->title = $title;
$this->beschrijving = $beschrijving;
$this->plaatje = $plaatje;
}
public static function loadCate($dbh, $cate){
$query = $dbh->prepare('SELECT * FROM schilderijen WHERE categorie=?');
$query->execute(array($cate));
$res = array();
while ($row = $query->fetch(PDO::FETCH_OBJ)) {
$res[] = new Categorie($row->id, $row->categorie, $row->titel, $row->beschrijving, $row->plaatje);
}
return $res;
}
public function getId(){
return $this->id;
}
public function getCategorie(){
return $this->categorie;
}
public function getTitle(){
return $this->title;
}
public function getBeschrijving(){
return $this->beschrijving;
}
public function getImage(){
return $this->plaatje;
}
}
And you can use it like that:
$categories = Categorie::loadCate($dbh, $id);
foreach($categories as $categorie){
var_dump($categorie->getTitle());
}
Related
I need to dynamically display user name from logged in user in my OOP PHP project. I can display it when I type right id from the database but it shows error when I try to define property $user_id in my function find_by_id. I need help on how to define $user_id variable. Here is my code:
index.php
<?php $user = User::find_by_id($user_id); ?>
<h1>Hello, <?php echo $user->username; ?></h1>
user.php
<?php
class User
{
protected static $db_table = "users";
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
private function has_the_attribute($the_attribute)
{
$object_properties = get_object_vars($this);
return array_key_exists($the_attribute, $object_properties);
}
public static function instantation($the_record)
{
$the_object = new self;
foreach ($the_record as $the_attribute => $value) {
if ($the_object->has_the_attribute($the_attribute)) {
$the_object->$the_attribute = $value;
}
}
return $the_object;
}
public static function find_this_query($sql)
{
global $database;
$result_set = $database->query($sql);
$the_object_array = [];
while ($row = mysqli_fetch_array($result_set)) {
$the_object_array[] = self::instantation($row);
}
return $the_object_array;
}
public static function find_all()
{
return self::find_this_query("SELECT * FROM " . static::$db_table . " ");
}
public static function find_by_id($user_id)
{
global $database;
$the_result_array = self::find_this_query("SELECT * FROM " . self::$db_table . " WHERE id = $user_id");
return !empty($the_result_array) ? array_shift($the_result_array) : false;
}
public static function verify_user($username, $password)
{
global $database;
$username = $database->escape_string($username);
$password = $database->escape_string($password);
$sql = "SELECT * FROM " . self::$db_table . " WHERE ";
$sql .= "username = '{$username}' ";
$sql .= "AND password = '{$password}'";
$the_result_array = self::find_this_query($sql);
return !empty($the_result_array) ? array_shift($the_result_array) : false;
}
}
$user = new User();
session.php
<?php
class Session
{
private $signed_in = false;
public $user_id;
public $message;
public function __construct()
{
session_start();
$this->check_the_login();
$this->check_message();
}
public function login($user)
{
if ($user) {
$this->user_id = $_SESSION['user_id'] = $user->id;
$this->signed_in = true;
}
}
public function logout()
{
unset($_SESSION['user_id']);
unset($this->user_id);
$this->signed_in = false;
}
private function check_the_login()
{
if (isset($_SESSION['user_id'])) {
$this->user_id = $_SESSION['user_id'];
$this->signed_in = true;
} else {
unset($this->user_id);
$this->signed_in = false;
}
}
public function is_signed_in()
{
return $this->signed_in;
}
public function message($msg="")
{
if (!empty($msg)) {
$_SESSION['message'] = $msg;
} else {
return $this->message;
}
}
public function check_message()
{
if (isset($_SESSION['message'])) {
$this->message = $_SESSION['message'];
unset($_SESSION['message']);
} else {
$this->message = "";
}
}
}
$session = new Session();
For the sake of marking this as accepted, what you need to do is actually pass the user ID of the and not just an uninitialised variable, if your instance you are storing it in the session so I presume it would be:
<?php $user = User::find_by_id($_SESSION['user_id']); ?>
Note: To make your templating cleaner, you can use the shorthand syntax for echo:
<h1>Hello, <?= $user->username; ?></h1>
Another thing to note is that you have built a Session class, however you are still for some reason accessing the data through $_SESSION which doesn't make sense, make some setters / getters for it. Finally, sessions are something that you'll be using a lot therefore it would be worth making that class static.
Reading Material
echo
I have received the following error:"Fatal error: Call to a member function session_type() on a non-object".
Supposedly I'm not creating an object in the variable "$tabsessiontype2". I don't see the reason why the object isn't created. Thanks for you help.
Here is my TeacherController.php
if(isset($_POST['search']) && $_POST['sessiontype_name']){
$tabsessiontype2=Db::getInstance()->select_session_type2($_POST['sessiontype_name']);
if($tabsessiontype2->session_type()=='X'){
$view='teacher.php';
}
elseif($tabsessiontype2->session_type()=='XO'){
$view='teacherxo.php';
}
elseif($tabsessiontype2->session_type()=='note'){
$view='teachernote.php';
}
}
This is the function I call:
public function select_session_type2($name_session_type) {
$query = "SELECT * FROM session_types WHERE session_types.name_session_type='$name_session_type'";
$result = $this->_db->query($query);
$tableau = array();
if ($result->rowcount()!=0) {
while ($row = $result->fetch()) {
$tableau[] = new Sessiontype($row->code_session_type,$row->name_session_type,$row->quarter_session_type,$row->code_lesson,$row->session_type);
}
}
return $tableau;
}
Here is the SessionType class:
class SessionType{
private $_code_session_type;
private $_name_session_type;
private $_quarter_session_type;
private $_code_lesson;
private $_session_type;
public function __construct($code_session_type,$name_session_type, $quarter_session_type, $code_lesson,$session_type){
$this->_code_session_type = $code_session_type;
$this->_name_session_type = $name_session_type;
$this->_quarter_session_type = $quarter_session_type;
$this->_code_lesson = $code_lesson;
$this->_session_type = $session_type;
}
public function code_session_type(){
return $this->_code_session_type;
}
public function name_session_type(){
return $this->_name_session_type;
}
public function quarter_session_type(){
return $this->_lastname;
}
public function code_lesson(){
return $this->_email_student;
}
public function session_type(){
return $this->_session_type;
}
}
It looks like the function select_session_type2 is returning an array:
$tableau = array();
if ($result->rowcount()!=0) {
while ($row = $result->fetch()) {
$tableau[] = new Sessiontype($row->code_session_type,$row->name_session_type,$row->quarter_session_type,$row->code_lesson,$row->session_type);
}
}
return $tableau;
and you are expecting an object:
$tabsessiontype2=Db::getInstance()->select_session_type2($_POST['sessiontype_name']);
if($tabsessiontype2->session_type()=='X'){
$view='teacher.php';
}
I am new to codeigniter 3 and try to convert my PHP project to MVC by this Framework
Controller file
class home extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('frontend/M_Headers');
}
public function index()
{
$data['slide_image'] = $this->M_Headers->get_all_slide();
$this->load->view('frontend/headers',$data);
}
}
Model file
class M_Headers extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function get_all_slide()
{
$query = $this->db->get('tbl_slide');
return $query->result();
}
}
View file
<div class="slider">
<ul class="rslides" id="slider">
<?php
if(count($slide_image) > 0)
{
foreach($slide_image as $value):
$get_image=$value->sl_image;
if($get_image != ''):
$image_properties = array(
'src' => 'assets/images/slide/'.$get_image,
'alt' => '',
);
?>
<li><?php echo img($image_properties); ?></li>
<?php else: ?>
<li>No Slide</li>
<?php
endif;
endforeach;
}
?>
</ul>
</div>
did am i right that loop result in View or should i do it in
Controller?
which query should i use between active record or bind (where id=?) or they had it own benefit in difference situation?
The loop in the view is correct. Because it is "view logic" (repeating li's) you can use into the view.
Your Model can be better. I personally like to use the model as a representation of the item from the database. Like this:
class M_Headers extends CI_Model
{
private var $tablename = "tbl_slide";
var $id;
var $sl_image;
public function __construct()
{
parent::__construct();
}
public function get_all_slide()
{
$slides = array();
$query = $this->db->get($this->tablename);
foreach($query->result() as $row)
{
$item = new self();
$item->id = $row->id;
$item->sl_image = $row->sl_image;
$slides[] = $item;
}
return $slides;
}
public function get_slide($id)
{
$this->db->where("id", $id);
$query = $this->db->get($this->tablename);
$results = $query->result();
if(isset($results[0]))
{
$row = $results[0];
$this->id = $row->id;
$this->sl_image = $row->sl_image;
return true;
}
return false;
}
}
You can even improve this to make a method that loads the row into the model:
class M_Headers extends CI_Model
{
private var $tablename = "tbl_slide";
var $id;
var $sl_image;
public function __construct()
{
parent::__construct();
}
private function load_with_record($row)
{
$this->id = $row->id;
$this->sl_image = $row->sl_image;
}
public function get_all_slide()
{
$slides = array();
$query = $this->db->get($this->tablename);
foreach($query->result() as $row)
{
$item = new self();
$item->load_with_row($row);
$slides[] = $item;
}
return $slides;
}
public function get_slide($id)
{
$this->db->where("id", $id);
$query = $this->db->get($this->tablename);
$results = $query->result();
if(isset($results[0]))
{
$row = $results[0];
$this->load_with_row($row);
return true;
}
return false;
}
}
<?php
require_once (realpath(dirname(__FILE__) . '/../includes/database.php'));
class User {
public $email;
public $password;
public function find_email($email, $password) {
global $database;
$pswd = substr(md5($password), 0, 25);
$results_array = self::find_by_sql("SELECT * FROM tbl_users where email_id='".$email."' AND password='".$pswd."'");
return !empty($results_array)? array_shift($results_array) : false;
}
public static function find_by_sql($sql){
global $database;
$results = $database -> query($sql);
$object_array = array();
while($row = $database -> fetch_array($results)){
$object_array[] = self::instantiate($row);
}
return $object_array;
}
public static function instantiate($row) {
$event = new self;
foreach($row as $attribute => $value) {
if($event -> has_attribute($attribute)) {
$event -> $attribute = $value;
}
}
return $event;
}
private function has_attribute($attribute) {
$object_vars = get_object_vars($this);
return array_key_exists($attribute, $object_vars);
}
}
if (isset($_GET['email']) && isset($_GET['password'])) {
$result = new User();
$result->find_email($_GET['email'], $_GET['password']);
echo json_encode($result);
}
?>
This is the login.php which is supposed to print out the json for the required user, but whenever I try to get the json, this is getting returned.
{"email":null,"password":null}
Any help would be appreciated. Thanks.
You don't do anything with the result of find_email. Your class doesn't update it's own properties when find_email is called. Instead, it returns a new instance of the class with the email and password properties set, so you need to capture the return value and encode that.
Change to:
$result = new User();
$user = $result->find_email($_GET['email'], $_GET['password']);
echo json_encode($user);
Side note: have a look at SOLID and Dependency Injection. DI would be preferred over having a global $Database.
I'm new in php oop..I'm having trouble in showing my fields value. I have here the ff classes.
public static function getAll()
{
self::conn();
try
{
$sql = "SELECT * FROM dbo.guitar";
$q = self::$db->prepare($sql);
$q->execute();
$results = $q->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE,
"Guitar",
array('id', 'make', 'model', 'colour', 'price'));
}
catch (Exception $e)
{
print "Error!: " . $e->getMessage();
}
return $results;
}
I want it to show from diff fields. Here is my code:
$guitars = Guitar::getAll();
I can see the values when I try using the print_r
What I want is like this.
echo $row['field1']; echo $row['field2'];
THank you in advance.
You are fetching result as objects, so you could do like this:
$guitars = Guitar::getAll();
foreach ($guitars as $guitar) {
echo $guitar->getId();
echo $guitar->getMake();
// ... and so on
}
Addtion:
You need to have the constructor to set the property, and provide public methods to access the property.
class Guitar {
private $id;
private $make;
private $model;
private $color;
private $price;
public function __construct($id, $make, $model, $color, $price) {
$this->id = $id;
$this->make = $make;
$this->model = $model;
$this->color = $color;
$this->price = $price;
}
public function getId() {
return $this->id;
}
public function getMake() {
return $this->make;
}
// and so on...
}