User:Taoist

Jsfsa banner.png

From WikiAudio

Jump to: navigation, search

Contents

Cake PHP

Getting information from the database

How to inject MYSQL table information (posts) into HTML

  1. You need a controller class to store the information in a variable. You do this using the set() method. This is defined in the controller class file inside an 'action' and then relayed to the view file which adopts the variable as its own as long as you follow the same naming convention
 
// PostController.php
class PostController extends AppController{

	 public function index() {
        $this->set('posts', $this->Post->find('all'));          //sets the post variable to all of the information in the POST table via the model. The entire array 'blob' from the Post table is stored in this as array data.
    }
}

2. You can then adopt the variable and use it. You do this by looping through it.

 

//Posts/index.php

<?php foreach ($posts as $post): ?>   // loop through it

<?php echo $post['Post']['id'];?>      // output whatever you want to the page.

<?php echo $this->Html->link($post['Post']['title'],                             // grab data and add links to it and output to page
 array('controller' => 'post', 'action'=> 'view',$post['Post']['id']));?>

<?php endforeach?>

$Id

This parameter is handed to the action through the requested URL. If a user requests /posts/view/3, then the value ‘3’ is passed as $id.


Trees

With trees the parent_id can be used to find, well, the parent.

 echo $post['Post']['parent_id']