I'm trying to create a dynamic swiper that is able to automatically update itself whenever I make changes in the database. The problem that I've encountered right now is that I've got 6 pictures and description in the swiper but all of them only retrieve from the first field from my database.
Old screenshot of the page. As you can see from the first screenshot I am able to retrieve the data which is the picture and the description from the database, but only repeatingly retrieve from the first field of the database for all the 6 results. Able to show it in the php area. Only the first slider is working when i called the function in html.
Any help would be appreciated, thank you.
<?php
$connect = mysqli_connect("localhost", "root", "", "db");
$result = make_query($connect);
function fetch_array(&$array) {
// Grab the first value from the array
$return = current($array);
// remove the value we just grabbed
array_shift($array);
// if what we have is an array spit it out, else return false
return is_array($return) ? $return : false;
}
function make_query($connect) {
$query = "SELECT * FROM db.slider ORDER BY p_id ASC";
$result = mysqli_query($connect, $query);
return $result;
}
function make_slide_indicators($result) {
$output = '';
$count = 0;
for($i = 0;$i<mysqli_num_rows($result);$i++) {
//for($i = 0;$i<count($result);$i++) {
if ($i == 0) {
$output .= '<li data-target="#" data-slide-to="'.$i.'" class="active"></li>';
} else {
$output .= '<li data-target="#" data-slide-to="'.$i.'"></li>';
}
$count++ === $count = $count + 1;
}
return $output;
}
function make_slides($result) {
$output = '';
$count = 0;
while($row = mysqli_fetch_assoc($result)) {
//while($row = fetch_array($result)) {
// Not needed as the output is the same
if($count == 0) {
$output .= '
<div class="swiper-slide platform">
<img src="'.$row["p_img"].'" alt="'.$row["p_name"].'" />
<div class="swiper-slide platform">
<h3>'.$row["p_desc"].'</h3>
</div>
</div>';
// Not used at the moment
$count++;
}
}
return $output;
}
$connect = mysqli_connect("localhost", "root", "", "db");
$result = make_query($connect);
$result = [['p_img' => 'img','p_name' => 'name','p_desc' => 'desc'],['p_img' => 'img','p_name' => 'name','p_desc' => 'desc'],['p_img' => 'img','p_name' => 'name','p_desc' => 'desc'],['p_img' => 'img','p_name' => 'name','p_desc' => 'desc']];
echo make_slide_indicators($result);
echo PHP_EOL;
echo make_slides($result);
?>
When working with databases use while instead of foreach. The problem you're having is that mysqli_result is not exactly what you think it is, You can have a look here:
https://www.php.net/manual/en/class.mysqli-result.php
Here is a clean version of the code provided. I didn't setup a db for this so to test the logic I implemented a dummy function to work on a set array. I hope the comments are helpful.
function fetch_array(&$array) {
// Grab the first value from the array
$return = current($array);
// remove the value we just grabbed
array_shift($array);
// if what we have is an array spit it out, else return false
return is_array($return) ? $return : false;
}
function make_query($connect) {
$query = "SELECT * FROM db.slider ORDER BY p_id ASC";
$result = mysqli_query($connect, $query);
return $result;
}
function make_slide_indicators($result) {
$output = '';
$count = 0;
//for($i = 0;$i<mysqli_num_rows($result);$i++) {
for($i = 0;$i<count($result);$i++) {
if ($i == 0) {
$output .= '<li data-target="#" data-slide-to="'.$i.'" class="active"></li>';
} else {
$output .= '<li data-target="#" data-slide-to="'.$i.'"></li>';
}
// $count++ === $count = $count + 1;
}
return $output;
}
function make_slides($result) {
$output = '';
// $count = 0;
//while($row = mysqli_fetch_assoc($result)) {
while($row = fetch_array($result)) {
// Not needed as the output is the same
//if($count == 0) { ... } else { ... }
$output .= '
<div class="swiper-slide platform">
<img src="'.$row["p_img"].'" alt="'.$row["p_name"].'" />
<div class="swiper-slide platform">
<h3>'.$row["p_desc"].'</h3>
</div>
</div>';
// Not used at the moment
// $count++;
}
return $output;
}
//$connect = mysqli_connect("localhost", "root", "", "db");
//$result = make_query($connect);
$result = [['p_img' => 'img','p_name' => 'name','p_desc' => 'desc'],['p_img' => 'img','p_name' => 'name','p_desc' => 'desc'],['p_img' => 'img','p_name' => 'name','p_desc' => 'desc'],['p_img' => 'img','p_name' => 'name','p_desc' => 'desc']];
echo make_slide_indicators($result);
echo PHP_EOL;
echo make_slides($result);
The biggest difference in the code is that we're using mysqli_num_rows() in make_slide_indicators(). We don't need to fetch all the data from the mysql result, we just need the number of rows we received.
That solves another problem. If you go trough the whole result with mysqli_fetch_assoc() the next time you would try to work on the same result you would only get the last value. The result has in internal pointer that moves a position forward when a line is read.
If you would ever want to go over a result more then once you'd need to use mysqli_data_seek(). Have a look here:
https://www.php.net/manual/en/mysqli-result.data-seek.php
If you run the code as is You'll see that the logic works correctly. If you still have an issue when you switch to the db connection the problem is there. Here's a quick debug check for you:
$connect = mysqli_connect("localhost", "root", "", "db");
$result = make_query($connect);
echo "Number of rows: ".mysqli_num_rows($result).PHP_EOL;
while($r = mysqli_fetch_assoc($result)) {
var_dump($r);
}
Related
i have a PHP code that creates a team page with team member boxes on my website. The code for every team meber is fetched from the database, and it works fine, but time has passed and we are many now. So many, that I need to display only 5 team members per section. Like 5 team members in one line, the next 5 in the other line, .. - I tried a few things to do that, but I got stuck. Sometimes members were missing, sometimes he created many lines with the same members, and so on. That's why I'm asking here. I already searched a bit but couldn't find anything that helps me.
Currently, my code creates a new <section> for ALL team members. But that's not what I need. It should create a section for 5 members, the next section for the next 5 members, and so on. How can I do that?
(btw I'm a complete beginner in PHP and want to learn something from it so you can improve my code if you want.)
function team_helfer() {
$db = new mysqli("ip", $username, $password, $database);
$result = mysqli_query($db, "SELECT code FROM team_data WHERE rank = 'HELFER'");
$team_list = "";
$count = 0;
while ($row = mysqli_fetch_assoc($result)) {
foreach ($row as $field => $value) {
$team_list .= "$value";
++$count;
}
}
if ($count == 2) {
$code = '<section class="elementor-section elementor-inner-section elementor-element elementor-section-boxed elementor-section-height-default elementor-section-height-default" data-element_type="section">
<div class="elementor-container elementor-column-gap-default" style="left: 17%;">
'.$team_list.'
</div>
</section>';
} elseif ($count == 1) {
$code = '<section class="elementor-section elementor-inner-section elementor-element elementor-section-boxed elementor-section-height-default elementor-section-height-default" data-element_type="section">
<div class="elementor-container elementor-column-gap-default" style="left: 33%;">
'.$team_list.'
</div>
</section>';
} else {
$code = '<section class="elementor-section elementor-inner-section elementor-element elementor-section-boxed elementor-section-height-default elementor-section-height-default" data-element_type="section">
<div class="elementor-container elementor-column-gap-default">
'.$team_list.'
</div>
</section>';
}
mysqli_free_result($result);
$db->close();
return $code;
}
add_shortcode( 'team_helfer', 'team_helfer' );
Code from HTMHell's answer:```php
function team_helfer() {
$db = new mysqli("ip", $username, $password, $database);
$result = mysqli_query($db, "SELECT code FROM team_data WHERE rank = 'HELFER'");
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
$sections = array_chunk($rows, 5);
foreach ($sections as $section) {
$teamList = implode(",", array_map(function($row) {
return $row['code'];
}));
$code = '<section class="elementor-section elementor-inner-section elementor-element elementor-section-boxed elementor-section-height-default elementor-section-height-default" data-element_type="section">
<div class="elementor-container elementor-column-gap-default">'.$teamList.'</div></section>';
}
mysqli_free_result($result);
$db->close();
return $code;```
Sadly that doesn't help, all elements are vanished now, i can't see them.
I think you are looking for array_chunk.
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
$sections = array_chunk($rows, 5);
foreach ($sections as $section) {
$teamList = implode(",", array_map(function($row) {
return $row['code'];
}, $section));
echo "<section>$teamList</section>";
}
Here's a live example:
https://3v4l.org/mXRtV
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);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am currently working on a multiple select drop-down list. I need to display the selected values on an edit form.
in_array() is not working as I expect, do I have an error in my logic?
The code to display the selected values from the database is:
<div class="form-group">
<label class="col-md-3 control-label" for="selectbasic">Update Artist Selection</label>
<div class="col-md-6">
<select id="artists1" multiple="multiple" name="id_artist_fk[]" class="form-control ">
<?php
foreach ($artist_list as $key => $value) {
if (in_array($value['id_artist'], $current_artist_list, true)) {
$selected = "selected='selected'";
}
// print_r($value['id_artist']. "==". $current_artist_list);
echo "<option value=\"{$value['id_artist']}\" {$selected}>{$value['name']} {$value['surname']}</option>";
}
?>
</select>
</div>
</div>
The $artist_list is gotten via:
public function get_artist_list() {
$sql = "SELECT * FROM tbl_v_artist WHERE status != 0;";
$result = $this->database->doSelectQuery($sql);
$artists = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_array()) {
$artist = array(
'id_artist' => $row['id_artist'],
'name' => $row['name'],
'surname' => $row['surname'],
'status' => $row['status']
);
array_push($artists, $artist);
}
}
return $artists;
}
The $current_artist_list is gotten via:
$current_artist_list = $vid->get_artistsID_for_video($_POST['id_video']);
get_artistsID_for_video is:
public function get_artistsID_for_video($video_id) {
try {
$sql = "SELECT
tbl_video_artist.id_artist_fk
FROM tbl_video_artist
left join tbl_v_artist
ON tbl_v_artist.id_artist = tbl_video_artist.id_artists
WHERE tbl_video_artist.id_video_fk = {$video_id};";
//echo $sql;
$result = $this->database->doSelectQuery($sql);
$artists = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_array()) {
$artist = array(
'id_artist_fk' => $row['id_artist_fk']
);
array_push($artists, $artist);
}
}
return $artists;
} catch (Exception $ex) {
$ex->getMessage();
$ex->getFile();
}
}
Please help point me in the right direction.
I have edited the get_artistsID_for_video as follows:
public function get_artistsID_for_video($video_id) {
try {
$sql = "SELECT
tbl_video_artist.id_artist_fk
FROM tbl_video_artist
left join tbl_v_artist
ON tbl_v_artist.id_artist = tbl_video_artist.id_artists
WHERE tbl_video_artist.id_video_fk = {$video_id};";
//echo $sql;
$result = $this->database->doSelectQuery($sql);
// $artists = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_array()) {
$artist [] = $row['id_artist_fk'];
// array_push($artists, $artist);
}
return $artist;
}
} catch (Exception $ex) {
$ex->getMessage();
$ex->getFile();
}
}
Look at in_array manual:
in_array — Checks if a value exists in an array
So, what checks your in_array($value['id_artist'], $current_artist_list, true)?
It checks that in $current_artist_list exists value of $value['id_artist']. For example, if $value['id_artist'] is 20, in_array checks if value 20 is in your array.
But value 20 is NOT in your $current_artist_list array.
Because format of each element in your $current_artist_list is array('id_artist_fk' => $row['id_artist_fk']).
So, you're searching for 20, but value which you store is ('id_artist_fk' => 20).
20 NOT EQUALS array.
The fix is in get_artistsID_for_video():
while ($row = $result->fetch_array()) {
$artists[] = $row['id_artist_fk'];
}
Now you search for 20 in array where every element is a number too.
Making your search even faster (still in get_artistsID_for_video):
while ($row = $result->fetch_array()) {
// create array key with value of artist id
$artists[$row['id_artist_fk']] = 1;
}
And replace in_array with:
// check for existence of a key, not value.
if (!empty($current_artist_list[$value['id_artist']])) {
$selected = "selected='selected'";
}
Please check that $current_artist_list must be single array. i.e $current_artist_list[0] = 1;
$current_artist_list[1] = 2;
Which will match your id with condition. Right now it's looks like your $current_artist_list is associative array value having with key. Try to push only value as i mentioned above OR change the code as below.
$artists = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_array()) {
$artist = array(
'id_artist_fk' => $row['id_artist_fk']
);
array_push($artists, $row['id_artist_fk']);
}
}
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);