This is my code.
index.php file:
$viewer_id = $_SESSION['viewer_id'];
$db = new Database('144.76.6.45','5432','3331','asd','31sd23');
$db->querySelect("SELECT * FROM users WHERE vk_id = $viewer_id");
$row = $db->STH->fetch();
if(empty($row)){
require 'template/default/not_logged.php';
}
else {
require 'template/default/logged.php';
}
This part is understandable. Connecting to database, doing query. If viewer's id is in db - logged.php if not - not_logged.php
Lets say viewers id is already in db.
logged.php file:
<div id="text-right">
<p>Игровой ник: <?php $user->getEuName(); ?></p>
<p>Cоциум: <?php $user->getSociety(); ?></p>
<p>Основная профессия: <?php $user->getMainProfession(); ?></p>
<p>Дополнительная информация: <?php $user->getNotes(); ?></p>
<p>Ищу команду для совместной охоты: <?php $user->getWantTeam(); ?></p>
<div class="edit-info">Редактировать</div>
</div>
This methods are getting info from db.
class User extends Database {
public $vk_id;
public $eu_name;
public $eu_society;
public $eu_notes;
public $eu_want_team;
public $eu_data;
function __construct() {
parent::__construct('144.76.6.45','5432','eu','eu','eu123');
}
function getEuName() {
$this->querySelect("SELECT eu_name FROM users WHERE vk_id = $this->viewer_id");
$row = $this->STH->fetch();
print '<b>'.$row['eu_name'].'</b>';
}
function getSociety() {
$this->querySelect("SELECT eu_society FROM users WHERE vk_id = $this->viewer_id");
$row = $this->STH->fetch();
print '<b>'.$row['eu_society'].'</b>';
}
function getNotes() {
$this->querySelect("SELECT eu_notes FROM users WHERE vk_id = $this->viewer_id");
$row = $this->STH->fetch();
print '<b>'.$row['eu_notes'].'</b>';
}
function getWantTeam() {
$this->querySelect("SELECT eu_want_team FROM users WHERE vk_id = $this->viewer_id");
$row = $this->STH->fetch();
if($row['eu_want_team'] == 'TRUE') {
print '<b>Да</b>';
}
else {
print '<b>Нет</b>';
}
}
function getMainProfession() {
$this->querySelect("SELECT eu_main_profession FROM users WHERE vk_id = $this->viewer_id");
$row = $this->STH->fetch();
print '<b>'.$row['eu_main_profession'].'</b>';
}
}
$user = new User();
And this is user class with get methods.(he is included in index.php like database.php(db connection class) is).
Everything is ok, but when viewer comes to page, the data of methods(query results) doesn't show, they show only AFTER RELOAD! I don't know whats the problem. Please solution.
Thanks!
Related
I have a problem with my script. I have been using this same script for months. Lat week I got a message from my client that cannot access their
dashboard anymore. I check it was showing too much redirect problem. I
quickly made attempt to solve this programming but all availed. I found out
that the session actually set on the Login page because I echo it out
without redirecting, but whenever I redirect to member dashboard the session
variable will be undefined. I have gone through other people similar problem
on this forum but none were able to proffer solution to my problem. Because
this same script has been working for months. Please take a look at the code
and help me out.
This is Login page. Login.php The session actually set because when display LoginId when I echo echo it out. but lost when redirecting to another page. though It was working for more four months before this unexpected problem
<?php
require("includes/config.php");
require_once(ROOT_PATH . "main/class.member.php");
$auth_member = new MEMBER();
if($auth_member->is_loggedin() != ""){
$auth_member->redirect(BASE_URL.'member');
}
if(isset($_POST['loginMemBtn'])){
$userLoginID = strip_tags($_POST['userID']);
$password = strip_tags($_POST['password']);
if($auth_member->memberLogin($userLoginID, $password)){
$auth_member->redirect(BASE_URL.'member');
}
else{
$error[] = "Inccorrect Login Details!";
}
}
?>
class.member.php
This is the class that holds all the member details and where the session
was set. It contain MemberLogin Function
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once(ROOT_PATH.'includes/dbconnect.php');
// Class
class MEMBER{
private $connect;
public function __construct(){
$database = new Database();
$db = $database->dbConnection();
$this->connect = $db;
}
public function lastInsertId(){
return $this->connect->lastInsertId();
}
public function runQuery($sql){
$stmt = $this->connect->prepare($sql);
return $stmt;
}
public function memberLogin($userLoginID, $password){
try {
$stmt = $this->connect->prepare("SELECT * FROM members
WHERE status='Active'
AND (email=:email OR phone=:phone OR username=:email)
");
$stmt->execute(array(':email'=>$userLoginID, ':phone'=>$userLoginID));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0) {
if(password_verify($password, $userRow['password'])) {
$_SESSION['member_session'] = $userRow['login_id'];
return true;
}else{
return false;
}
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
public function is_allowuser(){
if(isset($_SESSION['member_session'])) {
return true;
}
}
public function redirect($url){
header("Location: $url");
}
public function doMememberLogout(){
session_destroy();
unset($_SESSION['member_session']);
return true;
}
}
?>
session.php this file that check whether session is set or not and it
include i to all other script
<?php
$session = new MEMBER();
if(!$session->is_allowuser()){
$session->redirect(BASE_URL.'login');
exit();
}else{
$auth_member = new MEMBER();
$loginID = $_SESSION['member_session'];
$stmt = $auth_member->runQuery("SELECT * FROM members WHERE
login_id=:loginID");
$stmt->execute(array(":loginID"=>$loginID));
$userInfo = $stmt->fetch(PDO::FETCH_ASSOC);
if($userInfo['status'] != 'Active'){
unset($_SESSION['member_session']);
}
}
?>
This is dashboard.php this is the page that member redirect to from Login
Page
<?php
require("../includes/config.php");
require_once(ROOT_PATH . "main/class.member.php");
require_once(ROOT_PATH . "main/session.php");
//echo $_SESSION['member_session'];
?>
public function redirect($url){
header("Location: $url");
exit;
}
Use exit after header call in redirect method of class.member.php file
I'm fairly new using PHP classes, I have done some PHP using the procedural method for a while but never fully done proper object oriented programming on php. Which brings me to my question:
I have one file called classes.php where I intend to define all my php classes. Inside that file I have created a class as follows:
require_once("connection.php");
class User
{
public function getUserInfo() {
$userinfo = mysqli_query($con,"SELECT * FROM users WHERE username='". $_SESSION['username'] ."'");
while($row = mysqli_fetch_assoc($userinfo)) {
// USER DETAILS:
$userid = $row['id'];
$username = $row['username'];
$userfirstname = $row['first_name'];
$userlastname = $row['last_name'];
$useremail = $row['email'];
$useraddress1 = $row['address_line_1'];
$useraddress2 = $row['address_line_2'];
$userpostcode = $row['postcode'];
$userphone = $row['phone'];
$usermobile = $row['mobile'];
$usercreated = $row['created'];
$usermodified = $row['modified'];
$useraccess = $row['access_level'];
}
}
} // end of User
Now I want to use the values of the variables defined in that class in another page. But how can I access those values?
So far I'm trying this (unsuccessfully):
<?php
include "php_includes/classes.php";
$user = new User();
?>
<div class="somediv">
<?php echo $user->getUserInfo($username) ?>
</div>
I have also tried:
<?php
include "php_includes/classes.php";
$user = new User();
?>
<div class="somediv">
<?php echo $user->$username ?>
</div>
Is there any way to echo those variables in another page so I can use the user information in, for example, profile pages?
Thanks in advance.
you should return the value from function.
require_once("connection.php");
class User
{
public function getUserInfo() {
$userinfo = mysqli_query($con,"SELECT * FROM users WHERE username='". $_SESSION['username'] ."'");
$row = mysqli_fetch_assoc($userinfo);
return row
}
}
and now only have to show the detail of user
<?php
include "php_includes/classes.php";
$user = new User();
?>
<div class="somediv">
<?php $user_detail=$user->getUserInfo(); ?>
<label>name:</label><br>
<?php echo $user_detail["first_name"]; ?>
</div>
Hence you can check whether row is null or not and whole array can be returned by this function of class any where this class included in file.
Before your function you need make PUBLIC VARIABLE like:
public $userid;
Then next in code in function you need to use:
$this->userid = $row['id'];
EDIT
Your calss need to be:
class User
{
public $userid;
public function getUserInfo() {
$userinfo = mysqli_query($con,"SELECT * FROM users WHERE username='". $_SESSION['username'] ."'");
while($row = mysqli_fetch_assoc($userinfo)) {
// USER DETAILS:
$this->$userid = $row['id'];
}
}
} // end of User
And you also need include this class file in other php page when you want show data.
you have to declare the variable as PUBLIC
class User
{
public function getUserInfo() {
$userinfo = mysqli_query($con,"SELECT * FROM users WHERE username='". $_SESSION['username'] ."'");
while($row = mysqli_fetch_assoc($userinfo)) {
// USER DETAILS:
public $userid = $row['id'];
}
}
}
For more information check here
this may be a stupid question, but every source on the web seems not able to fully explain the logic to my complex brain
There's an edit page getting a $_GET['id'] from a link.
I got a function on my class elaborating this one to create an array of values from the database which must fill the form fields to edit datas. The short part of this code:
public function prel() {
$this->id= $_GET['id'];
}
public function EditDb () {
$connetti = new connessionedb();
$dbc = $connetti->Connessione();
$query = "SELECT * from anammi.anagrafica WHERE id = '$this->id'";
$mysqli = mysqli_query($dbc, $query);
if ($mysqli) {
$fetch = mysqli_fetch_assoc($mysqli);
return $fetch;
}
}
This array (which i tried to print) is perfectly ready to do what i'd like.
My pain starts when i need to pass it to the following function in the same class, which perhaps calls a parent method to print the form:
public function Associa() {
$a = $this->EditDb();
$this->old_id = $a['old_id'];
$this->cognome = $a['cognome'];
$this->nome = $a['nome'];
$this->sesso = $a['sesso'];
$this->tipo_socio_id = $a['tipo_socio_id'];
$this->titolo = $a['titolo']; }
public function Body() {
parent::Body();
}
How do i have to pass this $fetch?
My implementation:
<?php
require_once '/classes/class.ConnessioneDb.php';
require_once '/classes/class.editForm';
$edit = new EditForm();
$edit->prel();
if ($edit->EditDb()) {
$edit->Associa();
$edit->Body();
if (if ($edit->EditDb()) {
$edit->Associa();
$edit->Body();) {
$edit->Associa();
$edit->Body();
your Editdb method is returning a string and you are checking for a boolean condition in if statement. this is one problem.
using fetch-
$fetch=$edit->EditDb();
$edit->Associa();
$edit->Body($fetch);
Posting the full code of it:
public function prel() {
$this->id= $_GET['id'];
}
public function EditDb () {
$connetti = new connessionedb();
$dbc = $connetti->Connessione();
$query = "SELECT * from table WHERE id = '$this->id'";
$mysqli = mysqli_query($dbc, $query);
if ($mysqli) {
$fetch = mysqli_fetch_assoc($mysqli);
return $fetch;
}
}
public function Associa($fetch) {
$this->old_id = $fetch['old_id'];
$this->cognome = $fetch['cognome'];
$this->nome = $fetch['nome'];
$this->sesso = $fetch['sesso']; //it goes on from there with many similar lines
}
public function Body() {
$body = form::Body();
return $body;
}
Implementation
$edit = new EditForm();
$edit->prel();
$fetch=$edit->EditDb();
$edit->Associa($fetch);
$print = $edit->Body();
echo $print;
Being an edit form base on a parent insert form, i added an if in the parent form that sees if is set an $_GET['id] and prints the right form header with the right form action. This was tricky but really satisfying.
Method in my class does it work properly. Don't give me some error message, but simply does not work.
public function query($value)
{
$this->__error = FALSE;
$sql = "SELECT * FROM users WHERE username = ".Input::input($value);
if ($this->__query = $this->__pdo->query($sql))
{
$this->__result = $this->__query->fetchAll(PDO::FETCH_OBJ);
$this->__count = $this->__query->rowCount(); //Here is the problem
}
else {
$this->__error = TRUE;
}
return $this;
}
public function count()
{
return $this->__count;
}
But I would not write whole class code, I mention that PDO DataBase connection is properly defined ($_pdo property), also the instance who is responsible to comunicate with database. ($_instance property). Input class too.
Here is my index.php (some kind of registration form):
<?php
spl_autoload_register(function($class) //Load all class in project
{
require_once 'class/'.$class.'.php';
}
);
$user = DataBase_class::instance()->query("username"); //username is the name of textbox
if ($user->count())
{
echo 'User exist';
}
else echo 'User not exist';
?>
Result is "User not exist", although user exist 100%.
You forget the quotes
$sql = "SELECT * FROM users WHERE username = '".Input::input($value) . "'";
but you should consider to use prepared statements..
$stmt = $this->__pdo->prepare("SELECT * FROM users WHERE username = :name");
$stmt->bindParam(':name', Input::input($value));
$result = $stmt->execute();
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 8 years ago.
Hihow r u all?
I m trying to calculate basic salary with Particular employee_id but when i m trying to .. give me fatal error..
Fatal error: Call to a member function num_rows() on a non-object in D:\wamp\www\template\application\models\salary.php on line 112
my code is: model
<?php
class Salary extends Model
{
/*
Determines if a given person_id is a profile
*/
function exists($salary_id)
{
$this->db->from('salary_scale');
$this->db->where('id',$salary_id);
$this->db->where('deleted',0);
$query = $this->db->get();
return ($query->num_rows()==1);
}
/*
Determines if a given employee_id is a employee
*/
function exists_employee($employee_id)
{
$this->db->from('grade_history');
$this->db->where('employee_id',$employee_id);
$query = $this->db->get();
return ($query->num_rows()==1);
}
/*
Returns all the suppliers
*/
function get_all()
{
$this->db->from('salary_scale');
$this->db->where('deleted', 0);
$this->db->order_by("name", "asc");
return $this->db->get();
}
/*
*
* Gets information about a particular employees salary
*/
function grade_rules_info($salary_grade)
{
$this->db->from('salary_scale_rules');
$this->db->where('salary_grade',$salary_grade);
$query = $this->db->get();
if($query->num_rows()==1)
{
return $query->row();
}
else
{
//Get empty base parent object, as $item_id is NOT an item
$salary_obj=new stdClass();
//Get all the fields from items table
$fields = $this->db->list_fields('salary_scale_rules');
foreach ($fields as $field)
{
$salary_obj->$field='';
}
return $salary_obj;
}
}
/*
*
* Gets information about a particular employees salary
*/
function get_info($employee_id)
{
$this->db->from('allowance');
//$this->db->join('deductions', 'deductions.eid = allowance.eid');
$this->db->where('employee_id',$employee_id);
$query = $this->db->get();
if($query->num_rows()==1)
{
return $query->row();
}
else
{
//Get empty base parent object, as $item_id is NOT an item
$salary_obj=new stdClass();
//Get all the fields from items table
$fields = $this->db->list_fields('items');
foreach ($fields as $field)
{
$salary_obj->$field='';
}
return $salary_obj;
}
}
/**
* Gets information about a particular employees salary
*
**/
function get_grade_info($employee_id)
{
$this->db->from('grade_history');
$this->db->where('employee_id',$employee_id);
$query = $this->db->get();
if($query->num_rows()==1)
{
return $query->row();
}
else
{
//Get empty base parent object, as $employee_id is NOT an employee
$grade_obj=new stdClass();
//Get all the fields from items table
$fields = $this->db->list_fields('grade_history');
foreach ($fields as $field)
{
$grade_obj->$field='';
}
return $grade_obj;
}
}
/**
* Inserts or updates configuration data
*
*/
function save_grade(&$data, $employee_id=false)
{
if (!$employee_id)
{
if($this->db->insert('grade_history', $data))
{
$data['id']=$this->db->insert_id();
return true;
}
return false;
}
$this->db->where('id', $employee_id);
return $this->db->update('grade_history', $data);
}
// ------------------------ End of save_salary_cinfig function -----------------------------
/*
* Basic pay salary calculation
*/
function basic_pay($employee_id)
{
// Get grade information from grade_history table
// Get Particular person grade ifnormation by employ_id
$grade_info = $this->get_grade_info($employee_id);
$salary_grade = $grade_info->salary_grade;
$no_of_increment = $grade_info->number_of_increment;
// Get Grade rules information about particular grade by passing $salary_grade number
$grade_rules = $this->grade_rules_info($salary_grade);
$basic_amount = $grade_rules->basic_amount;
$increment = $grade_rules->increment;
$max_no_of_increment = $grade_rules->number_of_increment;
$max_amount = $grade_rules->max_amount;
return $basic_pay = $basic_amount + $increment*$no_of_increment;
}
}
?>
controller
<?php
require_once ("secure_area.php");
class Salaries extends Secure_area
{
function __construct()
{
parent::__construct('salaries');
}
function index()
{
$data['controller_name']=strtolower($this->uri->segment(1));
$data['form_width']=$this->get_form_width();
$data['manage_table']=get_profile_manage_table($this->Profile->get_all(),$this);
$this->load->view('salaries/manage',$data);
}
/*
Returns profile table data rows. This will be called with AJAX.
*/
function search()
{
$search=$this->input->post('search');
$data_rows=get_profile_manage_table_data_rows($this->Profile->search($search),$this);
echo $data_rows;
}
/*
Gives search suggestions based on what is being searched for
*/
function suggest()
{
$suggestions = $this->Profile->get_search_suggestions($this->input->post('q'),$this->input->post('limit'));
echo implode("\n",$suggestions);
}
/*
Loads the profile form
*/
function view($employee_id=-1)
{
//$data['salary_summary_info'] =$this->Salary->get_info($salary_id);
//$data['salary_deductions_summary_info'] =$this->Salary->get_deductions_info($salary_id);
$employee_id = array('' => '-- Select Employee ID --');
foreach($this->Profile->get_employee_id()->result_array() as $row)
{
$employee_id[$row['employee_id']]= $row['employee_id'];
}
$data['employee_id'] = $employee_id;
// $data['selected_employee_id'] = $this->Profile->get_info($employee_id)->employee_id;
$data['basic_pay'] = $this->Salary->basic_pay($employee_id);
$this->load->view("salaries/salary_summary_form", $data);
}
//--------------------------------------End view function-----------------------------------
/*
Loads the profile form
*/
function grade_view($employee_id=-1)
{
$data['salary_grade_info'] = $this->Salary->get_grade_info($employee_id);
$data['basic_pay'] = $this->Salary->basic_pay($employee_id);
$this->load->view("salaries/grade_view", $data);
}
//--------------------------------------End view function-----------------------------------
/*
Inserts/updates a profile
*/
function save_salary_grade($id=-1)
{
$grade_data = array(
'eid' =>$this->input->post('employee_id'),
'salary_grade' =>$this->input->post('salary_grade'),
'number_of_increment' =>$this->input->post('number_of_increment'),
'comments' =>$this->input->post('comments'),
'date' =>date('Y-m-d H:i:s')
);
if($this->Salary->save_grade($grade_data, $id))
{ //New profile
if($id==-1)
{
echo json_encode(array('success'=>true,'message'=>$this->lang->line('profiles_successful_adding').' '.
$grade_data['salary_grade'].' '.$grade_data['number_of_increment'],'id'=>$grade_data['eid']));
}
else //previous profile
{
echo json_encode(array('success'=>true,'message'=>$this->lang->line('profiles_successful_updating').' '.
$grade_data['salary_grade'].' '.$grade_data['number_of_increment'],'id'=>$grade_data['eid']));
}
}
else//failure
{
echo json_encode(array('success'=>false,'message'=>$this->lang->line('profiles_error_adding_updating').' '.
$grade_data['salary_grade'].' '.$grade_data['number_of_increment'],'id'=>$grade_data['id']));
}
}
/*
This deletes profiles from the profiles table
*/
function delete()
{
$profiles_to_delete=$this->input->post('ids');
if($this->Profile->delete_list($profiles_to_delete))
{
echo json_encode(array('success'=>true,'message'=>$this->lang->line('profiles_successful_deleted').' '.
count($profiles_to_delete).' '.$this->lang->line('profiles_one_or_multiple')));
}
else
{
echo json_encode(array('success'=>false,'message'=>$this->lang->line('profiles_cannot_be_deleted')));
}
}
/*
get the width for the add/edit form
*/
function get_form_width()
{
return 900;
}
}
?>
and view
<?php
echo form_open('salaries/save/'.$employee_id, array('id'=>'salary_summary_form'));
//echo form_open('salaries/save/', array('id'=>'salary_summary_form'));
?>
<div id="required_fields_message"><?php echo $this->lang->line('common_fields_required_message'); ?></div>
<ul id="error_message_box"></ul>
<fieldset id="salary_allowance_info">
<legend><?php echo $this->lang->line("salaries_allowance_info"); ?></legend>
<div class="field_row clearfix">
<?php echo form_label($this->lang->line('salaries_employee_id').':', 'employee_id', array('class'=>'required')); ?>
<div class='form_field'>
<?php echo form_dropdown('employee_id', $employee_id);?>
</div>
</div>
<div class="field_row clearfix">
<?php echo form_label($this->lang->line('salaries_allowance_basic_salary').':', 'basic_salary', array('class'=>'required')); ?>
<div class='form_field'>
<?php echo form_input(array(
'name'=>'basic_salary',
'id'=>'basic_salary',
'value'=>$basic_pay
));
?>
</div>
</div>
<div class="field_row clearfix">
<?php echo form_label($this->lang->line('salaries_allowance_house_rent').':', 'house_rent',array('class'=>'required')); ?>
<div class='form_field'>
<?php echo form_input(array(
'name'=>'house_rent',
'id'=>'house_rent',
// 'value'=>$salary_summary_info->house_rent
));
?>
</div>
</div>
<?php
echo form_submit(array(
'name'=>'submit',
'id'=>'submit',
'value'=>$this->lang->line('common_submit'),
'class'=>'submit_button float_right')
);
?>
</fieldset>
<?php
echo form_close();
?>
pls help me if any one
You don't test if your call to $db -> get() succeeded. I don't know the details of your $db class, but I suspect it only returns something if the call to it was successful. If the query fails does $db -> get() still return something?
Try doing a var_dump on what you get out of $db -> get() so you can see if it's returning what you think it's returning.
Fatal error: Call to a member function num_rows() on a non-object... is usually because there were no results return from a given query or possibly from a bad query.