Undefined property error message in PHP OOP - php

I'm working on a custom CMS using PHP OOP and this is actually my first project ever which is made with object oriented programming so I don't have that much of experience with it. Basically I have a class called Site.class.php which retrieves data from one of the tables in MySQL database and goes like this:
<?php
class Site
{
public $id,$site_name,$site_title,$site_url,$site_tags,$site_desc;
public function __construct()
{
$this->db = new Connection();
$this->db = $this->db->dbConnect();
}
public function getSite($name)
{
if(!empty($name))
{
$site = $this->db->prepare("select * from admins where site_name = ?");
$site->bindParam(1,$name);
$site->execute();
while($row = $site->fetch())
{
$this->id = $row['id'];
$this->site_name = $row['site_name'];
$this->site_title = $row['site_title'];
$this->site_url = $row['site_url'];
$this->site_tags = $row['site_tags'];
$this->site_desc = $row['site_desc'];
}
}
else
{
header("Location: maint/php/includes/errors/005.php");
exit();
}
}
public function getID()
{
return $this->id;
}
public function getSiteName()
{
return $this->site_name;
}
public function getSiteTitle()
{
return $this->site_title;
}
public function getSiteUrl()
{
return $this->site_url;
}
public function getSiteTags()
{
return $this->site_tags;
}
public function getSiteDesc()
{
return $this->site_desc;
}
}
?>
I have included this file at another file which is called settings.php and called it in this way:
$siteSet = new Site();
$siteSet->getSite("Daygostar");
Then I tried echoing out the variables like this:
<div class="box-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="usr">Site Name:</label>
<input type="text" class="form-control" id="usr" disabled='disabled' value="<?php echo $siteSet->getSiteName; ?>">
</div>
<div class="form-group">
<label for="usr">User URL:</label>
<input type="text" class="form-control" id="usr" disabled='disabled' value="<?php echo $siteSet->getSiteUrl; ?>">
</div>
</div>
</div>
</div>
But the problem is that whenever I call this file ,I receive this error message:
Undefined property: Site::$getSiteName
Undefined property: Site::$getSiteUrl
I don't know what's really going wrong because I have coded everything correctly! So if you know how to solve this question please let me know, I really appreciate that.. Thanks in advance.

Those are both methods. You need to add the () to the end of them to invoke the method.
<div class="box-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="usr">Site Name:</label>
<input type="text" class="form-control" id="usr" disabled='disabled' value="<?php echo $siteSet->getSiteName(); ?>">
</div>
<div class="form-group">
<label for="usr">User URL:</label>
<input type="text" class="form-control" id="usr" disabled='disabled' value="<?php echo $siteSet->getSiteUrl(); ?>">
</div>
</div>
</div>
</div>

Related

Why program show error with : array_key_exists()?

I want to validate form register and I created class UserValidator and I try to check if the username field exists. In my opinion everything is correct, but show me 2 errors
Warning: array_key_exists() expects parameter 2 to be array, null given in C:\xampp\htdocs\class\index.php on line 22
Notice: username is not present in data in C:\xampp\htdocs\class\index.php on line 24.
<?php
if(isset($_POST['submit']))
{
$validation = new UserValidator($_POST);
$errors =$validation->validateForm();
}
<?php
class UserValidator
{
private $data;
private $errors =[];
private static $fields =['username', 'email'];
public function _construct($post_data)
{
$this->data = $post_data;
}
public function validateForm()
{
foreach(self::$fields as $field)
{
if(!array_key_exists($field, $this->data))
{
trigger_error("$field is not present in data");
return;
}
}
$this->validateUsername();
return $this->errors;
}
private function validateUsername()
{
$val = trim($this->data['username']);
if(empty($val))
$this->addError('username', 'username cannot be empty');
else
{
if(!preg_match('/^[a-zA-Z-0-9]{6,12}$/', $val))
{
$this->addError('username', 'username must me 6-12 characters');
}
}
}
private function addError($key, $val)
{
$this->errors[$key] = $val;
}
}
?>
<div id="register">
<h1>REJESTRACJA</h1>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<div class="row">
<div class="col-25">
<label for="loginRe">Login</label>
</div>
<div class="col-75">
<input type="text" name="username" placeholder="Login...">
<div class="error">
<?php echo $errors['username'] ?? '' ?>
</div>
</div>
</div>
<div class="row">
<div class="col-25">
<label for="email">Email</label>
</div>
<div class="col-75">
<input type="text" name="email" placeholder="Email...">
</div>
</div>
<div class="button">
<input type="submit" name="submit" value="Utwórz konto">
</div>
<div class="displayCenter">
<div class="display">
</div>
</div>
</form>
</div>
$this->data is NULL, it is not filled by constructor, the constructor declaration has a typo, missing one _
public function __construct($post_data)
{
$this->data = $post_data;
}
Constructor declaration has a typo, please rectify

