Display user specific data in html form with oop php - php

I wanted to show a form specific to user with his personal detailes, and then allow him to update that information. But in order to do that first i need to show his detailes in the form so he can update them.
I have a function ShowUserInformation() in class MyClass:
function ShowUserInformation()
{
$query = "SELECT id, name, email FROM saloni WHERE id = '$_SESSION[ID_korisnika]'";
$result = mysql_query($query);
while($row=mysql_fetch_array($result)):
$id= $row['id'];
$name= $row['name'];
$email = $row['email'];
endwhile;
return $result;
}
My question is: How can i display value of $name, or $email, or $id on another page in text box?
If i do it in procedural way it works when i do this:
<input type="text" value="<?php echo $name ?>" name="name" class="" />
But, how can i display the $name,$email,$ID... in oop way?And there won't be just these 3 variables, there will be much more so i need something that can apply to that.
i've included file, created object...
$my_class = new MyClass; //create an object of class
HTML - i've tried something like this...
<input type="text" value="<?php echo $my_class->ShowUserInformation($name)?>" name="name" class="" />
I'm new in PHP and oop so be easy with me :)
Thank you

You ShowUserInformation() function must be return a $name. In you code a function return $result
And HTML must be looks like that:
<input type="text" value="<?php echo $my_class->ShowUserInformation() ?> name="name" class="" />

Fast and dirty way:
class YourClass {
/**
* Ident
*/
public $id;
/**
* Name
*/
public $name;
/**
* Mail
*/
public $email;
public function showUserInformation($name) {
//[...]
while($row=mysql_fetch_array($result)):
$this->id= $row['id'];
$this->name= $row['name'];
$this->email = $row['email'];
endwhile;
//[...]
}
}
<input type="text" value="<?php echo $my_class->name?>" name="name" class="" />

Related

undefined variable while updating

