What I want to do is When I enter all my information (for client ID 199 in the picture) In my account being submit it, it goes into the database. BUT I want it to change to something and so i added an if statement
Here the code im adding to the existing code already at the BOTTOM of the code
if ($vpr_clid == 199) {
$vpr_cl_name = "Shelley Madsen And Associates";
}
if the ($vpr_clid = 199)
i want the clname to be "Shelley Madsen And Associates" then what is show in the table below instead of "Nice and White Smiles" (that an example of the results look like)
but when i chcek the database it not changing it and still show "Nice and White Smiles :(
I dont see any error, so it might be the placement of the code i have to put the IF statement in the huge php file? Dont know how to fix this issue
Thanks (the code below is the base code before i added the If statement)
I also insert the if statement before the function were called but still didnt work example
if ($vpr_clid == 199) {
$vpr_cl_name = "Shelley Madsen And Associates";
}
$result = InsertIntoPayReminder($link, $vars);
$result = GetVpr_Id($link, $vars);
<?php
session_start();
if ($_SESSION['company'] != "ACB") {
// redirect to the logout page
$redirect = 'logout.php';
include './includes/redirect.php';
}
class variables_obj {
var $vpr_plan = '';
var $vpr_id = '';
var $vpr_clid = '';
var $vpr_cl_name = '';
var $vpr_cl_phone = '';
var $vpr_call_start_date = '';
var $vpr_db_account = '';
var $vpr_db_fname = '';
var $vpr_db_mname = '';
var $vpr_db_lname = '';
var $vpr_rp_fname = '';
var $vpr_rp_mname = '';
var $vpr_rp_lname = '';
var $vpr_rp_address = '';
var $vpr_rp_city = '';
var $vpr_rp_state = '';
var $vpr_rp_zipcode = '';
var $vpr_rp_phonenum = '';
var $vpr_rp_phonetype = '';
var $vpr_date_entered = '';
var $newrecdt = '';
var $vpl_day_offset = '';
var $vpl_action = '';
var $vpr_promocode = '';
}
function ScrubPhone($old_phone_num) {
$phone_length = strlen($old_phone_num);
$new_phone_num = "";
for($i = 0; $i < $phone_length; $i = $i + 1) {
if(is_numeric($old_phone_num[$i])) {
$new_phone_num .= $old_phone_num[$i];
}
}
return $new_phone_num;
}
function ScheduleCreated($link, $vars) {
$query = "UPDATE v_payreminder SET vpr_schedule_created = '1' WHERE vpr_id='".$vars->vpr_id."'";
if (!mysql_query($query,$link)) {
die('Error: ' . mysql_error());
}
return true;
}
function CreateScheduleRow($link, $vars){
// echo "vpl_day_offset: ".$vars->vpl_day_offset."<br>";
// echo "vpl_action: ".$vars->vpl_action."<br>";
$plus_days = " +".$vars->vpl_day_offset." days";
// echo "plus days: ".$plus_days."<br>";
$date_offset = strtotime(date("Y-m-d", strtotime($vars->vpr_date_entered)).$plus_days);
$date_offset = date("Y-m-d", $date_offset);
// echo "date_offset: ".$date_offset."<br>";
// $date_offset = strtotime(date("Y-m-d",strtotime($vars->vpr_date_entered))." +".$vars->vpl_day_offset." days");
// $date_offset = strtotime(date("Y-m-d", strtotime($date)) . " +1 day");
// echo "date_offset: ".$date_offset."<br>";
$query = "INSERT INTO v_pr_schedule (
vpr_id,
vsc_plan,
vsc_date_entered,
vsc_action,
vsc_action_date,
vsc_status
) VALUES (
'$vars->vpr_id',
'$vars->vpr_plan',
'$vars->vpr_date_entered',
'$vars->vpl_action',
'$date_offset',
'VACT')";
//echo "query: ".$query."<br>";
if (!mysql_query($query,$link)) {
die('Error: ' . mysql_error());
}
return true;
}
function CreateSchedule($link, &$vars) {
// CREATE SCHEDULE
$query = " SELECT vpl_day_offset, vpl_action, vpl_condition
FROM v_plan
WHERE vpl_plan = '".$vars->vpr_plan."'";
// echo "query: ".$query."<br>";
$qresult = mysql_query($query);
if (!$qresult) {
print(mysql_error());
}
if ($qresult && mysql_num_rows($qresult) > 0 ) {
while ($row = mysql_fetch_array($qresult, MYSQL_ASSOC)) {
$vars->vpl_day_offset = $row['vpl_day_offset'];
$vars->vpl_action = $row['vpl_action'];
if ($row['vpl_condition'] == 'OO') {
CreateScheduleRow($link, $vars);
}
}
}
return true;
}
function InsertIntoPayReminder($link, &$vars) {
$vars->vpr_cl_name = strtr($vars->vpr_cl_name, "'", " ");
//echo "Client Name: ".$vars->vpr_cl_name."<br><br>";
//exit();
$sql="INSERT INTO v_payreminder (
vpr_clid,
vpr_cl_name,
vpr_cl_phone,
vpr_call_start_date,
vpr_db_account,
vpr_db_fname,
vpr_db_mname,
vpr_db_lname,
vpr_rp_fname,
vpr_rp_mname,
vpr_rp_lname,
vpr_rp_phonenum,
vpr_rp_phonetype,
vpr_rp_address,
vpr_rp_city,
vpr_rp_state,
vpr_rp_zipcode,
vpr_promo,
vpr_date_entered) VALUES (
'$vars->vpr_clid',
'$vars->vpr_cl_name',
'$vars->vpr_cl_phone',
'$vars->vpr_call_start_date',
'$vars->vpr_db_account',
'$vars->vpr_db_fname',
'$vars->vpr_db_mname',
'$vars->vpr_db_lname',
'$vars->vpr_rp_fname',
'$vars->vpr_rp_mname',
'$vars->vpr_rp_lname',
'$vars->vpr_rp_phonenum',
'$vars->vpr_rp_phonetype',
'$vars->vpr_rp_address',
'$vars->vpr_rp_city',
'$vars->vpr_rp_state',
'$vars->vpr_rp_zipcode',
'$vars->vpr_promocode',
'$vars->vpr_date_entered')";
if (!mysql_query($sql,$link)) {
die('Error2: ' . mysql_error());
}
return true;
}
function GetVpr_Id($link, &$vars) {
// Find out what vpr_id is
$query = "SELECT vpr_id FROM v_payreminder ";
$query .= "WHERE vpr_clid = '".$vars->vpr_clid."' AND vpr_date_entered = '".$vars->vpr_date_entered."'";
$qresult = mysql_query($query);
if (!$qresult) {
print(mysql_error());
}
if ($qresult && mysql_num_rows($qresult) > 0 ) {
$row = mysql_fetch_array($qresult, MYSQL_ASSOC);
$vars->vpr_id = $row['vpr_id'];
}
}
function InsertInActivity($link, $vars) {
// ENTER INTO ACTIVITY
$vaction_desc = 'PATIENT ENTERED';
$sql = "INSERT INTO v_pr_activity (
vpr_id,
va_plan,
va_action_dttm,
va_action_code,
va_action_desc,
va_disposition_code,
va_disposition_desc,
va_status_code,
va_status_desc
) VALUES (
'$vars->vpr_id',
'$vars->vpr_plan',
'$vars->vpr_date_entered',
'VINIT',
'$vaction_desc',
'SUCCESS',
'SUCCESS',
'VACT',
'ACTIVE'
)";
if (!mysql_query($sql,$link)) {
die('Error: ' . mysql_error());
}
}
include './includes/dblogin.php';
$vars = new variables_obj();
$vars->vpr_plan = 'VP01';
$vars->vpr_clid = $_SESSION['userid'];
//-------------------------------------------------------
// No commas can be in client name or they will
// mess up the Global Connect CSV file.
//-------------------------------------------------------
$vpr_cl_name = $_SESSION['username'];
$vpr_cl_name = str_replace(",", " ", $vpr_cl_name);
$vars->vpr_cl_name = $vpr_cl_name;
//-------------------------------------------------------
//-------------------------------------------------------
$vars->vpr_cl_phone = ScrubPhone($_SESSION['uphone']);
$vars->vpr_call_start_date = '0000-00-00';
$vars->vpr_db_account = $_POST['ndaccnum'];
$vars->vpr_db_fname = $_POST['ndfreqname'];
$vars->vpr_db_mname = $_POST['ndmname'];
$vars->vpr_db_lname = $_POST['ndlreqname'];
$vars->vpr_rp_fname = $_POST['ndrfreqname'];
$vars->vpr_rp_mname = $_POST['ndrmname'];
$vars->vpr_rp_lname = $_POST['ndrlreqname'];
$vars->vpr_rp_address = '';
$vars->vpr_rp_city = '';
$vars->vpr_rp_state = $_POST['ndrstatereqname'];
$vars->vpr_rp_zipcode = $_POST['ndrreqzipcode'];
$phonenumber = $_POST['1ndrreqphone'].$_POST['2ndrreqphone'].$_POST['3ndrreqphone'];
$vars->vpr_rp_phonenum = $phonenumber;
$vars->vpr_rp_phonetype = $_POST['treqphone'];
$vars->vpr_date_entered = date('Y-m-d H:i:s');
$vars->newrecdt = date('Ymd');
$vars->vpr_promocode = $_POST['promocode'];
// echo "vpr_plan: ".$vars->vpr_plan."<br>";
// echo "vpr_date_entered: ".$vars->vpr_date_entered."<br>";
// echo "newrecdt: ".$vars->newrecdt."<br>";
// echo "vpr_clid: ".$vars->vpr_clid."<br>";
// echo "vpr_id: ".$vars->vpr_id."<br>";
$result = InsertIntoPayReminder($link, $vars);
$result = GetVpr_Id($link, $vars);
$result = InsertInActivity($link, $vars);
$result = CreateSchedule($link, $vars);
$result = ScheduleCreated($link, $vars);
// echo "vpr_id: ".$vars->vpr_id."<br>";
mysql_close($link);
// redirect
$redirect = 'vpayremind.php';
include './includes/redirect.php';
?>
okay referencing the following lines..
if ( $vpr_clid == 199 ) {
$vpr_cl_name = "Shelley Madsen And Associates";
}
$result = InsertIntoPayReminder($link, $vars);
...and then:
function InsertIntoPayReminder($link, &$vars) {
$vars->vpr_cl_name = strtr($vars->vpr_cl_name, "'", " ");
so on and so forth... }
it doesnt seem as if you are actually setting the value of the class object. You seem to be setting some arbitrary php variable to the name you want, and then passing a totally different ' $vars ' object into the function. I don't see any reason to believe that the ' $vars ' you are passing into the function call contains the name value you want it to contain. You should be assigning the value of ' $vars ' before passing it in.
For instance:
if ( $vpr_clid == 199 ) {
$vars[ 'vpr_cl_name' ] = "Shelley Madsen And Associates";
}
then you can get rid of this line all together:
$vars->vpr_cl_name = strtr($vars->vpr_cl_name, "'", " ");
Related
I am getting error after saving sales and error is occurring in update product function, this function is working fine when i am updating product, but when i try to update product using edit-sales it is giving me this error.
Error
Code where error is
Picture 1 is what error i am getting after saving the edited sales..
picture 2 is code where error is occurring....
This is controller.sales ( which is calling model.edit-sales)
static public function ctrEditSale(){
if(isset($_POST["editSale"])){
/*=============================================
FORMAT PRODUCTS AND CUSTOMERS TABLES
=============================================*/
$table = "sales";
$item = "code";
$value = $_POST["editSale"];
$getSale = ModelSales::mdlShowSales($table, $item, $value);
/*=============================================
CHECK IF THERE'S ANY EDITED SALE
=============================================*/
if($_POST["productsList"] == ""){
$productsList = $getSale["products"];
$productChange = false;
}else{
$productsList = $_POST["productsList"];
$productChange = true;
}
if($productChange){
$products = json_decode($getSale["products"], true);
$totalPurchasedProducts = array();
foreach ($products as $key => $value) {
array_push($totalPurchasedProducts, $value["quantity"]);
$tableProducts = "products";
$item = "id";
$value1 = $value["id"];
$order = "id";
$getProduct = ProductsModel::mdlShowProducts($tableProducts, $item, $value1, $order);
$item1a = "sales";
$value1a = $getProduct["sales"] - $value["quantity"];
$newSales = ProductsModel::mdlUpdateProduct($tableProducts, $item1a, $value1a, $value);
$item1b = "stock";
$value1b = $value["quantity"] + $getProduct["stock"];
$stockNew = ProductsModel::mdlUpdateProduct($tableProducts, $item1b, $value1b, $value);
}
$tableCustomers = "customers";
$itemCustomer = "id";
$valueCustomer = $_POST["selectCustomer"];
$getCustomer = ModelCustomers::mdlShowCustomers($tableCustomers, $itemCustomer, $valueCustomer);
$item1a = "purchases";
$value1a = $getCustomer["purchases"] - array_sum($totalPurchasedProducts);
$customerPurchases = ModelCustomers::mdlUpdateCustomer($tableCustomers, $item1a, $value1a, $valueCustomer);
/*=============================================
UPDATE THE CUSTOMER'S PURCHASES AND REDUCE THE STOCK AND INCREMENT PRODUCT SALES
=============================================*/
$productsList_2 = json_decode($productsList, true);
$totalPurchasedProducts_2 = array();
foreach ($productsList_2 as $key => $value) {
array_push($totalPurchasedProducts_2, $value["quantity"]);
$tableProducts_2 = "products";
$item_2 = "id";
$value_2 = $value["id"];
$order = "id";
$getProduct_2 = ProductsModel::mdlShowProducts($tableProducts_2, $item_2, $value_2, $order);
$item1a_2 = "sales";
$value1a_2 = $value["quantity"] + $getProduct_2["sales"];
$newSales_2 = ProductsModel::mdlUpdateProduct($tableProducts_2, $item1a_2, $value1a_2, $value_2);
$item1b_2 = "stock";
$value1b_2 = $getProduct_2["stock"] - $value["quantity"];
$newStock_2 = ProductsModel::mdlUpdateProduct($tableProducts_2, $item1b_2, $value1b_2, $value_2);
}
$tableCustomers_2 = "customers";
$item_2 = "id";
$value_2 = $_POST["selectCustomer"];
$getCustomer_2 = ModelCustomers::mdlShowCustomers($tableCustomers_2, $item_2, $value_2);
$item1a_2 = "purchases";
$value1a_2 = array_sum($totalPurchasedProducts_2) + $getCustomer_2["purchases"];
$customerPurchases_2 = ModelCustomers::mdlUpdateCustomer($tableCustomers_2, $item1a_2, $value1a_2, $value_2);
$item1b_2 = "lastPurchase";
date_default_timezone_set('America/Bogota');
$date = date('Y-m-d');
$hour = date('H:i:s');
$value1b_2 = $date.' '.$hour;
$dateCustomer_2 = ModelCustomers::mdlUpdateCustomer($tableCustomers_2, $item1b_2, $value1b_2, $value_2);
}
/*=============================================
SAVE PURCHASE CHANGES
=============================================*/
$data = array("idSeller"=>$_POST["idSeller"],
"idCustomer"=>$_POST["selectCustomer"],
"code"=>$_POST["editSale"],
"products"=>$productsList,
"tax"=>$_POST["newTaxPrice"],
"netPrice"=>$_POST["newNetPrice"],
"totalPrice"=>$_POST["saleTotal"],
"paymentMethod"=>$_POST["listPaymentMethod"]);
$answer = ModelSales::mdleditSale($table, $data);
if($answer == "ok"){
echo'<script>
localStorage.removeItem("range");
swal({
type: "success",
title: "The sale has been edited correctly",
showConfirmButton: true,
confirmButtonText: "Close"
}).then((result) => {
if (result.value) {
window.location = "sales";
}
})
</script>';
}
}
}
above code is calling model edit-sales with data to update database
This is model edit sales method
mdl:editsale
you put in last attribute all array $value, you only need to put only id $value['id']
$item1a = "sales";
$value1a = $getProduct["sales"] - $value["quantity"];
$newSales = ProductsModel::mdlUpdateProduct($tableProducts, $item1a, $value1a, $value['id']);
$item1b = "stock";
$value1b = $value["quantity"] + $getProduct["stock"];
$stockNew = ProductsModel::mdlUpdateProduct($tableProducts, $item1b, $value1b, $value['id']);
here is some of the code where I declared the values for $list.
$list['first_name'] = Request::input("first_name");
$list['last_name'] = Request::input("last_name");
when I use dd($list), it shows the value like in my snipped image
but when it enters this if else statement,
if($existing_customer)
{
$customer_id = $existing_customer->customer_id;
}
else
{
dd($list);
$insert_customer["first_name"] = ($list['first_name'] == "undefined" ? "John" : ucfirst($list['first_name']));
$insert_customer["last_name"] = ($list['last_name'] == "undefined" ? "Doe" : ucfirst($list['last_name']));
}
this is the result.
here is the photo of my function, if it could help.
first
second
public function import_submit()
{
$data = Self::get_initial_settings();
/* INITIALIZE AND CAPTURE DATA */
$shop_id = $this->user_info->shop_id;
$sponsor = Tbl_mlm_slot::where("slot_no", Request::input("sponsor"))->where("shop_id", $shop_id)->value("slot_id");
$placement = Tbl_mlm_slot::where("slot_no", Request::input("placement"))->where("shop_id", $shop_id)->value("slot_id");
/* POSITIONING DATA */
$slot_sponsor = $sponsor;
$slot_placement = $placement;
$slot_position = strtolower(Request::input("position"));
/* SLOT GENERATION */
$membership_package_id = Request::input("package_number");
/* JUST ADD TO SLOT IF EXISTING CUSTOMER */
if(Request::input("date_created") == "undefined")
{
$slot_date_created = date("Y-m-d h:i");
}
else
{
$slot_date_created = date("Y-m-d", strtotime(Request::input("date_created")));
}
$existing_customer = Tbl_customer::where("shop_id", $shop_id)->where("email", Request::input("email"))->first();
$list['first_name'] = Request::input("first_name");
$list['last_name'] = Request::input("last_name");
$list['email'] = Request::input("email");
$list['slot_no'] = Request::input("slot_no");
$list['password'] = Request::input("password");
$list['birthday'] = Request::input("birthday");
$list['contact'] = Request::input("contact_number");
$list['gender'] = Request::input("gender");
dd($list); <---- first run of the function, I put one here
if($existing_customer)
{
$customer_id = $existing_customer->customer_id;
}
else
{
dd($list); <--- for the second run of the function, to check what happens to my $list
$insert_customer["shop_id"] = $shop_id;
$insert_customer["first_name"] = ($list['first_name'] == "undefined" ? "John" : ucfirst($list['first_name']));
$insert_customer["last_name"] = ($list['last_name'] == "undefined" ? "Doe" : ucfirst($list['last_name']));
$insert_customer["email"] = ($list['email'] == "undefined" ? "dummy#gmail.com" : $list['email']);
$insert_customer["ismlm"] = 1;
$insert_customer["mlm_username"] = $list['slot_no'];
$insert_customer["password"] = ($list['password'] == "undefined" ? Crypt::encrypt(randomPassword()) : Crypt::encrypt($list['password']));
$insert_customer["created_date"] = $slot_date_created;
$insert_customer["b_day"] = date("Y-m-d", strtotime($list['birthday']));
$insert_customer["birthday"] = date("Y-m-d", strtotime($list['birthday']));
$insert_customer["contact"] = $list['contact'];
$insert_customer["gender"] = strtolower($list['gender']);
$customer_id = Tbl_customer::insertGetId($insert_customer);
/* Insert Customer Address */
$address_purpose[0] = "permanent";
$address_purpose[1] = "billing";
$address_purpose[2] = "shipping";
foreach ($address_purpose as $key => $value)
{
$insert_customer_address["customer_id"] = $customer_id;
$insert_customer_address["country_id"] = 420;
$insert_customer_address["customer_state"] = "";
$insert_customer_address["customer_city"] = "";
$insert_customer_address["customer_zipcode"] = "";
$insert_customer_address["customer_street"] = Request::input("address");
$insert_customer_address["purpose"] = $value;
$insert_customer_address["archived"] = 0;
$insert_customer_address["created_at"] = Carbon::now();
$insert_customer_address["updated_at"] = Carbon::now();
Tbl_customer_address::insert($insert_customer_address);
}
}
}
I can't really see where I went wrong as the values went null just because they entered that if/else statement.
First of thank you for your help.
The code piece "while (sqlite_has_more($dres))" is using sqlite2 and I need sqlite3. If there isn't a replacement for has_more is there another code I can use to still Find whether or not more rows are available?
F.Y.I. The server updated their stuff which included their sqlite and now I have to fix this last peice of code to get the schedule to populate and not give me this error.
Fatal error: Non-static method SQLite3::open() cannot be called statically in /home/server/public_html/current-list.php on line 57
$row_num = 0;
if ($dbh = SQLite3::open($sked_path))
{
$qsql = "SELECT rowid,* FROM sked ORDER BY sk_dow_num, sk_time_start, sk_time_end";
$dres = SQLite3::query($dbh, $qsql);
if (SQLite3::num_Rows($dres) > 0)
{
$last_dow = "";
$last_start = "0000";
$last_end = "0000";
while (sqlite_has_more($dres))
{
$ska = Sqlite3Result::fetchArray($dres, SQLITE3_ASSOC);
$rid = $ska['rowid'];
$dow = $ska['sk_dow_name'];
$start = $ska['sk_time_start'];
$end = $ska['sk_time_end'];
$title = preg_replace("/<br\s*\/*>/", " ", $ska['sk_show_title']);
$show_dow = strtoupper($dow);
$show_start = strtoupper(formatTimeAmPm($start));
$show_end = strtoupper(formatTimeAmPm($end));
$show_style = "";
if (stristr($title, "Encore Show"))
$show_style = " class=\"$text_style\"";
Something like ...
<?php
$dbh = new SQLite3;
if ( !$dbh->open($sked_path) ) {
trigger_error('...error handling...', E_USER_ERROR);
}
else {
$dres = $dbh->query('
SELECT
rowid,*
FROM
sked
ORDER BY
sk_dow_num, sk_time_start, sk_time_end
');
if ( !$dres ) {
trigger_error('...error handling...', E_USER_ERROR);
}
else {
$ska = $dres->fetchArray(SQLITE3_ASSOC);
if ( !$ska ) {
onNoRecords();
}
else {
do {
doSomethingWithRowData($ska);
}
while( false!=($ska=$dres->fetchArray(SQLITE3_ASSOC)) );
}
}
}
(completely untested)
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);
I have the following being extracted from a database:
Switchboard:265-7404-6,Marketing Hotline: 265-7403, B'ce: 333-6848
I want to convert it to something like this in PHP:
In the event of extension as: 265-7404-6 it only parses: 265-7404
function printdir()
{
$mysqli = new mysqli(constant("host"),constant("username"),constant("password"), constant("database"));
$storedProc = "SELECT * FROM `directory`;";
$result = $mysqli->query($storedProc);
if($mysqli->affected_rows>0)
{
while( $row = $result->fetch_assoc()) {
echo $row['telephone']; /*Formatting here*/
}
}
}
$telnumber = explode('-', $row['telephone'], 3));
echo $telnumber[0].'-'.$telnumber[1];
The extension and anything after the second value will be in $telnumber[2]
<?php
function format_number($phone){
$phone = preg_replace("#[^\d{10}\s]#",'',$phone);
if(strlen($phone)==7)
{
$area = substr($phone,0,3);
$prefix = substr($phone,3,4);
$format = $area."-".$prefix;
$phone = "$format";
return($phone);
}
if(strlen($phone) != 10) return(False);
$area = substr($phone,0,3);
$prefix = substr($phone,3,3);
$number = substr($phone,6,4);
$format = $area."-".$prefix."-".$number;
$phone = "$format";
return($phone);
}
function telephoneText($string)
{
$format_one.= '\d{10}'; //5085551234
$format_two_and_three .= '\d{3}(\.|\-)\d{3}\2\d{4}'; //508.555.1234 or 508-555-1234
$format_four .= '\(\d{3}\)\-\d{3}\-\d{4}'; //(508)-555-1234
$format_five .='\d{3}\-\d{4}'; //(508)555-1234
$format_five_seven .='\d{7}';
$string = preg_replace("~({$format_one}|{$format_two_and_three}|{$format_four}|{$format_five}|{$format_five_seven})~e", 'format_number("$1")', $string);
return $string;
}
?>
Thats is the what i was trying to achieve. Thanks guys..