How i get variable value saved in database? - php

i had save data in mysql data base and i had create template html tags in one column. now i want to display template data in php, but its not working.
MYSQL DATABASE IMAGE CLICK HEAR TO SHOW DATABASE
Controller
class Project extends CI_Controller{
function template(){
$query = $this-db->query("select * from templete where id='11' ");
$result = $query->result_array();
$data['result'] = $result[0];
$this->load->view('template_view',$data);
}
}
View
<html>
<head></head>
<body>
<?php
extract($result);
echo $template_data;
?>
</body>
</html>
Output :
{$ticker}
{$address1}
{$address2}
{$city}
{$phone}
{$website}
I want output
HSPG.OL
Sparebankgården
Bjørkelangen
http://www.hsbank.no
template data dyanamic
its gone be
<p>{$ticker}</p><p>{$address1}</p><p>{$address2}</p><p>{$city}</p><p>{$phone}</p><p>{$website}</p>
or
<p>{$ticker}</p><p>{$address1}</p><p>{$address2}</p><p>{$city}</p>
any one help, i am post this question 2nd time with full coding.

Although Codeigniter as a framework doesn't stop you or restrict you to stay in MVC boundaries but it is really appreciated and a good practice that one should do so.
BEST PRACTICE
Create a model and put your query in a function in that model. Call
that function in your controller, get your data in an array/object and
then send it to the view that's how MVC is supposed to be.
In your case, you are using php extract() function to get data out of the $result array which it has done perfectly but what you are printing is not the correct index.
Read this for php extract info
so instead of printing $template_data use the following ;
<html>
<head></head>
<body>
<?php
extract($result);
echo $ticker.'<br>';
echo $address1.'<br>';
echo $city.'<br>'; // and so on
?>
</body>
</html>

Lot of things wrong with this code. You shouldn't be getting template data from the database, that should be in the view. You should probably delete the template_data column from your table.
class Project extends CI_Controller{
function template(){
$query = $this-db->query("select * from templete where id='11' ");
$data['result'] = $query->result_array();
$this->load->view('template_view',$data);
}
}
View:
<html>
<head></head>
<body>
<?php echo $result['ticker']; ?>
<?php echo $result['address1'] . ' ' . $result['address2']; ?>
<?php echo $result['city']; ?>
<?php echo $result['phone']; ?>
<?php echo $result['website']; ?>
?>
</body>
</html>

Related

How can I run PHP code in an specific html section

I have a section in my .html page where I want to run some PHP code, which reads data from a database and 'echoes' the table filled up with that information. I kinda did it object-oriented so I'm trying to keep that along the project.
I have this exact function or method in the Class (Class Servicio):
public static function listaServicios(){
$servicios = array();
$query = "";
$db = Database::getInstance();
$query = "SELECT descripcion, precio FROM servicio";
$resultado = $db->conn()->query($query);
foreach($resultado as $item){
$servicio = new Servicio();
$servicio->setDescripcion($item['descripcion']);
$servicio->setPrecio($item['precio']);
array_push($servicios,$servicio);
}
return $servicios;
}
As you can see, the function just returns an array filled up with as many objects as rows there is in the table. The PHP page would call this method, and then print the table with the selected data inside (there is no problem with this).
The thing is how can I print it in the specific section (div with id='datos') previously mentioned, which simply is:
<section class="principal">
<div id="datos">
</div>
</section>
I kinda of have an idea but I really don't know to implement it. Maybe using a document.ready function in jQuery calling the PHP code? I would really like to use this language even if it is a very tiny function in order to learn.
You can use jquery's load function to load content via a remote file into the div. But you will need to update your listaServicios to return html instead of the array.
jquery:
$(document).ready(function(){
$('#datos').load('phpfile.php');
});
phpfile.php
<?php
$serv = new Servicio();
echo $serv->listaServicios();
?>
Correct answer to your question depends on the interface of your future application you want to reach.
If you want some kind of SPA, then you should make AJAX-requests using JavaScript (jQuery or something else) and create a separate controller to response with data.
But I think in your particular case you can do everything on server side.
First of all you should add new method to your class, name f.e. render:
public static function render(){
$services = static::listaServicios();
include 'path/to/your/template.php';
}
Then inside your template.php write next:
<section class="principal">
<div id="datos">
<?php
foreach($services as $service) {
// echo your $service here as you wish
}
?>
</div>
</section>
So after calling render() PHP will render that part of template.
To access the properties of Servicio is better you construct your table in php:
<?php $servicios = Servicio::listaServicios(); ?>
<section class="principal">
<div id="datos">
<table style="width:100%">
<tr>
<th>Descripcion</th>
<th>Precio</th>
</tr>
<?php foreach ($servicios as $servicio): ?>
<tr>
<td><?= $servicio->getDescripcion() ?></td>
<td><?= $servicio->getPrecio() ?></td>
</tr>
<?php endforeach; ?>
</table>
</div>
</section>