How to fix the Add function?

I'm doing a php based project.And I want to add data to the database.I did it using php, PDO. And I created the code with OOC. But There's a if else part in main HTML page. In that part the else part is running. But I didn't even click the insert button. When the page is loading the else part is running. I watched a video and this code is working perfectly fine. Here's the code..
Insert.php - Getters, Setters, SQL query and etc.
class Stock
{
protected $ItemNo;
protected $ItemName;
protected $brand;
protected $qty;
protected $Description;
protected $ItemDate;
protected $SupplierName;
protected $SupplierMail;
private $tableName = 'StockDetails';
private $dbconn;
function setItemNo($ItemNo) { $this->ItemNo = $ItemNo; }
function getItemNo() { return $this->ItemNo; }
function setItemName($ItemName) { $this->ItemName = $ItemName; }
function getItemName() { return $this->ItemName; }
function setBrand($brand) { $this->brand = $brand; }
function getBrand() { return $this->brand; }
function setQty($qty) { $this->qty = $qty; }
function getQty() { return $this->qty; }
function setDescription($Description) { $this->Description = $Description; }
function getDescription() { return $this->Description; }
function setItemDate($ItemDate) { $this->ItemDate = $ItemDate; }
function getItemDate() { return $this->ItemDate; }
function setSupplierName($SupplierName) { $this->SupplierName = $SupplierName; }
function getSupplierName() { return $this->SupplierName; }
function setSupplierMail($SupplierMail) { $this->SupplierMail = $SupplierMail; }
function getSupplierMail() { return $this->SupplierMail; }
public function __construct()
{
require_once ('Database.php');
$db = new Database();
$this->dbconn = $db->connect();
}
public function insert(){
$sql = "INSERT INTO $this->tableName VALUES (:ItemNo, :ItemName, :brand, :qty, :Description, :ItemDate, :SupplierName, :SupplierMail)";
$stmt = $this->dbconn->prepare($sql);
$stmt->bindParam(':ItemNo', $this->ItemNo);
$stmt->bindParam(':ItemName', $this->ItemName);
$stmt->bindParam(':brand', $this->brand);
$stmt->bindParam(':qty', $this->qty);
$stmt->bindParam(':Description', $this->Description);
$stmt->bindParam(':ItemDate', $this->ItemDate);
$stmt->bindParam(':SupplierName', $this->SupplierName);
$stmt->bindParam(':SupplierMail', $this->SupplierMail);
if($stmt->execute()){
return true;
}else{
return false;
}}}
?>
Action.php - Form action on AddItem.php
require_once ('Insert.php');
class action{
function __construct(){
switch ($_POST['submit']) {
case 'insert':
$obInsert = new Stock;
$obInsert->setItemNo($_POST['ItemNo']);
$obInsert->setItemName($_POST['ItemName']);
$obInsert->setBrand($_POST['brand']);
$obInsert->setQty($_POST['qty']);
$obInsert->setDescription($_POST['Description']);
$obInsert->setItemDate(date('Y-m-d H:i:s'));
$obInsert->setSupplierName($_POST['SupplierName']);
$obInsert->setSupplierMail($_POST['SupplierMail']);
if($obInsert->insert()) {
header('location: AddItem.php?insert=1');
} else{
header('location: AddItem.php?insert=0');
}
break;
default:
header('location: AddItem.php');
break;
}
}
}
if(isset($_POST['submit'])){
$object = new action;
}
AddItem.php
To get the brand and ItemName from the Database. The brand changes according to ItemName.
<?php
require_once ('GetBrand.php');
$ItemName = LoadItemName();
?>
$(document).ready(function(){
$("#ItemName").change(function(){
var aid = $("#ItemName").val();
$.ajax({
url: 'GetBrand.php',
method: 'post',
data: 'aid=' + aid
}).done(function(brand){
console.log(brand);
brand = JSON.parse(brand);
$('#brand').empty();
brand.forEach(function(bnamee){
$('#brand').append('<option>' + bnamee.brand + '</option>')
})
})
})
})
The Form
<form name="form0" method="post" action="Action.php">
<div class="form-group">
<label for="text">Item No</label>
<input type="text" name="ItemNo" id="ItemNo" placeholder="Item No" required>
</div>
<form name="form1" action="AddItem.php" method="post">
<div class="form-group">
<label for="text">Item Name</label>
<table>
<tr>
<td><select name="ItemName" id="ItemName" required>
<option value="" disabled="" selected>Select Name</option>
<?php foreach($ItemName as $iname)
echo "<option id='".$iname['ItemNo']."' value='".$iname['ItemNo']."'>".$iname['ItemName']."</option>";
?>
</select></td>
<td><label for="text">Add Item Name : </label></td>
<td><input type="text" name="name" id="name"> </td>
<td><button>Add</button></td>
</tr>
</table>
</div>
<div class="form-group">
<label for="text">Brand Name</label>
<table>
<tr>
<td><select name="brand" id="brand" required>
<option value="">Select Brand</option>
</select></td>
<td<label for="text">Add Brand : </label></td>
<td><input type="text" name="Bname" id="Bname" class="form-control" > </td>
<td><button>Add</button></td>
</tr>
</table>
</div>
</form>
<div class="form-group">
<label for="text">Quantity</label>
<input type="text" name="qty" id="qty" placeholder="Quantity" required>
</div>
<div class="form-group">
<label for="text">Item Description</label>
<input type="text" name="Description" id="Description" placeholder="Description" required>
</div>
<div class="form-group">
<label for="text">Date</label>
<input type="date" name="ItemDate" id="ItemDate" required>
</div>
<div class="form-group">
<label for="text">Supplier Name</label>
<input type="text" name="SupplierName" id="SupplierName" placeholder="Supplier Name" required>
</div>
<div class="form-group">
<label for="text">Supplier Mail</label>
<input type="text" name="SupplierMail" id="SupplierMail" placeholder="Supplier Mail" required>
</div><br/>
<div class="form-group">
<button id="submit" name="submit" value="insert">Insert</button>
<?php
if(isset($_GET['insert']) && ($_GET['insert'] == 1)){
echo "Inserted Successfully ";
}else // This else part is running when the page is loading
echo "Ooops..! Something went wrong.";
}
?>
</div>
</form>
<?php
if(isset($_GET['insert']) && ($_GET['insert'] == 1)){
echo "Inserted Successfully ";
}else // This else part is running when the page is loading
echo "Ooops..! Something went wrong.";
}
?>
you are surprised that this runs?
What you have said here is, if there is a $_GET parameter called insert and it's equal to 1 then echo "inserted..." in any other situation that may exist echo 'oops...'
Php cannot naturally discern whether this is the initial page load, a redirect, a button has been pressed or what you are thinking. If you only want this to run if a button has been been clicked you'd need to add in some extra checks around the whole thing, for example
if(isset($_POST['submit'])) {
///add in your checks to
}
or possibly more suitable for you would be
if(isset($_GET['insert']) {
if($_GET['insert'] == 1)){
echo "Inserted Successfully ";
} else {// you're missing a brace here
echo "Ooops..! Something went wrong.";
}
}
the point is, your code will always run regardless at the moment because it is an if/else i.e. do this or do that - but what you want to say is if a - do b or c, else do nothing. I think you need to try and understand exactly how conditionals work