Here my aim to update a book's information with title which I set in the textbox. But in my code I when I run I'm getting the error as $query2 is undefined in $query2['status']=="Available". Can anyone rectify my error?
<?php
$user="root";
$server="localhost";
$password="";
$db="library book";
$query=mysql_connect($server,$user,$password);
$dbRes = mysql_select_db($db,$query);
if(isset($_GET['book_id']))
{
$bookid = $_GET['book_id'];
$str="select * from books where bookid=$bookid";
$query1=mysql_query($str);
//echo $query1;
$query2=mysql_fetch_array($query1);
//print_r ($query2);
}
if(isset($_POST['Update']))
{
$title=mysql_real_escape_string($_POST['title']);
$author=mysql_real_escape_string($_POST['author']);
$publisher=mysql_real_escape_string($_POST['publisher']);
$numcopies=mysql_real_escape_string($_POST['numcopies']);
$shelfno=mysql_real_escape_string($_POST['shelfno']);
$status=mysql_real_escape_string($_POST['status']);
$str1="update books set title=$title where bookid=$bookid";
$query3=mysql_query($str1);
echo $query3;
$query4=mysql_query("select * from books");
$row=mysql_fetch_array($query3);
echo "<table>";
echo "<tr><th>BookID</th><th>Title</th><th>Author</th><th>Publisher</th><th>numcopies</th><th>shelfno</th><th>status</th><th>Action</th></tr>";
echo "<tr>";
echo "<td>".$row['bookid']."</td>";
echo "<td>".$row['title']."</td>";
echo "<td>".$row['author']."</td>";
echo "<td>".$row['publisher']."</td>";
echo "<td>".$row['numcopies']."</td>";
echo "<td>".$row['shelfno']."</td>";
echo "<td>".$row['status']."</td>";
echo "</tr>";
echo "</table>";
if ($query2['status']=="Available")
echo "selected";
if ($query2['status']=="Unavailable")
echo "selected";
}
?>
<html>
<head><title>Editing the fields</title>
<style>
body {
background-color: rgb(255,0,255);
}
</style>
</head>
<body>
<form action="edit1.php" action="post">
EnterTitle:<input type="text" name="title" value="<?php echo $query2['title'];?>">
<br/>
EnterAuthor:<input type="text" name="author" value="<?php echo $query2['author'];?>" >
<br/>
EnterPublisher:<input type="text" name="publisher" value="<?php echo $query2['publisher'];?>">
<br/>
EnterNumCopies:<input type="text" name="numcopies" value="<?php echo $query2['numcopies'];?>">
<br/>
EnterShelfNo:<input type="text" name="shelfno" value="<?php echo $query2['shelfno'];?>">
<br/>
<input type="hidden" name="bookid" value=<?php if(isset($bookid)) echo $bookid; ?>>
<select>
<option value="available" <?php if ($query2['status']=="Available") echo "selected";?>>Available</option>
<option value="unavailable" <?php if ($query2['status']=="Unavailable") echo "selected";?>>Unavailable</option>
</select>
<br>
<input type="submit" name="submit" value="Update">
</form>
</body>
</html>
I think unfortunately, what you have going on here is the beginnings of a "spaghetti code" syndrome so you will want to invest in learning a PHP framework. You will have less chance of security issues, your script will be cleaner from the get-go, more-easily maintained, etc.
For this particular snippet, among other things, you have sql injection issues, you set bookid by $_GET and $_POST but it's hard to determine which is best to use, you have html happening above the <html> tag, but the main problem you are experiencing is that you have variables that are defined in an if scope but are also referenced outside of that if scope so will create the error(s) when the if condition is not satisfied (See this example for more reference).
Some suggestions besides fixing the scope issue:
Use PDO or mysqli_ with parameter binding. My example uses PDO
Use functions or class/method for both usability and readability in your final layout (it looks more complex as I have it below, but only because it's all pasted on one page. Each page should be separate). All of this $query, $query1, $query2, etc. gets confusing. I have used functions, but a class would have been better to pass bookid to all the methods internally.
Standardize your book id key name, either make it book_id or bookid, not both. My example uses bookid.
There are probably some flaws in this, but hopefully it gives you some useful ideas and as I said before, this would be more useful implemented as a class (a few classes actually) but using functions might be a good start to help clean your scripting up.
IMPORTANT NOTE: I have not tested this (there should be no syntax errors though) but you should be able to get the idea about what is happening and what things are for by paralleling your version to this one. If you don't understand it, read up on it first, don't blindly copy and paste or you will get into more trouble. Use at your own risk, as they say.
/functions/getBooks.php
# Create a general function to fetch all books.
function getBooks($con)
{
$result = array();
$query = $con->prepare("SELECT * FROM books");
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
return $result;
}
/functions/getBookById.php
# Create a function to fetch a specific book by id
function getBookById($id,$con)
{
$query = $con->prepare("SELECT * FROM books WHERE bookid = :id");
$query->execute(array(":id"=>$id));
$row = $query->fetch(PDO::FETCH_ASSOC);
return (!empty($row))? $row : array();
}
/functions/getBook.php
# This should fetch from a global request, that way you can tell if
# a book is currently being accessed
function getBook($con)
{
autoload(array('getBookById','getId'));
$id = getId('req');
if(empty($id))
return false;
return getBookById($id,$con);
}
/functions/updateBookById.php
# Create an update function that can be accessed at anytime. Use binding
# so you don't need to mess with any sort of escaping
function updateBookById($id,$values,$con)
{
foreach($values as $keys => $vals) {
$bKey = ":{$keys}";
$bind[$bKey] = $vals;
$sql[] = '`'.$key.'` = '.$bKey;
}
$bind[":id"] = $id;
$query = $con->prepare("UPDATE books SET ".implode(', ',$sql)." WHERE bookid = :id");
$query->execute($bind);
}
/functions/updateBookTitle.php
# This is is just a specific function to focus on title. Not sure you need
# it since the update book by id function would do the same thing
function updateBookTitle($id,$title,$con)
{
$bind[":id"] = $id;
$bind[":title"] = $title;
$query = $con->prepare("UPDATE books SET title = :title WHERE bookid = :id");
$query->execute($bind);
}
/functions/getId.php
# This will fetch the id value from a global
function getId($type = false)
{
switch($type) {
case('post'):
return (isset($_POST['bookid']))? $_POST['bookid'] : false;
case('req'):
return (isset($_REQUEST['bookid']))? $_REQUEST['bookid'] : false;
default:
return (isset($_GET['bookid']))? $_GET['bookid'] : false;
}
}
/functions/bookObserver.php
# This will sit and just wait for the right globals activate it
function bookObserver($con,&$curr)
{
autoload('getId');
if(getId('req')) {
autoload('getBookById');
$books = getBookById(getId('req'),$con);
if(!empty($books))
$curr = $books;
if(isset($_POST['Update'])) {
$values = array(
'title' => $_POST['title'],
'author' => $_POST['author'],
'publisher' => $_POST['publisher'],
'numcopies' => $_POST['numcopies'],
'shelfno' => $_POST['shelfno'],
'status' => $_POST['status']
);
autoload('updateBookById');
updateBookById(getId('req'),$values,$con);
}
}
}
/functions/bookListObserver.php
# This sits and waits for the update to write the table to the page
function bookListObserver($current,$con)
{
if(isset($_POST['Update'])) {
autoload('bookList');
echo bookList(((!empty($current['status']))? $current['status'] : false),$con);
}
}
/functions/getValue.php
# This will just check if a value is set. Saves on scripting
function getValue($array,$key,$def = false)
{
return (!empty($array[$key]))? $array[$key] : $def;
}
/functions/bookList.php
# Displays your book list. Currently you are only showing the last book,
# which doesn't appear correct. No point in getting all books but only showing
# the last one
function bookList($selected = false,$con)
{
autoload('getBooks');
$books = getBooks($con);
ob_start();
?>
<table>
<tr>
<th>BookID</th>
<th>Title</th>
<th>Author</th>
<th>Publisher</th>
<th>numcopies</th>
<th>shelfno</th>
<th>status</th>
<th>Action</th>
</tr>
<?php foreach($books as $row) { ?>
<tr>
<td><?php echo $row['title'] ?></td>
<td><?php echo $row['author'] ?></td>
<td><?php echo $row['publisher'] ?></td>
<td><?php echo $row['numcopies'] ?></td>
<td><?php echo $row['shelfno'] ?></td>
<td><?php echo $row['status'] ?></td>
</tr>
<?php } ?>
</table>
<?php
if($selected == "Available")
echo "selected";
elseif($selected == "Unavailable")
echo "selected";
$data = ob_get_contents();
ob_end_clean();
return $data;
}
/functions/connect.php
# This is your mysql connection, it requires attention to build out
# It's not as useful as it could be, so you will want to research it
function connect()
{
return new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER,DB_PASS);
}
/functions/autoload.php
# This is just a handy function to autoload functions when you want
# to use them. If you used classes, you would make an spl_autoload_register()
# function or install something like Composer to autoload
function autoload($name,$run = false)
{
if(is_array($name)) {
foreach($name as $func) {
autoload($func);
}
return;
}
if(!function_exists($name)) {
if(is_file($file = FUNCTIONS.DS.$name.'.php'))
include_once($file);
}
if($run) {
if(function_exists($name))
return $name();
}
}
/config.php
# Make sure errors are on in testing
ini_set('display_errors',1);
error_reporting(E_ALL);
# Creating commonly-used defines will help your scripts be
# more reliable and consistent
define('DS',DIRECTORY_SEPARATOR);
define('ROOT_DIR',__DIR__);
define('FUNCTIONS',ROOT_DIR.DS.'functions');
define('DB_HOST','localhost');
define('DB_NAME','library book');
define('DB_USER','root');
define('DB_PASS','');
# Start session by default
session_start();
require_once(FUNCTIONS.DS.'autoload.php');
# Autoload the connect function and assign it
$con = autoload('connect',true);
/index.php
<?php
# Add config
include(__DIR__.DIRECTORY_SEPARATOR.'config.php');
# Include all our starting page functions
autoload(array('bookObserver','bookListObserver','getBook', 'getValue'));
# Set default array for current selection
$current = array();
# Start observer, pass connection
bookObserver($con,$current);
?>
<html>
<head><title>Editing the fields</title>
<style>
body {
background-color: rgb(255,0,255);
}
</style>
</head>
<body>
<?php
# This writes the table if update is set
# You should not put this html above the <html> tag
bookListObserver($current,$con);
# This gets the book from the page request
$book = getBook($con);
?>
<form action="edit1.php" action="post">
EnterTitle:<input type="text" name="title" value="<?php echo getValue($book,'title') ?>"><br/>
EnterAuthor:<input type="text" name="author" value="<?php echo getValue($book,'author') ?>" ><br/>
EnterPublisher:<input type="text" name="publisher" value="<?php echo getValue($book,'publisher') ?>"><br/>
EnterNumCopies:<input type="text" name="numcopies" value="<?php echo getValue($book,'numcopies') ?>"><br/>
EnterShelfNo:<input type="text" name="shelfno" value="<?php echo getValue($book,'shelfno') ?>"><br/>
<input type="hidden" name="bookid" value="<?php echo getValue($book,'bookid') ?>" />
<select>
<option value="available" <?php if(isset($current['status']) && $current['status'] == "Available") echo "selected";?>>Available</option>
<option value="unavailable" <?php if (isset($current['status']) && $current['status'] == "Unavailable") echo "selected";?>>Unavailable</option>
</select><br>
<input type="submit" name="submit" value="Update">
</form>
</body>
</html>

