how to separate php code to html using pdo? - php

I have a page called index.php and inside that php i have the function of CRUD and my problem is that how can i separate the php code to html and put it in a class..please help me..
here's the php and html code i want to separate
<label class="Land_Type">
<span>Land Type</span>
<?php
include_once 'dbconfig.php';
$sql = "SELECT Land_Type_Name FROM land_type";
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($stmt->rowCount() > 0)
{
?>
<select name="Land_Type">
<option selected="selected" value="">---</option>
<?php
foreach ($results as $row)
{
?>
<option value="<?php echo $row['Land_Type_Name']; ?>"><?php echo $row['Land_Type_Name']; ?></option>
<?php
}
?>
</select>
<?php
}
?>
</label>
and here is my class
<?php
class crud
{
private $db;
function __construct($DB_con)
{
$this->db = $DB_con;
}
public function login($uname,$upass)
{
try
{
$stmt = $this->db->prepare("SELECT * FROM users WHERE user_name=:uname LIMIT 1");
$stmt->execute(array(':uname'=>$uname));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
if(password_verify($upass, $userRow['user_pass']))
{
$_SESSION['user_session'] = $userRow['user_id'];
return true;
}
else
{
return false;
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function is_loggedin()
{
if(isset($_SESSION['user_session']))
{
return true;
}
}

Use a design pattern/architecture like MVC (Model-View-Controller) There's a lot of information to be found about this on the internet and on SO. Have a look at this question and this one for a good start.
Regarding seperating PHP from HTML: the easiest way is to use an existing template engine. Smarty is a very popular one and easy to use.
The important thing is to seperate your business logic. A class should have only one responsibility, which is called the single responsibility principle. In your example, your database class is doing 2 things: it contains the database logic (executing queries) and handling your login system. You should attempt to seperate these.
These things can be pretty confusing in the beginning. My advice is to use a MVC framework (many exist for PHP like codeigniter, cakephp,...) to understand the concepts.

Related

Data not displaying in View from controller codelgniter

I am learning CodeIgniter; in my program I am trying to populate a dropdown from mysql database but I seemed to be doing something wrong.
Please find below what I tried:
Model
In my model I tried to use different select methods I found online but all failed so I stick with the below method and still failed.
function getAllVendors()
{
$this->db->select('DISTINCT SUBSTRING(product_code,1,3) as vendor')
->order_by('vendor');
$q = $this->db->get('tec_sale_items');
if ($q->num_rows() > 0) {
foreach (($q->result()) as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
Controller
public function allVendors(){
$this->data['vendors'] = $this->vendors_sales_model->getAllVendors();
$this->page_construct('reports/vendors_sales_details', $this->data);
}
View
<select class="form-control">
<option value="">All</option>
<?php
foreach($vendors as $ven)
{
echo '<option value="'.$ven['vendor'].'">'.$ven['vendor'].'</option>';
}
?>
</select>
Could someone please point me to what I am doing wrong.
As I see you might be forget to call view into your controller. Load view in the controller $this->load->view("your view file name") and pass the data you got from your database.
First make sure that you are getting proper data from model. And as I see your are using current object of class $this->data['vendors'] so you have to use same in the code
<select class="form-control">
<option value="">All</option> <?php
foreach($this->data['vendors'] as $ven)
{
echo '<option value="'.$ven['vendor'].'">'.$ven['vendor'].'</option>';
}
?>
</select>
May be it's helpful 🙂.
And you should use ci4 it's 3rd version of ci and it's no longer maintained. For better security and performance change php server 7.4 and above.

Passing data from Controller to View with CodeIgniter

I'm having difficulty with display data from the db to dropdown.
This is what I have tried:
form_model.php
function getEmployee()
{
$this->db->select('username');
$query = $this->db->get('tbl_usrs');
return $query->result();
}
form_controller.php
public function evaluate()
{
$data['employee'] = $this->form_model->getEmployee();
$this->load->view('evaluate_view');
}
evaluate_view.php
<select class="form-control">
<?php
foreach($employee as $row)
{
echo '<option value="'.$row->username.'">'.$row->username.'</option>';
}
?>
</select>
It's giving me an error saying I have an unidentified variable employee in my view file. I've seen problems relating to this but so far all their solutions didn't work for me.
When you load the view you have to send the data like this:
$this->load->view('evaluate_view', $data);

HTML code in OOP PHP file

I want to get some advice of using PHP OOP.
For example I'm createing some PHP/MySQL code using OOP and I need to output the code, how to do it?
I might have been bit confusing, I will show you all the code and you tell me if I do it right:
index.php
<?php
require_once CLASSES."Pages.Class.php";
$obj = new Pages;
if (isset($_GET['page'])) {
$obj->setPage($_GET['page']);
echo $obj->getPage();
} else {
echo $obj->getFrontPage();
}
?>
Pages.Class.php - one function from it
public function getDatabasePage() {
global $conn;
$sql = "SELECT * FROM pages WHERE page_seo_title = '$this->pageId' LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
?>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="well">
<div class="page-head">
<?php echo $row["page_title"]; ?>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="well">
<div class="page-content">
<?php echo $row["page_content"]; ?>
</div>
</div>
</div>
<?php
}
} else {
echo "0 results";
}
}
So basiclly the question is: Where do I need to put HTML code?
In the index.php file or in the pages.class.php file?
How to do this right? Maybe I can get some links with documentation about this from you :) ..
Thanks.
btw - code is an example, not fully done. Just as example - I know it's not right as it is :D
In your Pages class, create a separate method that outputs HTML and does only that; the DB-related logic should be in another method or (preferably) in a totally separate class.
class Pages {
public function __construct(){
//Object initialization logic comes here
}
public function getOutputHTML($resultOfQuery = ''){
return "<div> Your html </div>";
}
}
Other class file only for DB access , just pass parameter and get result as Database result.
class DB {
public function insertMethod($table,$fields,$where){
//Your logic
}
public function updateMethod($table,$fields,$where){
//Your logic
}
public function deleteMethod($table,$fields,$where){
//Your logic
}
public function selectMethod($table,$fields,$where){
//Your logic
}
}
Instantiate DB class like $dbObj = new DB();
Then you can access DB methods like $resultQuery = $dbObj.selectMethod('users');
So you can pass the $resultQuery result to other method like : $objPages = new Pages();$objPages.getoutputHTML($resultOfQuery); . It separates the Database and HTML logic/functionality.
I recommand you to use OOP with MVC so there will be templating system like Smarty,Blade etc.

CodeIgniter Dropdown menu

I have a view (myView) in which there is a form. The form action is myController/myFunction1 which is used to validate the input variables in the form and insert it to the database by calling a model function. This works perfectly fine.
Now, I need a dropdown box inside the form, for which the values will be fetched from a table (called business) in the db.
This is the code I wrote in my model to fetch the values
public function get_dropdown_list() {
$this -> db -> select('business_name');
$result = $this -> db -> get('business');
if ($result -> num_rows() > 0) {
foreach ($result->result_array() as $row) {
$new_row['value'] = htmlentities(stripslashes($row['business_name']));
$row_set[] = $new_row;
}
}
return $row_set;
}
I'm not entirely sure if this is correct.
What I need to know is, if this is correct, what should be the code inside the controller and the view to display the result as a dropdown in the form in the myView.
And if this model itself is wrong, how do I get it working?
P.S. : I'm new to CodeIgniter. I have been going through S.O and various other sites to get this thing working for quite a bit of time now. This might seem to be a repeated question for which I'm really sorry, because I could not find a solution from the already available discussions dealing with the same issue. Any help is very much appreciated.
try Model :-
public function get_dropdown_list() {
$this -> db -> select('business_name');
$result = $this -> db -> get('business');
if ($result -> num_rows() > 0) {
return $result->result_array();
}
else {
return false;
}
}
Controller :-
1. include model in your controller
2. call the function and send data to view.
$this->load->model('model_name');
$this->data['dropdown'] = $this->model_name->get_dropdown_list();
$this->load->view('yourview', $this->data);
get value in view:-
print_r($dropdown)
Loop your data and make a dropdown
<select name="dropdown">
<?php foreach($dropdown as $d) {?>
<option value="<?php echo $d;?>"><?php echo $d;?></option>
<?php }?>
</select>
Call This function in controller for getting your records from DB
$data['records'] = $this->my_model->get_data();
In my_model.php
function get_data()
{
$query = "select * from my_tab";
$res = $this->db->query($query);
if ( $res->num_rows )
{
return $res->row_array();
}
return false;
}
In view.php
<select>
<?for($i=0;$i<count($records);$i++)
{
?>
<option>$records[$i]->name</option>
<?php } ?>
</select>

Right mvc concept, little php code in view

I have one not understood point In MVC pattern. Please help understood.
for example we have table for cars in database, we want obtain and print results from table, but if results are not found (0 rows), in this case print: "We dont have results"
this is models.php
class modesl {
function getCars () {
$res = $this->db->query("SELECT names FROM cars");
if ($res->num_rows == 0) {
return "We dont have results";
}
else {
return $res;
}
}
}
this is views.php
class views {
function loadHTML ($resultFromCars) {
require 'carspage.php';
}
}
this is carspage.php
<html>
<body>
<?php
if (is_object($resultFromCars)) {
while ($row = $resultFromCars->fetch_assoc()) {
echo $row['names']."<br>";
}
}
else {
echo $resultFromCars;
}
?>
</body>
</html>
this is controllers.php
class controllers {
function generatePage () {
$model = new models();
$resultFromCars = $model->getCars();
$view = new views();
$view->loadHTML($resultFromCars);
}
}
This works, but as I know, many php code in view, (that is condition if (is_object) { } else { } ) is not right MVC. tell please for this concret case, what must be change in my architecture (lol), for obtain right MVC concept?
I like the answer provided by Havelock.
I would adjust this even further, by making sure your model already returns the data in an array format (or false, if nothing is found). Therefore, the logic for extracting data from resultset stays in the model, where it really should be.
Your view becomes even simpler then:
<?php
if (!empty($results)) {
foreach ($results as $row) {
echo $row['name'] . "<br />";
}
} else {
echo "Eh, Nothing found...";
}
You seem to have done a good job, just one small thing to improve. As the model is a wrapper for data only, so you should return only data (and no strings, containing error/exception messages). In the case there's no data to return, then return FALSE, as it's done in PHP.
class CarModel {
function getCars () {
$res = $this->db->query("SELECT names FROM cars");
if ($res->num_rows == 0) {
return FALSE; // if that happens, the function will stop execution here, so no "else" is needed
}
return $res;
}
}
And in your view
<?php
if ($resultFromCars === FALSE && !empty($resultFromCars)) {
echo "We don't have results";
}
else { // now you know it's not FALSE, so it must be an object, no need to check whether it is one
while ($row = $resultFromCars->fetch_assoc()) {
echo $row['names']."<br>";
}
}
?>

Categories