how to fetch results from select query with class

I am trying to learn select query with class.
Below is index.php, which have a form to display results and I in PHP I am calling class operations, which is in operations.php
<?php
session_start();
include('operations.php');
$userprofileobj = new operations();
$userprofileobj->showuserprofile($_SESSION['user_email']);
$row = $userprofileobj->fetch_assoc();
?>
<form class="form-horizontal" method="post" action="#" name="number_validate" id="number_validate" >
<div class="control-group">
<label class="control-label">Admin Name</label>
<div class="controls">
<input type="text" name="min" id="min" value="<?php echo $row['user_name']; ?>" required />
</div>
</div>
<div class="control-group">
<label class="control-label">User Email</label>
<div class="controls">
<input type="text" name="max" id="max" value="<?php echo $row['user_email']; ?>" required />
</div>
<div class="form-actions">
<input type="submit" value="Update" class="btn btn-success">
</div>
</form>
operations.php is:
class operations{
public $user_email;
public $error;
public $con;
public function __construct()
{
$this->con = new mysqli("localhost","root","","admin_with_oops");
}
public function showuserprofile($user_email)
{
$result = $this->con->query("select * from user_table where user_email='$user_email'");
if($result->num_rows > 0)
{
return $result;
}
else
{
$this->error = "User not exist";
}
}
}
Am I on right way? If yes teh what is the problem on above code?
Error is: Fatal error: Call to undefined method operations::fetch_assoc() in F:\xampp\htdocs\admin_with_oops\HTML\index.php on line 16
$userprofileobj is an instance of the operations class. It doesn't have fetch_assoc() method. You should replace
$userprofileobj->showuserprofile($_SESSION['user_email']);
$row = $userprofileobj->fetch_assoc();
with
$row = $userprofileobj->showuserprofile($_SESSION['user_email'])->fetch_assoc();
Or you could assign the result to a variable and then call the fetch_assoc() function on it:
$result = $userprofileobj->showuserprofile($_SESSION['user_email']);
$row = $result->fetch_assoc();