Editing SQL Database using PHP

While editing a specific record using PHP code given below, all records in the database are edited simultaneously to the some garbage values. Here "db" is the Database. I am new to PHP and SQL. Please help
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($reportno, $dateofreceipt, $title, $type, $issuingagency, $markedto, $date, $remarks, $isdate, $issuedto, $returndate)
{
?>
<!DOCTYPE HTML PUBLIC >
<html>
<head>
<title>Edit Record</title>
</head>
<body>
<form action="edit.php" method="post">
<div>
<p><strong>Report No.:</strong> <?php echo $reportno; ?></p>
<strong>Date of receipt: *</strong> <input type="date" name="dateofreceipt" value="<?php echo $dateofreceipt; ?>"/><br/>
<strong>Report Title: *</strong> <input type="text" name="title" value="<?php echo $title; ?>"/><br/>
<strong>Report Type: *</strong> <input type="text" name="type" value="<?php echo $type; ?>"/><br/>
<strong>Issuing agency: *</strong> <input type="text" name="issuingagency" value="<?php echo $issuingagency; ?>"/><br/>
<strong>Marked to: *</strong> <input type="text" name="markedto" value="<?php echo $markedto; ?>"/><br/>
<strong>Date: *</strong> <input type="date" name="date" value="<?php echo $date; ?>"/><br/>
<strong>Remarks: *</strong> <input type="text" name="remarks" value="<?php echo $remarks; ?>"/><br/>
<strong>Issuing Date: *</strong> <input type="date" name="isdate" value="<?php echo $isdate; ?>"/><br/>
<strong>Issued To: *</strong> <input type="text" name="issuedto" value="<?php echo $issuedto; ?>"/><br/>
<strong>Return Date: *</strong> <input type="date" name="returndate" value="<?php echo $returndate; ?>"/><br/>
<p>* Required</p>
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$reportno = $_POST['reportno'];
$dateofreceipt = mysql_real_escape_string(htmlspecialchars($_POST['dateofreceipt']));
$title = mysql_real_escape_string(htmlspecialchars($_POST['title']));
$type = mysql_real_escape_string(htmlspecialchars($_POST['type']));
$issuingagency = mysql_real_escape_string(htmlspecialchars($_POST['issuingagency']));
$markedto = mysql_real_escape_string(htmlspecialchars($_POST['markedto']));
$date = mysql_real_escape_string(htmlspecialchars($_POST['date']));
$remarks = mysql_real_escape_string(htmlspecialchars($_POST['remarks']));
$isdate = mysql_real_escape_string(htmlspecialchars($_POST['isdate']));
$issuedto = mysql_real_escape_string(htmlspecialchars($_POST['issuedto']));
$returndate = mysql_real_escape_string(htmlspecialchars($_POST['returndate']));
//renderForm($reportno, $dateofreceipt, $title, $type, $issuingagency, $markedto, $date,$remarks, $isdate, $issuedto, $returndate, $error);
// save the data to the database
mysql_query("UPDATE `db` SET `Report No.`='[$reportno]',`Date of receipt`='[$dateofreceipt]',`Report Title`='[$title]',`Report Type`='[$type]',`Issuing agency`='[$issuingagency]',`Marked to`='[$markedto]',`Date`='[$date]',`Remarks`='[$remarks]',`Issuing date`='[$isdate]',`Issued to`='[$issuedto]',`Return Date`='[$returndate]' WHERE `Report No.`= '$id'")
// once saved, redirect back to the view page
header("Location: view.php");
}
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM db WHERE `Report No.`= '$id'")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$reportno = $row['Report No.'];
$dateofreceipt = $row['Date of receipt'];
$title= $row['Report Title'];
$type= $row['Report Type'];
$issuingagency= $row['Issuing agency'];
$markedto= $row['Marked to'];
$date= $row['Date'];
$remarks=$row['Remarks'];
$isdate= $row['Issuing date'];
$issuedto= $row['Issued to'];
$returndate= $row['Return Date'];
// show form
renderForm($reportno, $dateofreceipt, $title, $type, $issuingagency, $markedto, $date, $remarks ,$isdate, $issuedto, $returndate, '');
}
?>
Try this query for updation. Also dont forget to add semicolons after statements. Use mysqli_* Functions instead of mysql_*
mysqli_query("UPDATE `db` SET `Date of receipt`='$dateofreceipt',`Report Title`='$title',`Report Type`='$type',`Issuing agency`='$issuingagency',`Marked to`='$markedto',`Date`='$date',`Remarks`='$remarks',`Issuing date`='$isdate',`Issued to`='$issuedto',`Return Date`='$returndate' WHERE Report No = $reportno");
Several issues here:
The mysql api in PhP is deprecated. Don't bet on it working for longer. Use the mysqli api instead.
In your query the "where 1 part is completly superflous. 1 means true and where 1 means all records, at which point you can leave the WHERE out completly. You probably wanted to use WHERE somekey = 1, which is different.
try this
mysql_query("UPDATE db SET Report No.=".'$reportno'.",Date of receipt=."'$dateofreceipt'.",Report Title=."'$title'.",Report Type=."'$type'.",Issuing agency=."'$issuingagency'.",Marked to=."'$markedto'.",Date=."'$date'.",Remarks=."'$remarks'.",Issuing date=."'$isdate'.",Issued to=."'$issuedto'.",Return Date=."'$returndate'." WHERE Report No.= ."'$id'."")

