I want to create a simple menu function which can call it example get_menu()
Here is my current code.
<?php
$select = 'SELECT * FROM pages';
$query = $db->rq($select);
while ($page = $db->fetch($query)) {
$id = $page['id'];
$title = $page['title'];
?>
<?php echo $title; ?>
<?php } ?>
How to do that in?
function get_menu() {
}
Let me know.
Here is the function for that:
function get_menu(&$db)
{
$select = 'SELECT * FROM pages';
$query = $db->rq($select);
$menu = '';
while ($page = $db->fetch($query)) {
$id = $page['id'];
$title = $page['title'];
$menu .= '<a href="page.php?id=' . $id . '" &title="' . $title .'></a>'
}
return $menu;
}
.
Some Quick Corrections In Your Script:
You were missing = after id
You were missing & after title
Suggestion:
You can give your menu links a class and style as per your menu needs :)
get_menu() has to get reference to $db somehow. Probably the best and easiest way is to pass that reference as parameter:
function get_menu(MyDatabaseHandler $db) {
// code proposed by Sarfraz here
}
now here you already have a mistake:
<?php echo $title; ?>
notice the = after id
you can't be too careful
First, separate the part where you're doing something, and the one used to display things.
Second, the alternative syntax looks better for the display part.
<?php
function get_menu(){
$items = array();
$select = 'SELECT * FROM pages';
$query = $db->rq($select);
while ($page = $db->fetch($query)) {
$items[] = $page['id'];
}
return $items;
}
$menuItems = get_menu();
?>
<ul>
<?php foreach($menuItems as $item): ?>
<li><?php echo $item['title']; ?></li>
<?php endforeach;?>
</ul>
The code Sarfraz posted is going to create invalid anchor tags (i.e. links). They'll also be missing names. Here is the shorter/faster version:
function get_menu($db)
{
$result = $db->rq('SELECT id,title FROM pages');
$menu = '';
while ($page = $db->fetch($result))
{
$id = $page['id'];
$title = $page['title'];
$menu .= "<a href='page.php?id={$id}&title={$title}'>{$title}</a>\n";
}
return $menu;
}
To use that do this:
echo get_menu($db);
The error you were getting was probably resulting from not passing the database connection to the function.
NOTE: It's generally not a good idea to show database ID numbers to the user in the interest of security; slugs are much better for identifying pages and are SEO friendly. Also, there shouldn't be any need to pass the page title to page.php because if you've got the ID you can get that when you need it from the database. Here's the code with this in mind:
function get_menu($db)
{
$result = $db->rq('SELECT id,title FROM pages');
$menu = '';
while ($page = $db->fetch($result))
{
$menu .= "<a href='page.php?id={$page['id']}'>{$page['title']}</a>\n";
}
return $menu;
}
just put function get_menu() { above your code and } below
or like this??
function get_menu( $title, $id ) {
$menu = '';
$menu .= '<a href="page.php?id' . $id . '" title="' . $title .'></a>'
echo $menu;
}
------------------------
$select = 'SELECT * FROM pages';
$query = $db->rq($select);
while ($page = $db->fetch($query)) {
$id = $page['id'];
$title = $page['title'];
get_menu($title, $id );
}
function getMenu()
{
$select = 'SELECT FROM pages';
$query = $db->rq($select);
$menu = new Array;
while ($page = $db->fetch($query)) {
$menu[] = '';
}
return $menu;
}
Related
I need two print the same rows which retrieved from the db, in two different locations in same php file.
I know it is better to have a function. It tried, It doesn't work properly.
I am using the below code print the said rows/
$get_g = "SELECT * FROM profile_groups";
$get_gr = mysqli_query($condb ,$get_g);
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
echo "<option value='".$groups['profile_gid']."'>".$groups['profile_gname']."</option>";
}
}
else
{
echo '<option value="">Empty - No Groups!!</option>';
}
I need to print exactly the same code twice in two different location in a php file.
I think it is not a good idea to retrieve data twice from the server by pasting the above code twice.
Is there any way to recall or reprint the retrieved data in second place which I need to print.
Edit : Or else, if someone can help me to convert this to a function?
I converted this into a function. It prints only first row.
Edit 2 : Following is my function
unction getGroup($dbconn)
{
$get_g = "SELECT * FROM profile_groups";
$get_gr = mysqli_query($dbconn ,$get_g);
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
$groupData = "<option value='".$groups['profile_gid']."'>".$groups['profile_gname']."</option>";
}
}
else
{
echo '<option value="">Empty - No Groups!!</option>';
}
return $groupData;
You can store the records coming from the DB in array and use a custom function to render the element
$get_g = "SELECT * FROM profile_groups";
$get_gr = mysqli_query($condb ,$get_g);
$options = []; //store in an array
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
$options[$groups['profile_gid']] = $groups['profile_gname'];
}
}
Now you can use the $options array many times in your page
echo renderElement($options);
function renderElement($ops){
$html = '';
foreach($ops as $k => $v){
$html .= "<option value={$k}>{$v}</option>";
}
return $html;
}
If the data is same for both places, put the entire string into variable, then echo it on those two places.
instead of
echo "here\n";
echo "there\n";
do
$output = "here\n";
$output .= "there\n";
then somewhere
echo $output
on two places....
Values are being stored in groups array, hence you can use a foreach loop elsewhere to get values from the array:
$groups = array();
$get_g = "SELECT * FROM profile_groups";
$get_gr = mysqli_query($condb ,$get_g);
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
echo "<option value='".$groups['profile_gid']."'>".$groups['profile_gname']."</option>";
}
}
else
{
echo '<option value="">Empty - No Groups!!</option>';
}
// use here
foreach($groups as $group)
{
echo $group['profile_gid'] . " ". $group['profile_gname'] . "<br/>";
}
class ProfileGroups
{
public $profile_groups_options;
public static function get_profile_groups_options($condb) {
$get_g = "SELECT * FROM profile_groups";
if( isset( $this->profile_groups_options ) && $this->profile_groups_options != '') {
return $this->profile_groups_options;
}
$get_gr = mysqli_query($condb ,$get_g);
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
$this->profile_groups_options .= "<option value='".$groups['profile_gid']."'>".$groups['profile_gname']."</option>";
}
}
else
{
$this->profile_groups_options .= '<option value="">Empty - No Groups!!</option>';
}
return $this->profile_groups_options;
}
}
ProfileGroups::get_profile_groups_options($condb);
I have class called posts in a separate file :
<?php
class POSTS {
//Start of class properties:
private $db_connection;
public $post_id;
public $section_id;
public $user_id;
public $post_title;
public $post_details;
public $post_date;
public $post_category;
public $post_display;
public $num_of_rows;
public function getRelatedPosts($section_name, $category, $display) {
$stm = $this->db_connection->prepare("SELECT * FROM posts WHERE section_name!=:Section_name AND category=:Category AND display=:Display ORDER BY id DESC");
$stm->bindParam(":Section_name", $section_name);
$stm->bindParam(":Category", $category);
$stm->bindParam(":Display", $display);
$stm->execute();
$this->num_of_rows = $stm->rowCount();
if ($this->num_of_rows >= 1) {
$post_data = $stm->fetch(PDO::FETCH_OBJ);
$this->post_id = $post_data->id;
$this->section_id = $post_data->section_id;
$this->user_id = $post_data->user_id;
$this->post_title = $post_data->title;
$this->post_details = $post_data->details;
$this->post_date = $post_data->date;
$this->post_category = $post_data->category;
$this->post_display = $post_data->display;
}
}
}
?>
Then I want to loop through the results in my Index file:
$section_name = 'PHP';
$display = 'yes';
$POSTS->getRelatedPosts($section_name, $category $display);
$num_of_rows = $POSTS->num_of_rows;
if ($num_of_rows >= 1) {
for ($m=1; $m<=$num_of_rows; $m++) {
$post_id = $POSTS->post_id;
$section_id = $POSTS->section_id;
$user_id = $POSTS->user_id;
$post_title = $POSTS->post_title;
$post_details = $POSTS->post_details;
$post_date = $POSTS->post_date;
?>
<div id="related_post">
<h4><?php echo $post_title;?></h4>
<p><?php echo $post_details;?></p>
</div>
<?php
}
} else {
echo 'Sorry no related posts now!';
}
Unfortunately The results are only one record repeated as many as the $num_of_rows variable equal.
I tried some different ways with fetch methods like:
fetchAll() and others styles but always the result is an error or only one record repeated.
Someone help me with my code please.
If you want to loop, try looping in your method:
public function getRelatedPosts($section_name, $category, $display)
{
$stm = $this->db_connection->prepare("SELECT * FROM posts WHERE section_name!=:Section_name AND category=:Category AND display=:Display ORDER BY id DESC");
$stm->bindParam(":Section_name", $section_name);
$stm->bindParam(":Category", $category);
$stm->bindParam(":Display", $display);
$stm->execute();
$this->num_of_rows = $stm->rowCount();
if ($this->num_of_rows >= 1) {
while($post_data = $stm->fetch(PDO::FETCH_OBJ)) {
$this->post_id[] = $post_data->id;
$this->section_id[] = $post_data->section_id;
$this->user_id[] = $post_data->user_id;
$this->post_title[] = $post_data->title;
$this->post_details[] = $post_data->details;
$this->post_date[] = $post_data->date;
$this->post_category[] = $post_data->category;
$this->post_display[] = $post_data->display;
}
}
}
Your loop would likely be something like:
for ($m=1; $m<=$num_of_rows; $m++) {
$post_id = $POSTS->post_id[$m];
$section_id = $POSTS->section_id[$m];
$user_id = $POSTS->user_id[$m];
$post_title = $POSTS->post_title[$m];
$post_details = $POSTS->post_details[$m];
$post_date = $POSTS->post_date[$m];
?>
<div id="related_post">
<h4><?php echo $post_title;?></h4>
<p><?php echo $post_details;?></p>
</div>
<?php
}
In my class I should use the following instead of the current one:
$results = $stm->fetchAll(PDO::FETCH_OBJ);
I will not get any advantages of my current class properties.
In my index file I will loop through the $results using foreach loop as the following:
foreach($results as $post){
$post_title = $post->title;
$post_details = $post->details;
}
and so on...
I'm experimenting with PDO and I had the same issue with PDO::FETCH_OBJ
I'm using PHP 5.6 in xampp 5.6.30
needless to say that
- the DB name is animals
- it has three columns only : animal_id, animal_type, animal_name
the following test code works fine and outputs all the records (that in my test DB are only eleven)
$stmt = $dbh->prepare("SELECT * FROM animals");
$stmt->execute();
if($stmt->rowCount() > 0) {
while($obj = $stmt->fetch(PDO::FETCH_OBJ)) {
echo $obj->animal_type . " " . $obj->animal_name . "<br>";
}
}
perhaps you may insert the counters inside the loop or, even better, make the query to properly limit the range.
Anyway, the code above, as expected outputs what follow
kookaburra bruce
emu bruce
goanna bruce
dingo bruce
kangaroo bruce
wallaby bruce
wombat bruce
koala bruce
kiwi cambiato
pippo zollo
pippz zoll2
My problem is that when I press on the pagination link the URL CHANGE and the segment array also so, first I started with this URL:
site/argument/argument
and when I press the pagination link the URL turn into:
site/method/startIndex.
Is there a way to use pagination without using the URL query index ?
EDIT:
Here is my controller method where I've receive the arguments from the URL:
function index ($par1, $par2 = null, $par3 = null)
{
$data['records'] = $this->site_model->getRecords($par1, $par2, $par3);
$this->load->view('main', $data);
}
And this is the Model method where I've do the DB query:
function getRecords($par1, $par2 = null, $par3 = null )
{
if (!isset($par2) && !isset($par3)) {
$where = "lvlOne = '".$par1."'";
} elseif(isset($par2) && !isset($par3)) {
$where = "lvlOne = '".$par1."' AND lvlTwo = '".$par2."'";
} elseif(isset($par2) && isset($par3)) {
$where = "lvlOne = '".$par1."' AND lvlTwo = '".$par2."' AND lvlThree = '".$par3."'";
}
$this->db->from('mph_products');
$this->db->where($where);
$query = $this->db->get();
return $query->result();
}
How can I paginate this results? Because I've got conflicts with the pagination library URL
EDIT:
I've found a way to do what I've wanted to.
There is a config option of the Pagination Library where you put the suffix of the pagination anchor and you can pass the arguments to it.
$config['suffix'] = "$arg1/$arg2/$arg3";
:D
This library codeigniter pagination + bootstrap design
<?php
class Paginacao
{
public $CI;
function __construct() {
$this->CI = &get_instance();
$this->CI->load->library('pagination');
}
function criar($total_rows,$base_url,$per_page=15,$num_links=5)
{
$paginacao['total_rows'] = $total_rows;
$paginacao['base_url'] = site_url($base_url);
$paginacao['per_page'] = $per_page;
$paginacao['num_links'] = $num_links;
$paginacao['full_tag_open'] = '<br /><div class="pagination pagination-centered"><ul>';
$paginacao['full_tag_close'] = '</ul></div>';
$paginacao['first_link'] = 'Primeira';
$paginacao['first_tag_open'] = '<li>';
$paginacao['first_tag_close'] = '<li>';
$paginacao['last_link'] = 'Ultima';
$paginacao['last_tag_open'] = '<li>';
$paginacao['last_tag_close'] = '</li>';
$paginacao['next_link'] = 'Próximo';
$paginacao['next_tag_open'] = '<li>';
$paginacao['next_tag_close'] = '</li>';
$paginacao['prev_link'] = 'Anterior';
$paginacao['prev_tag_open'] = '<li>';
$paginacao['prev_tag_close'] = '</li>';
$paginacao['cur_tag_open'] = '<li class="active"><a href="#">';
$paginacao['cur_tag_close'] = '</a></li>';
$paginacao['num_tag_open'] = '<li>';
$paginacao['num_tag_close'] = '</li>';
$this->CI->pagination->initialize($paginacao);
$html = $this->CI->pagination->create_links();
return $html;
}
}
As I understand, you want not to see page number in url, but CI Pagination class always add number to link. For more details see Pagination class.
Also you can use jquery datatable for client or server pagination.
During my coding I really got stuck into this problem.
I ran a foreach loop and for every item I had to get a certain value from a function.
But I got only one returned. I could not figure out what was happening. I hope you guys surely will.
Below is the short version of my program.
Database structure is given at last.
<?php
function opendb() {
mysql_connect("localhost", "root", "root");
mysql_select_db("something_db");
}
function sql_query($sql) {
$datas = array();
if ($res = mysql_query($sql)) {
$x = 0;
while ( $data = mysql_fetch_assoc($res) ) {
$datas[$x] = $data;
$x += 1;
}
}
return $datas;
}
function get_parent_id($table, $parent, $cid) {
// cid=>child id
$sql = "SELECT * FROM $table WHERE id=$cid";
$datas = sql_query($sql);
$pid = $datas[0]['parent'];
$p_id = $datas[0]['id'];
if ($pid != 0) {
get_parent_id($table, $parent, $pid);
} else {
return $p_id;
}
}
opendb();
$datas_pkg = sql_query("SELECT * FROM tbl_packages WHERE 1");
foreach ( $datas_pkg as $data_pkg ) {
echo $data_pkg['destination_id'] . '-->';
echo $parent_id = get_parent_id('tbl_destinations', 'parent', $data_pkg['destination_id']);
echo '<br/>';
}
?>
Database structure..
tbl_destinations
+--------+-------------------------+-----------+
| id(int)|destination_name(Varchar)|parent(int)|
+--------+-------------------------+-----------+
tbl_packages
+-------+---------------------+-------------------+
|id(int)|package_name(varchar)|destination_id(int)|
+-------+---------------------+-------------------+
If I did not clear my question please let me know so that I can help you to help me.
if($pid!=0)
{
get_parent_id($table,$parent,$pid);
}
You call the function, but never use its value.
Problem:
I am trying to delete all sublevels of a category by using a class. Currently I can only make it delete two sublevels, not three.
The database table:
CREATE TABLE betyg_category (
CID int(11) NOT NULL AUTO_INCREMENT,
Item varchar(100) NOT NULL,
Parent int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (CID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The PHP class:
<?php
class ItemTree
{
var $itemlist = array();
function ItemTree($query)
{
$result = mysql_query($query) or die ('Database Error (' . mysql_errno() . ') ' . mysql_error());
while ($row = mysql_fetch_assoc($result))
{
$this->itemlist[$row['CID']] = array(
'name' => $row['Name'],
'parent' => $row['Parent']
);
}
}
function get_tree($parent, $with_parent=0)
{
$item_tree = array();
if ($with_parent == 1 && $parent != 0)
{
$item_tree[$parent]['name'] = $this->itemlist[$parent]['name'];
$item_tree[$parent]['parent'] = $this->itemlist[$parent]['parent'];
$item_tree[$parent]['child'] = $this->get_tree($parent);
return $item_tree;
}
foreach ($this->itemlist as $key => $val)
{
if ($val['parent'] == $parent)
{
$item_tree[$key]['name'] = $val['name'];
$item_tree[$key]['parent'] = $val['parent'];
$item_tree[$key]['child'] = $this->get_tree($key);
}
}
return $item_tree;
}
function make_optionlist ($id, $class='', $delimiter='/')
{
$option_list = '';
$item_tree = $this->get_tree(0);
$options = $this->make_options($item_tree, '', $delimiter);
if (!is_array($id))
{
$id = array($id);
}
foreach($options as $row)
{
list($index, $text) = $row;
$selected = in_array($index, $id) ? ' selected="selected"' : '';
$option_list .= "<option value=\"$index\" class=\"$class\"$selected>$text</option>\n";
}
return $option_list;
}
function make_options ($item_tree, $before, $delimiter='/')
{
$before .= empty($before) ? '' : $delimiter;
$options = array();
foreach ($item_tree as $key => $val)
{
$options[] = array($key, '- '.$before.$val['name']);
if (!empty($val['child'])) {
$options = array_merge($options, $this->make_options($val['child'], $before.$val['name'], $delimiter));
}
}
return $options;
}
function get_navlinks ($navid, $tpl, $startlink='', $delimiter=' » ')
{
// $tpl typ: {name}
$search = array('{id}', '{name}');
$navlink = array();
while (isset($this->itemlist[$navid]))
{
$replace = array($navid, $this->itemlist[$navid]['name']);
$navlink[] = str_replace($search, $replace, $tpl);
$navid = $this->itemlist[$navid]['parent'];
}
if (!empty($startlink))
{
$navlink[] = str_replace($search, array(0, $startlink), $tpl);
}
$navlink = array_reverse($navlink);
return implode($delimiter, $navlink);
}
function show_tree ($parent=0, $tpl='%s', $ul_class='', $li_class='')
{
$item_tree = $this->get_tree($parent);
return $this->get_node($item_tree, $parent, $tpl, $ul_class, $li_class);
}
function get_node ($item_tree, $parent, $tpl, $ul_class, $li_class)
{
// $tpl typ: {name}
$search = array('{id}', '{name}');
$output = "\n<ul class=\"$ul_class\">\n";
foreach ($item_tree as $id => $item)
{
$replace = array($id, $item['name']);
$output .= "<li class=\"$li_class\">".str_replace($search, $replace, $tpl);
$output .= !empty($item['child']) ? "<br />".$this->get_node ($item['child'], $id, $tpl, $ul_class, $li_class) : '';
$output .= "</li>\n";
}
return $output . "</ul>\n";
}
function get_id_in_node ($id)
{
$id_list = array($id);
if (isset($this->itemlist[$id]))
{
foreach ($this->itemlist as $key => $row)
{
if ($row['parent'] == $id)
{
if (!empty($row['child']))
{
$id_list = array_merge($id_list, get_id_in_node($key));
} else
{
$id_list[] = $key;
}
}
}
}
return $id_list;
}
function get_parent ($id)
{
return isset($this->itemlist[$id]) ? $this->itemlist[$id]['parent'] : false;
}
function get_item_name ($id)
{
return isset($this->itemlist[$id]) ? $this->itemlist[$id]['name'] : false;
}
}
?>
Scenario:
Say you have the following structure in a :
Literature
-- Integration of sources
---- Test 1
It will result in the following in the database table:
When I try to delete this sublevel, it will leave the last sublevel in the database while it should delete it. The result will be:
The PHP code:
//Check if delete button is set
if (isset($_POST['submit-deletecategory']))
{
//Get $_POST variables for category id
$CategoryParent = intval($_POST['CategoryList']);
//Check if category is selected
if ($CategoryParent != "#")
{
//Get parent category and subsequent child categories
$query = "SELECT CID, Item AS Name, Parent FROM " . TB_CATEGORY . " ORDER BY Name";
$items = new ItemTree($query);
if ($items->get_item_name($_POST['CategoryList']) !== false)
{
//Build up erase list
$CategoryErase = $items->get_id_in_node($CategoryParent);
$CategoryEraseList = implode(", ", $CategoryErase);
}
else
{
$CategoryEraseList = 0;
}
//Remove categories from database
$query = "DELETE FROM " . TB_CATEGORY . " WHERE CID IN ($CategoryEraseList)";
$result = mysql_query($query) or die ('Database Error (' . mysql_errno() . ') ' . mysql_error());
//Return a confirmation notice
header("Location: settings.php");
exit;
}
}
Thank you in advance for any guidance I can get to solve the issue.
Here is a way to do it : use a recursive function, which will first look for the leaf item (the deepest in your tree). You remove children first, then the parent. And for each child, you remove child's children first, etc...
deleteSub(1);
function deleteSub($cat_id) {
$request = "SELECT * FROM ". TB_CATEGORY ." WHERE Parent = ".$cat_id;
$results = mysql_query($request);
while($child = mysql_fetch_array($results))
{
deleteSub($child["CID"]);
}
$request = "DELETE FROM ". TB_CATEGORY ." WHERE CID = ".$cat_id;
return mysql_query($request);
}
A better way could be use this kind of recursive function to store CIDs in an array, then make a single DELETE request, but I think you'll be able to adapt this code.
I'm not going to read or try to understand the entire code, but it seems to me you need some sort of recursion function. What I basicly would do is create a function that goes up in the hierachy and one that goes down.
Note: It has been a while since i've written anything in procedural mysql, so please check if the mysql_num_rows(),mysql_fetch_array and so on is written in the correct manner
EDIT: I've just noticed you only wanted a downwards deletion and therefore zessx's answer is more valid
<?php
function recursiveParent($id) {
$sql = 'SELECT parent FROM betyg_category WHERE CID=' . $id;
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0) {
while($r = mysql_fetch_array($result,MYSQLI_ASSOC)) {
recursiveParent($r['parent']);
}
}
$sql = 'DELETE FROM betyg_category WHERE CID=' . $id;
mysql_query($sql);
}
function recursiveChild($parent) {
$sql = 'SELECT CID FROM betyg_category WHERE parent=' . $parent;
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0) {
while($r = mysql_fetch_array($result,MYSQLI_ASSOC)) {
recursiveChild($r['CID']);
}
}
$sql = 'DELETE FROM betyg_category WHERE parent=' . $parent;
mysql_query($sql);
}
function delete($id) {
recursiveParent($id);
recursiveChild($id);
}
?>
This is my way to do. instead of recursive the query to run, i get all the child's id first then only run query. here the code refer:-
First, defined a variable called $delete_node_list as array. (to store all node id that need to be delete)
function delete_child_nodes($node_id)
{
$childs_node = $this->edirectory_model->get_child_nodes($node_id);
if(!empty($childs_node))
{
foreach($childs_node as $node)
{
$this->delete_child_nodes($node['id']);
}
}
$this->delete_node_list[] = $node_id;
}
in mysql..
$sql = 'DELETE FROM betyg_category WHERE CID IN '.$this->delete_node_list;
mysql_query($sql);