Unable to fetch data from database in codeigniter php

Once the user login into site unable to fetch the data from database getting blank page if i write foreach condition here is my code.Fetching username and login verification is workig fine.
Controller:
public function index()
{
if($this->session->userdata('admin_logged_in')){
$data['admin_details'] = $this->session->userdata('admin_logged_in');
$data['records']= $this->profile_model->getprofiledata($this->uri->segment(3));
$data['mainpage']='profile';
$this->load->view('templates/template',$data);
}
else{
$this->load->view('welcome');
}
}
Model:
function getprofiledata($id)
{
$this->db->select('profile_details.*');
$this->db->from('profile_details');
$this->db->where(array('profile_details.profile_id'=>$id));
$q=$this->db->get();
if($q->num_rows()>0)
{
return $q->result();
}
else
{
return false;
}
}
View:
<div id="legend">
<legend class="">Profile Information</legend>
</div>
<?php if(isset($records) && is_array($records) && count($records)>0): ?>
<?php foreach($records as $r):?>
<form action="<?php echo base_url();?>profile/updateprofile" role="form" class="form-horizontal" id="location" method="post" accept-charset="utf-8">
<?php
echo form_hidden('profile_id',$r->profile_id);
?>
<div class="form-group">
<label class="control-label col-sm-2 " for="name">Name:</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="name" placeholder="Enter name" value="<?php echo $r->first_name;?>" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2 " for="profilename">Profile Name:</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="profile_name" placeholder="Enter Profile name">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2 " for="designation">Designation:</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="designation" placeholder="Enter Designation">
</div>
</div>
<button type="submit" class="btn">Submit</button>
</form>
<?php endforeach;endif;?>
You chose the wrong segment number on line $data['records']= $this->profile_model->getprofiledata($this->uri->segment(3));.
Take notice that segment counting starts with zero, so segment no 3 is actually the 4th one in the uri.
If you keep the user id inside your session, you should replace $data['records']= $this->profile_model->getprofiledata($this->uri->segment(3)); with $records = $this->profile_model->getprofiledata($this->session->userdata('profile_id'))‌​‌​‌​;. And you're done.
add a new session when you login process like bellow in your login model :
<?php
public function login_user($user_name = '', $password=''){
$userdetails = array(
'email' => $user_name,
'password' => md5($password),
'status'=>1,
);
$this->db->where($userdetails);
$query = $this->db->get('profile_details');
if($query->num_rows()):
$user = $query->result();
$sess_arry = array(
'profile_id' => $user[0]->profile_id, // add new session profile_id
'first_name' => $user[0]->first_name
);
$this->session->set_userdata('admin_logged_in', $sess_arry); //add admin details to session
return true;
else:
return false;
endif;
}
?>
And some change your index method like bellow :
<?php
public function index()
{
if($this->session->userdata('admin_logged_in')){
$data['admin_details'] = $this->session->userdata('admin_logged_in');
$data['country'] = $this->signup_model->getcountry();
$data['states'] = $this->profile_model->getstates();
$profile_id = $this->session->userdata('profile_id');
$records = $this->profile_model->getprofiledata($profile_id)‌​‌​;
$data['records']= $records;
$data['mainpage']='profile';
$this->load->view('templates/template',$data);
$this->load->view('templates/sidebar',$data);
}
else{
$this->load->view('welcome');
}
}
?>
I have added new 3 line because i thinks you are no getting profile id properly in $this->uri->segment(3)
So,
$profile_id = $this->session->userdata('profile_id');
$records = $this->profile_model->getprofiledata($profile_id)‌​‌​;
$data['records']= $records;