Can't update data in database with Codeigniter

I can't update data in a record in CodeIgniter . Instead of updating it's adding new record in database table.'hotelres_id' is the primary key of my table.
I have posted the code below:-
Controller code for update:-
function edit($id){
$this->load->model('hotel_reservation','mb');
$data['message'] = '';
$data['object'] = $this->mb->find_by_id($id);
if($data['object']){
$this->form_validation->set_rules('roomno', 'Room Number', 'required|is_unique[hotel_reservation.roomno]');
$this->form_validation->set_rules('checkin', 'Check In', 'required|is_unique[hotel_reservation.checkin]');
$this->form_validation->set_rules('checkout', 'Check Out', 'required|is_unique[hotel_reservation.checkout]');
if ($this->form_validation->run() == TRUE){
$this->mb->eventreg_id = $_POST['hotelres_id'];
$this->mb->eventreg_id = $_POST['eventreg_id'];
$this->mb->eventhotel_id = $_POST['eventhotel_id'];
$this->mb->roomno = $_POST['roomno'];
$this->mb->checkin = $_POST['checkin'];
$this->mb->checkout = $_POST['checkout'];
$this->mb->comment = $_POST['comment'];
$this->mb->update();
$data['message'] = 'Details updated successfully';
$data['object'] = $this->mb;
}
$this->load->view('core/hotel_reservation/edit',$data);
}
else{
$data['message'] = 'No details available!! Fill It!!';
$this->load->view('core/hotel_reservation/save',$data);
}
}
View Code :-
<html>
<head>
<title>Hotel Reservation</title>
</head>
<body>
<h2>Hotel Reservation</h2>
<?php if(isset($message)&&$message!='') echo "<span class=\"message\">{$message}</span>"; ?>
<form action="<?php echo site_url('core/hotel_re/edit/'.#$object->hotelres_id); ?>" method="POST" >
<table class="formtable">
<tr><td>hotelres_id</td><td><input type="text" name="hotelres_id" id="hotelres_id" class="textbox" value="<?php echo #$object->hotelres_id; ?>" readonly></td></tr>
<tr><td>eventreg_id</td><td><input type="text" name="eventreg_id" class="textbox" value="<?php echo #$object->eventreg_id; ?>" readonly></td></tr>
<tr><td>eventhotel_id</td><td><input type="text" name="eventhotel_id" class="textbox" value="<?php echo #$object->eventhotel_id; ?>" readonly></td></tr>
<tr><td>Room Number</td><td><input type="text" name="roomno" value="<?php echo #$object->roomno; ?>" class="textbox" ></td></tr>
<tr><td>Check In</td><td><input type="text" name="checkin" value="<?php echo #$object->checkin; ?>" class="textbox"></td></tr>
<tr><td>Check Out</td><td><input type="text" name="checkout" value="<?php echo #$object->checkout; ?>" class="textbox"></td></tr>
<tr><td>Comment</td><td><textarea type="text" name="comment" value="<?php echo #$object->comment; ?>" class="textarea" ></textarea></td></tr>
<tr><td> </td><td><input type="submit" name="submit" value="Update" class="submitbutton"></td></tr>
</table>
</form>
<span class="validation-errors"><?php echo validation_errors(); ?></span>
</body>
</html>
Model code:-
<?php
class hotel_reservation extends CI_Model{
var $hotelres_id;
var $eventreg_id;
var $eventhotel_id;
var $roomno;
var $checkin;
var $checkout;
var $comment;
static $tablename = 'hotel_reservation';
static $tableid = 'hotelres_id';
function find_by_id($id)
{
$tableid = self::$tableid;
$resultset = $this->db->get_where(self::$tablename,array($tableid=>$id),1);
if($resultset->num_rows()==1)
return array_shift($resultset->result(get_class($this)));
return false;
}
function find_all()
{
$resultset = $this->db->get(self::$tablename);
return $resultset->result(get_class($this));
}
function save()
{
$tableid = self::$tableid;
if(isset($this->$tableid)&&$this->$tableid!=''&&$this->$tableid!=0)
$this->update();
else
$this->insert();
}
private function insert()
{
$this->db->insert(self::$tablename,$this);
}
function update()
{
$tableid = self::$tableid;
$this->db->where($tableid,$this->$tableid);
$this->db->update(self::$tablename,$this);
}
function delete()
{
$tableid = self::$tableid;
$this->db->where($tableid,$this->$tableid);
$this->db->delete(self::$tablename);
}
}
The mistake is here!!
In your controller, you have done this...
$this->mb->eventreg_id = $_POST['hotelres_id'];
$this->mb->eventreg_id = $_POST['eventreg_id'];
This should be this
$this->mb->hotelres_id = $_POST['hotelres_id'];
$this->mb->eventreg_id = $_POST['eventreg_id'];
And like i Said, the update term should be written like this...
$this->db->where($tableid,$this->hotelres_id);
Solved?
From what i can see, i think your issue is with this line:
$this->db->update(self::$tablename,$this);
As you should pass the update function an array with matching keys to your TB columns and values to be updated, with you send the whole object ($this), doesn't also send tableid and tablename?
According to your code ($this->mb->update();), it is calling mb model. But you have provided code for hotel_reservation model. May be some mismatch there.

