i'm in mid of creating my own cms . And now i want to show which one of the category has parent but i don't know how, so please help me.
my category table
idkategori | namakategori | parentid
1 Programming 0
2 PHP 1
Or i need relationship table for my categories?
My Controller so far.
function tampilmenu()
{
$sql = "select * from fc_kategori";
$data['kategori'] = $this->bymodel->tampildata($sql);
$sql1 = "select parentid from fc_kategori";
$data['parent'] = $this->bymodel->tampildata($sql1);
$id=array();
foreach ($data['parent'] as $paren)
{
$id[]=$paren->parentid;
}
foreach ($data['kategori'] as $cat)
if(in_array($cat->parentid,$id))
{
$have ='Yes';
}
else
{
$have ='No';
}
echo $cat->idkategori.$have;
}
}
my model
function tampildata ($sql)
{
$query = $this->db->query($sql);
return $query->result();
}
Please don't laugh on me.
Kindly follow:
1) Since you are using a MVC framework, never write queries inside the controller (queries should always be written in models).
2) Never use raw queries, since CI provides you what is called as Active Record.
3) Also never pass direct queries anywhere you'll possibly code in whichever language. Always pass data and make do that function to compute and query process.
4) Remember, in CI Models are only used for database functionalities, Views are only used for your HTML markups and Controllers acts as the mediator between models and views.
Your code:
Controller -
public function tampilmenu()
{
$categories = $this->bymodel->get_category_having_parent();
echo "<pre>"; print_r($categories);
// this will return object having all categories that are parents
}
Model -
public function get_category_having_parent()
{
$parent_ids = array();
$ps = $this->get("parentid");
foreach($ps as $p)
{
$parent_ids[] = $p->parentid;
}
$this->db->where_in("id", $parent_ids);
$query = $this->db->get("fc_kategori");
return $query->result();
}
public function get($column="*")
{
$this->db->select($column);
$query = $this->db->get("fc_kategori");
return $query->result();
}
Related
I am working on a MLM System, i want to get all childs & subchilds of any parent user. i tried use of recursion but failed. please help me to solve this.
public function searchAllDownline(Request $req){
$ids = array();
$req->validate(['search_keyword'=>'required']);
$search_keyword = $req->search_keyword;
$position = $req->position;
$user = User::where('username',$search_keyword)->first();
if(empty($user)){
return back()->with('error','Invalid username');
}
$query = User::where('parent_id',$user->id)->where('position',$position)->get();
foreach($query as $data){
$ids[] = $data->id;
}
$depth = User::where('name','!=','')->max('depth') - $user->depth - 2;
$this->recursion($ids,$position,$depth);
return view('admin.all-downline',compact('search_result','search_keyword','position'));
}
public function recursion($ids,$position,$depth){
$subquery = User::whereIn('parent_id',$ids)->where('position',$position)->get();
foreach($subquery as $subdata){
array_push($ids,$subdata->id);
}
while($depth-- != 0){
$this->recursion($ids,$position,$depth);
}
print_r(array_unique($ids));
}
Table structure:
There is a quite useful answer you can try below (can’t comment without enough rep…):
https://stackoverflow.com/a/26654139/19766732
It’s old but gold ;)
I need to call a function from view to echo a value. I use following code,
Controller (test_controller)
public function displayCategory()
{
$this->load->model('Model_test');
$data['categories'] = $this->Model_test->getCategories();
$this->load->view('test_view', $data);
}
public function display($id)
{
$this->load->model('Model_test');
$name= $this->Model_test->getName($id);
return $name;
}
Model (Model_test)
function getCategories() {
$query = $this->db->query("SELECT * FROM category");
if ($query->num_rows() > 0) {
return $query->result();
} else {
return NULL;
}
}
function getName($userId) {
$query = $this->db->query("SELECT name FROM user where id = '$userId' ");
if ($query->num_rows() > 0) {
return $query->row()->name;
} else {
return NULL;
}
}
View
<div id="body">
<?php
foreach ($categories as $object) {
$temp = $this->test_controller->display($object->id);
echo $object->title . " ". $object->no . $temp . '<br/>';
}
?>
</div>
but some error when running the code.
error Message: Undefined property: CI_Loader::$test_controller in view
I am not sure if you use CodeIgniter 2 or 3.
Anyway, basically you don't want to use anything inside View files except perhaps helper function(s) or some kind of "presenter" layer (that should be called inside controller I guess).
Solution using Join
Go and read this manual page and search for join. There you can learn about implementation of SQL join directive.
You want to modify this (getCategories()) function so it returns data that you require
function getCategories() {
$this->db->select('category.title, category.no, user.name as username')
->from('category')
->join('user', 'user.id = category.id');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result();
} else {
return NULL;
}
}
and in view you can get your username like this
foreach ($categories as $object) {
echo $object->title . " ". $object->no . $object->username . '<br/>';
}
I am not 100% sure so please post comments I will edit this answer later.
Solution "breaking rules"
https://stackoverflow.com/a/24320884/1564365
general notes
Also consider naming your tables using plural so categories, users...
Also it is a bad practise to use "category.id as user.id" (storing user id inside category table in "id" field) instead you shold use either a pivot table or in case of 1:1 relation field "user_id".
I am creating a web-service backend for a mobile app I am developing. (I am an experience Obj-C developer, not a web-designer!) Essentially I would like to use Codeigniter and Phil Sturgeon's RESTful API Server https://github.com/philsturgeon/codeigniter-restserver however, I'm having some trouble getting it all setup and working.
I have MySQL database that is setup with data in it. And I need some help writing a CodeIgniter PHP model and controller that returns JSON data of what is inside that database. All of the tutorials and forum post's i have found deal with hardcoded data in the controler, not a MySQL database. I would ideally like to have the URL formatted like this http://api.mysite.com/v1/search?id=1&name=foo&city=bar , I could potentially have 50+ parameters to pass in the url.
Using Phil's code, I have come up with this as my controller:
public function index_get()
{
if (!$this->get('id'))
{
$this->response(NULL, 400);
}
$data = $this->grid_m->get_id($this->get('id'));
if ($data)
{
$this->response($data, 200);
}
else
{
$this->response(NULL, 404);
}
}
That only gets me one search term: id?=# .. I need to know how to get multiple search terms
Here is my Codeigniter model:
<?php
class Grid_m extends CI_Model
{
function get_all()
{
$query = $this->db->get('grid');
if ($query->num_rows() > 0)
{
return $query->result();
}
return FALSE;;
}
This just returns EVERYTHING in my MySQL database regardless of what id or url term I pass it in the URL.
I'm a big noob when it comes to developing my own custom API so any suggestions on how to fix my controller and database model would be a huge help!
Thanks for the help!
-brian
This is old question but if somebody go here and still need help, try these code:
In your controller:
public function index_get()
{
$where = '';
if ($this->get('id')) // search by id when id passed by
{
$where .= 'id = '.$this->get('id');
}
if ($this->get('name')) // add search by name when name passed by
{
$where .= (empty($where)? '' : ' or ')."name like '%".$this->get('name')."%'";
}
if ($this->get('city')) // add search by city when city passed by
{
$where .= (empty($where)? '' : ' or ')."city like '%".$this->get('city')."%'";
}
// you can add as many as search terms
if ( ! empty($where))
{
$data = $this->grid_m->get_searched($where);
if ($data)
{
$this->response($data, 200);
}
else
{
$this->response(NULL, 404);
}
}
else
{
$this->response(NULL, 404);
}
}
In your model, create get_searched function:
class Grid_m extends CI_Model
{
function get_searched($where = NULL)
{
if ( ! is_null($where))
{
$this->db->where($where);
$query = $this->db->get('grid');
if ($query->num_rows() > 0)
{
return $query->result();
}
}
return FALSE;
}
}
User Codeigniter's Active record to build proper query, you can build any type of query using methods of active record, refer following example I have just added one condition in it you can add more conditions as per your need.
<?php
class Grid_m extends CI_Model
{
function get_all()
{
$this->db->select('col1, col2, col3')->where('id', 5);
$query = $this->db->get('grid');
if ($query->num_rows() > 0)
{
return $query->result();
}
return FALSE;;
}
}
Please check you query
$query = $this->db->get_where('grid', array('id' => $id));
i am looking for a function to fetch wordpress category hierarchy from wordpress tables (wp_terms, wp_term_relationships, wp_term_taxonomy) WITHOUT using wordPress functions / templates.
i am basically looking to fetch categories (parent/child) relationship and then I want to insert them into my own CMS table. For this i must know "What Category Comes under What? (with all the sub-sub (multiple) directories)"
So far I made this:
$sql="SELECT a.term_id,a.description,a.parent,a.count,b.name,b.slug
FROM wp_term_taxonomy a INNER JOIN wp_terms b WHERE a.term_id=b.term_id
AND a.taxonomy='category';
";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
echo($row['name'].'<br>');
}
exit;
This function displays all the categories but NOT the hierarchy and i am NOT able to get the Child Parent thing..
Can anyone help me with this please?
Regards
It's not that hard. First I'd wrap that recursive stuff by letting it behave like a RecursiveIterator:
class RecursiveCategoryIterator implements RecursiveIterator {
const ID_FIELD = 'term_id';
const PARENT_FIELD = 'parent';
private $_data;
private $_root;
private $_position = 0;
public function __construct(array $data, $root_id = 0) {
$this->_data = $data;
$this->_root = $root_id;
}
public function valid() {
return isset($this->_data[$this->_root][$this->_position]);
}
public function hasChildren() {
$subid = $this->_data[$this->_root][$this->_position][self::ID_FIELD];
return isset($this->_data[$subid])
&& is_array($this->_data[$subid]);
}
public function next() {
$this->_position++;
}
public function current() {
return $this->_data[$this->_root][$this->_position];
}
public function getChildren() {
return new self($this->_data,
$this->_data[$this->_root][$this->_position][self::ID_FIELD]);
}
public function rewind() {
$this->_position = 0;
}
public function key() {
return $this->_position;
}
public static function createFromResult($result) {
$menu_array = array();
while($row = mysql_fetch_assoc($result)) {
$menu_array[$row[self::PARENT_FIELD]][] = $row;
}
return new self($menu_array);
}
}
Now why would I do that? First, because you can re-use id for displaying the tree, or do other stuff with it like import it in your own table. Second, if you have to test your code, you can just put in some other RecursiveIterator as a mock (for example a RecursiveArrayIterator).
Now the second part, the actual import of the word-press data:
// your original query
$sql="SELECT a.term_id,a.description,a.parent,a.count,b.name,b.slug
FROM wp_term_taxonomy a INNER JOIN wp_terms b WHERE a.term_id=b.term_id
AND a.taxonomy='category';
";
$result = mysql_query($sql, $dbh);
// always test for failure
if($result === false) {
die("query failed: ". mysql_error());
}
// create the iterator from the result set
$wpterms = RecursiveCategoryIterator::createFromResult($result);
// and import it.
insert_it($wpterms, 0);
// the function which does all the dirty work.
function insert_it($iterator, $parent_id = 0) {
foreach($iterator as $row) {
// insert the row, just edit the query, and don't forget
// to escape the values. if you have an insert function,
// use it by all means
$qry = 'INSERT INTO my_table (myparent, myname, ...)'
. ' VALUES (\'' . mysql_real_escape_string($parent_id)
. '\', \'' . mysql_real_escape_string($row['name']) . '\', ....)';
$status = mysql_query($qry);
if($status === false) {
// insert failed - rollback and abort
die("hard: " . mysql_error());
}
// you need to pass the id of the new row
// so the "child rows" have their respective parent
$cid = mysql_insert_id();
// insert the children too
if($iterator->hasChildren()) {
insert_it($iterator->getChildren(), $cid);
}
}
}
If you want to migrate your data to a different (and even custom-built) CMS, you should use Export, which will generate a WXR (XML) file that is very easy to parse and import into third-party systems. It includes all post types, taxonomies, meta data, attachments and everything else.
Working directly with the database is a pain, but if you will, it'll be easier to work on the WordPress side write the data into your other tables, rather than trying to read the data from somewhere else.
The best example i can think of is a hall of fame page for sports.
You can then have a navigation that can limit the results depending on the user's requests, Past 3 Months and boxing for example.
What would be the best way to display multiple kind of result layouts, for example,
The swimming results have a different layout to football, football differs to boxing and then add a time limiter by timestamp.
These are the options i have thought of so far and would like your opinion on.
Simple PHP
if($_GET['sport'] = "boxing"){
if(isset($_GET['timescale'])){
$start = 1334752108;
$end = 1334759108;
$query = "SELECT athlete_name, athlete_age, athlete_desc FROM `athletes` WHERE `timestamp` BETWEEN '".$start."' AND '".$end."' AND `sport` = 'boxing' LIMIT 30";
} else {
$query = "SELECT athlete_name, athlete_age, athlete_desc FROM `athletes` WHERE `sport` = 'boxing' LIMIT 30";
}
while($row = mysql_fetch_array(mysql_query($query))){
echo "<div class='boxing'>";
//show results
echo "</div>";
}
}
if($_GET['sport'] = "swimming"){
//repeated
}
if($_GET['sport'] = "football"){
//repeated
}
Ajax
Have either one page that will handle all the requests (ajax_request_hof.php) that contains similar code to the PHP above.
EDIT
skafandri suggested a Data Mapping Class, would anyone else advise this or is able to show me an example?
Any ideas on how i can improve this are greatly welcomed and needed.
You mentioned in SO chat that you didn't have any experience with frameworks so here's a suggestion without one.
I know I'm probably going to be flamed for this, but knowing that it's an organizational structure issue you can steal some concepts of MVC and use them until you can port it to a more proper structure to at least make it a little cleaner and a lot easier to manage.
Disclaimer: In no way is this a good structure but for your problem, considering you told me you didn't have any background on OOP and or patterns, but it's "good enough" as a temporary solution.
If you order it like this you can insert it into almost any framework without doing a lot of work.
Here's one way you can do it.
With the following classes:
<?php
class BasketballPage
{
protected $mapper;
public construct ( $mapper )
{
$this->mapper = $mapper;
}
public function display_player_info( $playerid, $sportid )
{
$basketball_player = $this->mapper->get_sports_player( $playerid, $sportid )
echo '<p>Basketball player name ' . $basketball_player['name'];
echo '<p>Some other HTML, etc</p>';
}
public function display_match_data($matchid, $sportid)
{
//Same as above but would call to $this_mapper->get_match_data(); And display relevant HTML.
}
public function display_player_info_AJAX( $playerid, $sportid )
{
$player = $this->mapper->get_sports_player();
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode( $player );
exit();
}
}
class BoxingPage
{
protected $mapper;
public function display_player_info( $playerid, $sportid)
{
$boxing_person = $this->mapper->get_sports_player( $playerid, $sportid)
echo '<p>Person\'s boxing name ' . $boxing_person['name'];
echo '<p>Some other HTML, etc</p>';
}
}
class Mapper
{
protected $connection;
public function __construct ( $connection )
{
$this->connection = $connection;
}
public function get_sports_player($id, $sportid)
{
$query = $this->connection->prepare( 'SELECT * FROM players WHERE id = :player_id AND sport_id' );
$query->bindValue(':player_id', $id, PDO::PARAM_INT);
$query->bindValue(':sport_id', $sport_id, PDO::PARAM_INT);
$query->execute();
return $query->fetchAll( PDO::FETCH_ASSOC );
}
public function get_match_data($matchid, $sportid)
{
//some query here that returns match data.
}
}
?>
You'd have a single php page for each of these classes, since they can grow big.
I.e:
Basketballpage.php
Boxingpage.php
Mapper.php
Then include these files into your index.php. and your index could look something like this:
index.php?playerid=1&sportid=2
<?php
//Instantiate the classes first.
$connection = new PDO($dsn,$username,$password); //your database credentials
$mapper = new Mapper( $connection );
$basketballpage = new BasketballPage( $mapper );
$boxingpage = new BoxingPage( $mapper );
if( $_GET['page'] == 2]) //lets say basketball is id 2 in your database
{
$basketballpage->display_player_info( $_GET['playerid'], $_GET['sportid'] );
}
//In this same page you'd also add this other line, but lets say they visit the bottom link instead: index.php?playerid=1&sportid=3
if( $_GET['page'] == 3]) //lets say boxing is 3 in your database
{
$boxing->display_player_info( $_GET['playerid'], $_GET['sportid'] );
}
//THEN lets say someone visits a different link like: index.php?index.php?matchid=1&sportid=2&page=2
if( $_GET['page'] == 2] && $_GET['matchid'])
{
$boxingpage->display_match_data( $_GET['playerid'] );
}
//On the above you can use that same category, but a different function will display a different page!
//Bonus example, you can use it for AJAX easily. Lets say they visit the url index.php?playerid=1&sportid=2&AJAX=1
if( $_GET['page'] == 2 && GET['AJAX'] == 1)
{
$basketballpage->display_player_info_AJAX( $_GET['playerid'], $_GET['sportid'] );
}
?>
It seems complicated but once you see how it's all connected, notice how your index page is only around 30-40 lines! It can make things really neat and you can just concentrate on routing your requests on index.php while the other files take care of the rest.
EAV is a great solution to handle different data models, you can also write a data mapping class, although I recommend you to use a PHP framework, why not ZEND?
The basic ideas to solving this well are:
Split your data retrieval from your display.
class Model { public function getData() {} }
class View { public function write() {} }
$model = new Model();
$view = new View();
$view->write($model->getData());
Implement Model::getData:
Loop to build the sports that you are interested in so that you can OR them in a query.
Get all of the results.
Use PHP to order the array into sports.
Implement View::write:
Loop over each sport, displaying it correctly.