how to fetch results from select query with class - php

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();

Related

PHP If isset() Not Returning Value For HTML Input

I'm having issues with a PHP form that is using the isset() function for input values that have been pulled from a database. When I use the below code, the isset function is returning nothing to the input fields on an edit client form. I'm in need of some help on how I can get this head scratching problem solved.
edit-client.php
<?php
require_once __DIR__ . '/inc/bootstrap.php';
require_once __DIR__ . '/inc/head.php';
require_once __DIR__ . '/inc/nav.php';
$client = getClient(request()->get('client_id'));
$firstName = $client['first_name'];
$lastName = $client['last_name'];
$notes = $client['notes'];
$buttonText = 'Update Client';
?>
<div class="container-fluid">
<div class="row">
<?php include __DIR__ . '/inc/sidebar-nav.php'; ?>
<main role="main" class="col-md-9 ml-sm-auto mt-4 col-lg-10 px-4 main">
<h1 class="h3 border-bottom pb-3 mb-4 text-primary">Edit Client</h1>
<form method="post" action="/procedures/procedure-edit-client.php">
<label for="first_name" class="text-muted">First Name</label>
<input type="hidden" name="first_name" value="<?php if(isset($firstName)) echo $firstName; ?>">
<label for="last_name" class="text-muted">Last Name</label>
<input type="text" id="last_name" name="last_name" class="form-control" value="<?php if(isset($lastName)) echo $lastName; ?>" required>
<label for="notes" class="text-muted">Notes</label>
<textarea id="notes" name="notes" class="form-control" rows="10"><?php if(isset($firstName)) echo $firstName; ?></textarea>
<button type="submit" class="btn btn-action btn-primary">
<?php
if(isset($buttonText)) echo $buttonText;
else echo 'Add New Client';
?>
</button>
</form>
</main>
</div>
</div>
<?php require_once __DIR__ . '/inc/footer.php';
functions.php
function getClient($clientId) {
global $db;
try {
$query = "SELECT * FROM client WHERE client_id = ?";
$stmt = $db->prepare($query);
$stmt->bindParam(1, $clientId);
$stmt->execute();
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch(\Exception $e) {
throw $e;
}
}
Try this i assume you only get one result so returning that first result:
function getClient($clientId) {
global $db;
try {
$query = "SELECT * FROM client WHERE client_id = ?";
$stmt = $db->prepare($query);
$stmt->bindParam(1, $clientId);
$stmt->execute();
$result = $stmt->fetchAll();
return (!empty($result)) ? $result[0] : false;
} catch(\Exception $e) {
throw $e;
}
}
After that check you var_dump($client) again to see your data. Also when client is false, it could not find the client. Adjust your code to check for that also else $client is still empty.

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;

Undefined property error message in PHP OOP

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>

Can't show data with postgres + php

i'm trying to make a web app with php and postgres but i have problems showing the data.
This is my view, it's just a simple login.
<form method="post" action="../Controlador/logueo.php" role="form" class="form-inline">
<div class="form-group">
<input name="nombre" type="text" class="form-control" placeholder="Introduce tu usuario">
</div>
<br>
<div class="form-group">
<br>
<input name="contraseña" type="password" class="form-control"
placeholder="Contraseña">
</div>
<br>
<br>
<button type="submit" class="btn btn-primary">Enviar</button>
</form>
This is ../Controlador/logueo.php and here is where i have problems. I can't show the info in $alumno (the variable in foreach), i tried to make an echo and nothing happens...
<?php
include("../Modelo/alumno.php");
$al = new alumno();
$alumnos = $al->obtenerAlumnos();
echo $alumnos;
foreach ($alumnos as $alumno) {
echo $alumno[0];
if ($alumno[0] == $_POST[nombre] && $alumno[5] == $_POST[contraseña] ){
//Do something
}
}
?>
And this is Modelo/alumno.php
<?php
class alumno
{
function _construct()
{
}
function obtenerAlumnos()
{
include("conexion.php");
$query = "SELECT * FROM alumno";
$result = pg_query($squery);
$alumnos = array();
while ($row = pg_fetch_row($result)) {
array_push($alumnos, $row);
}
return $alumnos;
}
}
?>
finally i have Conexion.php
<?php
$db = pg_connect("host=localhost port=5432 dbname=Tarea3BD user=postgres password=motorola13")
or die('Could not connect: ' . pg_last_error());
?>
Hope someone can help me, i'm new with php and postgres.
Many thanks.

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