Display data into textbox in codeigniter

I am new to codeigniter. I am stuck somewhere in displaying the value retrieved from database!
How can I display the value extracted from Database into the Textbox using Codeigniter ?
My view is : PutArtistProfile_v
<?php
foreach ($return_Name as $row )
{
echo '<input type="text" name="Name" id="Name" />';
}
?>
My Controller is:
public function index($return_Name)
{
$this->load->view('PutArtistProfile_v', $return_Name );
}
$return_Name -- have data fetched from database.
<?php
foreach($return_Name as $key)
{
$val= $key->text_name;
echo "<input type='text' value='$val' />";
}
?>
In View -
<?php
foreach ($return_Name as $row )
{
echo '<input type="text" name="Name" id="Name" value="$row->columnname" />';
}
?>
You have to send your result to view:
In controller:
public function index($return_Name)
{
$data['return_Name'] = $return_Name;
$this->load->view('PutArtistProfile_v', $data );
}
In view you can get data like $return_Name
You can pass the data to view using controller method
public function index()
{
$data['return_data'] = $this->model_name->function_name();
$this->load->view('view_filename', $data );
}
And in view you can access the value using loop
foreach($return_data as $row)
{
echo '<input type="text" name="name" value="$row['column_name']" /';
}
You can access your data from session variables from controller
$data['id'] = $this->session->userdata('user_id');
And in view you can echo it out in input fields
<input type="text" name="id_admin" value="<?php echo $id; ?>" maxlength="50" class="form-control" />