Is it correct to print long HTML via PHP?

I would like to know if it is correct to print long html through php classes with echo instead of just print it in a normal way, for example do the following:
Supose i have an user class
User.php
class User {
private $name, $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function printProfile($name, $age) {
echo '<div class="panel panel-profile">
Name: '.$this->name.'<br />
Age: '.$this->age.'<br />
</div>';
}
}
And my profile.php would look something like
profile.php
<html lang="en">
<head>
<?php
require_once __DIR__ . "/Head.php
$head = new Head();
$head->printPanel();
?>
</head>
<body>
<?php
require_once __DIR__ . "/Header.php
$header = new Header();
$header->printPanel();
?>
<div class="content">
<?php
require_once __DIR__ . "/User.php
$user = new User();
$user->printProfile();
?>
</div>
<?php
require_once __DIR__ . "/Footer.php
$footer = new Footer();
$footer->printPanel();
?>
</body>
</html>
So.. I know it's possible but i don't know if is it correct to do that, am i making a proper use of the code? will influence the processing speed?
I like this way because i can reduce the code in all the pages, and just by changing the class it modify all the code. I also know that i could make something like
<?php require_once __DIR__ . "/header.php ?>
And include all the code there without making a class
header.php
<header>
some stuffs
</header>
But i don't really like this because it is not object-oriented.
Sorry about my english as you may have noticed i'm not really good at it.
Turns out, object orientation isn't everything. If you can do just as much procedurally, do it. In your case, for a simple website, you can get away with storing all of your chunks in a separate file, say, Chunks.php. Use one function for each of the pieces you want to add. You don't need 20 different classes with constructors for each element on the page. Just use static methods.
As for code style, put all your requires at the top so your page doesn't crash half way through rendering:
<?php require_once __DIR__ . "/Chunks.php ?>
<html lang="en">
<head>
<?php Chunks::printHead(); ?>
</head>
<body>
<?php Chunks::printHeader(); ?>
<div class="content">
<?php Chunks::printUserProfile(); ?>
</div>
<?php Chunks::printFooter(); ?>
</body>
</html>
Simple, easy to read, and does exactly what you expect without 30 different 20-line files clogging up your view.
Using echo to output the html to the screen is more typical today.
PHP echo and print Statements echo and print are more or less the
same. They are both used to output data to the screen.
The differences are small: echo has no return value while print has a
return value of 1 so it can be used in expressions. echo can take
multiple parameters (although such usage is rare) while print can take
one argument. echo is marginally faster than print.
You can read more about that here
You should add the require imports to the top of the page. which is what most people do.
Thanks! Your answers have been very useful, i'll begin using more statics methods.
I've been doing some simples websites, with javascript, jquery, html and php but i'm about to start a larger project and i wanted to clarify some stuffs.
You said In your case, for a simple website, ... but what about a larger website? the same applies?

What method should I use for later set a variable and then echo the page title

I'm trying to avoid to query my database twice: for set <title> attribute and also for echo the page title. I want to query it just one time:
Example:
<html>
<head>
<?php
// how should I use here ob_start() ? Is there any other possible way to achieve this?
$title = "";
echo '<title>', $title, '</title>'; // this should be in the end <title>value of $row['page_title']</title>
?>
</head>
<body>
<?php
$sql = $mysqli->query("MY QUERY");
$row = $sql->fetch_assoc();
$title = $row['page_title']; // I want that this assignment to set the variable in the top
// I know that for this job I can use ob_start() but I didn't used it until now
// and I will really appreciate any help from you.
?>
<h1><?php echo $title; ?></h1>
</body>
</html>
I know that I can do the query before echo the title attribute but I don't want to do it like that. Do you have any suggestion? or can you show me how to use that ob_start() / ob_clean() functions?
Thank you!
Shift the query to the top of the code and reuse the variables!
<?php
$sql = $mysqli->query("MY QUERY");
$row = $sql->fetch_assoc();
$title = $row['page_title'];
?>
<html>
<head>
<?php echo '<title>', $title, '</title>'; ?>
</head>
<body>
<h1><?php echo $title; ?></h1>
</body>
</html>
ob_start();, in usual sense, won't help you have. However, you can use ugly solution like this:
ob_start();
echo '
<html>
<head>
<title>{title}</title>
</head>
<body>
';
$header = ob_get_clean();
// and then, when you know your title
echo str_replace('{title}', $known_title, $header);
But I strongly recommend taking another approach. You need to choose and fill the template after all data has been gathered and you know all details about which template you want. If you start echoing different parts preemptively, you will get more and more troubles. Now you need to change title for some pages. Then you will need to add css file for specific page and you will have to do that ugly business again. Why not do it the right way?