Call to a member function query()

I have problem in php i'm using WAMP(php 5.3.13 and mysql 5.5.24). And my problem is when I am testing the register form:
include "config.php";
if(isset($_GET['confirm_registration'])){
User::ConfirmRegistration($_GET['confirm_registration']);
}
if(isset($_POST['confirm_registration'])){
$username= $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if(!Validator::Email($email)){
echo "Invalid email address";
} else {
User::BeginRegistration($username,$email,$password);
}
}
?>
<div id="contentWrapper">
<div id="form">
<form id="signup" method="POST" action="">
<div class="signup_form"><strong>Sign up</strong></div>
<div class="signup_form">
<label>Username</label>
<input type="text" id="username" name="username" size="30">
</div>
<div class="signup_form">
<label>E-Mail</label>
<input type='text' id='email' name='email' size="30">
</div>
<div class="signup_form">
<label>Password</label>
<input type='password' id='password' name='password' size="30">
</div>
<div class="signup_form">
<label></label>
<input type='submit' name="confirm_registration" value='Submit'>
</div>
</form>
</div>
</html>
This is the error :Call to a member function query() on a non-object in C:\wamp\www\zavrsni_rad\classes\DataBase.class.php on line 11
and here is the DataBase class:
class DataBase
{
public static $connection;
public static function Connect(){
self::$connection = new mysqli("localhost","root","","zavrsni_rad");
self::$connection->set_charset("utf8");
}
public static function Execute($query){
self::$connection->query($query);
}
public static function GetString($query){
$r = self::$connection->query($query);
$res_arr = $r->fetch_row();
return $res_arr[0];
}
public static function GetRow($query){
$r = self::$connection->query($query);
return $r->fetch_row();
}
public static function GetTable($query){
$r = self::$connection->query($query);
$res = array();
while($rw = $r->fetch_row()){
$res[] = $rw;
}
return $res;
}
public static function Disconnect(){
self::$connection->close();
}
}
Clearly self::$connection is not yet instantiated when you call Execute() - you should run Connect() before.

Categories