Call a variable from function and display in text field oop php

i want to show user specific data in html form(in text fields or in select list)
I have a function ShowUserInformation() in class MyClass:
function ShowUserInformation()
{
$query = "SELECT id, name, email FROM saloni WHERE id = '$_SESSION[ID_korisnika]'";
$result = mysql_query($query);
while($row=mysql_fetch_array($result)):
$id= $row['id'];
$name= $row['name'];
$email = $row['email'];
$address= $row['address'];
$address2= $row['address2'];
$address3= $row['address3'];
endwhile;
return $result;
}
My question is: How can i display value of $name, or $email, $id... on another page in text box or in select list?
If i do it in procedural way it works when i do this:
<input type="text" value="<?php echo $name ?>" name="name" class="" />
But, how can i display the $name,$email,$ID... in oop way? Is there a way to call it directly and not declare it as class variable and then call it.
i've included file, created object...
$my_class = new MyClass; //create an object of class
HTML - i've tried something like this...
<input type="text" value="<?php echo $my_class->ShowUserInformation($name)?>" name="name" class="" />
I'm new in PHP and oop so be easy with me :)
Thank you
If you only plan on one row being returned, then why not use mysql_fetch_assoc()
class MyClass{
public function GetUserInformation(){
$query = "SELECT id, name, email FROM saloni WHERE id = '$_SESSION[ID_korisnika]'";
$result = mysql_query($query);
$info = mysql_fetch_assoc($result);
return $info;
}
}
$class = new MyClass;
$info = $class->GetUserInformation();?>
<input type="text" value="<?php echo $info['id']?>" name="id" class="" />
<input type="text" value="<?php echo $info['name']?>" name="name" class="" />
Note: mysql_* functions are deprecated, and you should move to use MySQLi or PDO
First, change the function to get the data:
function ShowUserInformation()
{
// Assuming you need only one user, I have set "LIMIT" to "1"
$query = "SELECT id, name, email, address, address2, address3 FROM saloni WHERE id = '$_SESSION[ID_korisnika]' LIMIT 1";
$result = mysql_query($query);
return mysql_fetch_array($result);
}
Now, get the information:
$my_class = new MyClass;
$userData = $my_class->ShowUserInformation();
// HTML
<input type="text" value="<?php echo $userData['name']; ?>" name="name" class="" />
kindly try this:
<?php
$show_info=ShowUserInformation();
$data = $show_info->fetchAll(PDO::FETCH_ASSOC);
foreach($data as $row){ ?>
<input type="text" value="<?php $row['name']; ?>" name="name" class="" />
<?php } ?>
OR
<?php $show_info=ShowUserInformation();
while ($row= mysql_fetch_assoc($show_info){ ?>
<input type="text" value="<?php $row['name']; ?>" name="name" class="" />
<?php } ?>

Categories