Dynamic titles best way?

header.php
<?php
$conn = mysql_connect('localhost', '-', '-');
#mysql_select_db('accmaker', $conn) or die("Unable to select database");
?>
<html>
<head>
<title>Mysite.com - <?php isset($pageTitle) ? $pageTitle : 'Home'; ?></title>
</head>
<body>
profile.php
require 'header.php';
$q = mysql_query("SELECT * FROM users WHERE username = '$username'");
$r = mysql_fetch_assoc($q);
$pageTitle = "Profile of $r[username]";
I think you understand what i want
I cant include header.php after the query, because i wont be connected to mysql
waht do you suggest other than having the connection snippet on every page
What do I suggest? A MVC (Model-View-Controller) Framework like Kohana. If you don't want to go that route, break your connection off into its own file:
<?php
# connect
require_once("connection.php");
# load page data array
require_once("page-data.php");
?>
...
<title><?php print $page["title"]; ?></title>
Note here how I have a $page array of data. This will be helpful when debugging later rather than having several independent variables. With an array of page data, I can quickly see all of the information laid out for any given page:
print "<pre>";
print_r($page);
print "</pre>";
Determining your title should be done within page-data.php, rather than on your page:
$config["site_name"] = "Bob's Shoe Mart";
$config["admin_email"] = "bob#shoemart.com";
/* query to get $row['title'] */
$page["title"] = (!empty($row["title"])) ? $row["title"] : $config["site_name"] ;
Not sure of a "best" solution, but we currently include multiple files. We have our "utilities.php" file that connects to the database and provides some nice functions. We then set our page titles and then we include "top.php" which is the layout portion. It doesn't have anything except HTML with a little bit of PHP for display purposes. Looks like this:
include "utilities.php";
$pageTitle = "Welcome";
include "top.php";

MVC for footer-header-sidebar at codeigniter

I use codeigniter. I have footer_view.php, header_view.php and other view php files for pages like aboutus, contactus, etc... for example for about us page, I create model for db actions, than I create a controller to get db variables and send variable to about us view as:
$this->load->view('aboutus/',$data);
Everything is fine until this point, but when I need to get data from db at footer, how will I use in the CodeIgniter Way?
If I create a footer_model, I cannot make view('footer/') because it is actually a part if page, not a page itself :/
You can use $this->load->vars($data);
This will make all data available to all views, footer_view.php, header_view.php and any other views.
$data['your_info'] = $this->user_model->get_info();
$data['your_latest_info'] = $this->user_model->get_latest_info();
$data['your_settings_info'] = $this->user_model->get_settings_info();
$this->load->vars($data);
$this->load->view('your_view');
You view can and will access the data like so:
Your "primary" view
<?php
// your_view.php
// this can access data
$this->load->view('header_view');
<?php foreach ($your_info as $r):?>
<?php echo $r->first_name;?>
<?php echo $r->last_name;?>
<?php endforeach;?>
$this->load->view('footer_view');
?>
Your header_view
<?php
// header_view.php
<?php echo $your_latest_info->site_name;?>
?>
Your footer_view
<?php
// footer_view.php
<?php foreach ($your_setting_info as $setting):?>
<?php echo $setting->pages;?>
<?php endforeach;?>
?>
No need for any template library...
I wrote a blog post about this http://joshhighland.com/blog/2008/11/09/how-i-do-layouts-and-views-in-codeigniter/
basically, you want to load all the data that all your views are going to need in the controller. I use an array of data elements, then pass that to the layout view. My blog post explains more about this, and shows more detail. Here is a sample of my controller.
$this->load->model('search');
$lastest_albums = $this->search->last_n_albumsAdded(10);
$popular_songs = $this->search->popular_n_songs(10);
$featuredAlbums = $this->search->getFeaturedAlbums();
$body_data['featured'] = $featuredAlbums;
$body_data['newest'] = $lastest_albums;
$body_data['popular'] = $popular_songs;
$layout_data['content_body'] = $this->load->view(’home/homePage’, $body_data, true);
$this->load->view('layouts/main', $layout_data);

Categories