sql updating whole data in database - php

I have written code to add and update users and also I want to add and update categories they can work in. The added users will go in users table and the categories they can access goes in the category_permitted table. I have the following code for adding and updating tables:
if ($user_info) {
if ($act == "add") {
if ($user_info) {
$array = array(
'user_id' => $user_info,
'category_id' => $temp['cat_access']
);
$category_permitted->addCategoryAccess($array);
}
} else {
if ($user_info) {
$array = array(
'user_id' => $id,
'category_id' => $temp['cat_access']
);
$deleteold = $category_permitted->deleteCategoryAccess($id);
$category_permitted->addCategoryAccess($array);
}
}
}
This my function to add and update category access:
public function addCategoryAccess($data, $is_die = false){
return $this->insert($data, $is_die);
}
public function updateCategoryAccess($data, $id, $is_die = false){
$args = array(
'where' => array('user_id' => $id),
);
return $this->update($data, $args, $is_die);
}
And this is the data in database table .
My update function is updating all data of the column category_id with the number being added while updating category access for the user.
I want to leave 2 and 3 as it is and add another category id which is 1 but after running the update code it updates the data like this. Do I have to add another condition to WHERE CLAUSE to get the expected output?

To update only one row you need an unique identifier for that row.
If the column id is the primary key, you can use that column to update only the corresponding row.
$args = array(
'where' => array('id' => $category_permitted_id),
);
As an alternative, if you know which category is changing, and the relation (user_id,category_id) is unique, you can add the changing category to the where.
$args = array(
'where' => array(
'user_id' => $user_id,
'category_id' => $category_id
),
);
Please note that i don't know your Database abstraction layer and i'm implying that you can simply add another entry in the array to put conditions in 'AND', this could be wrong in your case.
Managing relationships this way takes a bit of effort, and in my opinion is not worth it.
If you are able to modify the application logic, i suggest you to switch to using only insert/delete, like so:
Add a permitted category: Just add it creating a new record with insert
Remove a permitted category: Remove it trough a delete function
Change a permitted category to another: Delete the one that is changing and add the new one

Doing this in my code worked for me. I called the function $deleteold = $category_permitted->deleteCategoryAccess($id); just before the for loop to avoid deleting the previous data being deleted in every iteration.
if ($user_info) {
$cat_access = (isset($_POST['cat_access']) && !empty($_POST['cat_access'])) ? ($_POST['cat_access']) : $_SESSION['cat_access'];
$value = array();
if (!empty( $cat_access ) && is_array( $cat_access ) ) {
foreach( $cat_access as $key => $item ) {
$value[] = filter_var( $item, FILTER_SANITIZE_NUMBER_INT );
}
}
$categoryData = $value;
$temp = array();
if ($categoryData) {
$count = count($categoryData);
if ($count > 0) {
$deleteold = $category_permitted->deleteCategoryAccess($id);
for($i=0; $i<$count; $i++){
$temp =array(
'cat_access' => $categoryData[$i]
);
if ($act == "add") {
if ($user_info) {
$array = array(
'user_id' => $user_info,
'category_id' => $temp['cat_access']
);
$category_permitted->addCategoryAccess($array);
}
} else {
if ($user_info) {
$array = array(
'user_id' => $id,
'category_id' => $temp['cat_access']
);
$category_permitted->addCategoryAccess($array);
}
}
}
}
}
}

Related

How to fetch the key of an array that contains a specific substring?

This is my array:-
$ header_menu = array(
['category'] => array(
'id' => 1,
'title' => 'Test Apple',
'slug' => 'category'
),
['how-to-do'] => array(
'id' => 1,
'title' => 'How to do',
'slug' => 'how-to-do'
)
)
The array is formed dynamically based on the data saved in the table. Due to that, sometimes the key can be 'category', sometimes it can be 'categories', based on what the admin has saved in the DB.
I need to fetch the key which has the substring 'categor', because this sequence of alphabets is present both in 'category' & 'categories'. By the following code, I can check if the 'categor' substring is present in any of the key or not:-
if (preg_grep('/^categor/', array_keys($header_menu)))
{
}
One way is to run a loop like this:-
foreach($header_menu as $key => $row)
{
if(strpos($key, 'categor') !== false)
{
$catKey = $key;
}
}
However, I don't want to run a loop. Is there any other way to fetch the matching key?
If you know that you have only two options category/categories , you can check if one of this fields exists in array:
if (isset($header_menu['category'])) {
$key = 'category';
} elseif (isset($header_menu['categories'])) {
$key = 'categories';
}
switch variation which allows many options:
switch (true) {
case isset($header_menu['category']):
$key = 'category';
break;
case isset($header_menu['categories']):
$key = 'categories';
break;
}
You can use preg_grep if you do not want to loop through with array_keys() to get every key of your array and find all key matching given pattern.
$matchingKeys = array_keys($header_menu);
$matchingKeys = preg_grep('/'.'categor'.'\.\d/i', $matchingKeys);

How do i grab all users with their meta data?

I am building out a website that has about 7500 users. What i wanted was to grab all of my users and their meta data and return it to me through a rest api call that I built myself. Currently I am having a hard time returning all of our users meta data and not just one single user's meta data.
I have already built out the custom endpoint and can successfully return users
add_action( 'rest_api_init', 'my_register_route' );
function my_register_route() {
register_rest_route( 'map/v1', 'test', array(
'methods' => 'GET',
'callback' => 'custom_phrase',
)
);
}
function custom_phrase() {
$users = get_users( array( 'fields' => array( 'ID' ) ) );
foreach($users as $user_id){
return (get_user_meta ( $user_id->ID));
}
}
I expect that the endpoint will return all of my users meta_data & user_data together instead of just the final user in the index.
UPDATE: I feel like I am almost there but each index in the array comes back with the exact same information. Not to mention i am somehow unsuccessful at grabbing the Active_Memberships values which is an array before it gets to me.
function custom_phrase($request_data) {
$parameters = $request_data->get_params();
$state = $parameters['state'];
$users = get_users(array(
'meta_key' => 'active state membership',
'meta_value' => $state,
));
$stack = array();
foreach($users as $user_id) {
$user_meta = get_user_meta ($user_id -> ID);
$obj->display_name = $user_id -> display_name;
$obj->memberships = $user_meta -> active_memberships;
array_push($stack, $obj);
}
return $stack;
}
You use return in your loop, so it will return at the first iteration.
Just create a variable to store meta :
function custom_phrase() {
$users = get_users( array( 'fields' => array( 'ID' ) ) );
$data = [];
foreach($users as $user_id){
$data []= get_user_meta ( $user_id->ID);
}
return $data;
}

How to fix "Call to a member function execute() on string" on my function

I'm modifying a Wordpress API witch is currently getting learnpress course and lessons infos from the database using leanrpress functions only. I need to modify the API to get the scores from the newly implemented plugin h5p, therefor i need to make a new function to access the Database and get the scores from the right table, then put then into an array with the according lesson. The array here is only an exemple i'm using to see if i can get the datas, ut i'm stuck with the error
"Call to a member function execute() on string"
when i try and run it on postman. Could someone lighten me on this issue please ?
function ilp_api_get_progress_by_mail($data){
$mail=$_GET['mail']; //$data->get_param["mail"];
$course_id=$_GET['course'];
global $wpdb;
$user=get_user_by("email",$mail);
if($user !== false){
$lp_user=learn_press_get_user( $user->ID );
if($course_id==NULL){
$all_courses=ilp_api_get_all_courses($data);
}else{
$all_courses=array('courses' => array(array('id' => intval($course_id))));
}
$progress=array();
$i=0;
if($all_courses!=NULL && $all_courses['courses']!=null){
foreach($all_courses['courses'] as $course){
if($lp_user->has_enrolled_course($course['id'])){
$lp_course=learn_press_get_course( $course['id'] );
$course_data = $lp_user->get_course_data($course['id']);
$course_results = $course_data->get_results( false );
$progress[$i]=array(
'id' => $course['id'],
'name' => $lp_course->get_title(), //$course['name'],
'condition' => $lp_course->get_passing_condition(),
'completed' => $course_results['completed_items'],
'total' => $course_results['count_items'],
'progress' => absint( $course_results['completed_items'] / $course_results['count_items'] * 100 ),
'permalink' => $lp_course->get_permalink(),
);
$i++;
}
}
}
$result = array(
'userfound' => true,
'user_id' => $user->ID,
'connect' => get_h5p_grades(),
'courses_progress' => $progress,
'course_id' => $all_courses,
);
function get_h5p_grades(){
global $wpdb;
$ID = 1;
$ID_use = 1;
$result = $wpdb->prepare('SELECT score FROM mci_h5p_results WHERE id = %d AND user_id = %d', $ID, $ID_use);
$result->execute();
$donnees = $result->fetch();
return $donnees;
}

How to Update Two table Data one after other In codeigniter?

how to update plan with vendor_plan_task_status_mapp table.
the model for plan update is
public function updatePlanData(){
$planId = $this->input->post('plan_id');
$data = array(
'plan_title' => $this->input->post('plan_title'),
'plan_price' => $this->input->post('plan_price'),
'plan_desc' => $this->input->post('plan_desc')
);
$this->db->where('plan_id', $planId);
$this->db->update('tbl_plan', $data);
$this->db->where('plan_id',$planId);
$this->db->delete('plan_task_mapping');
foreach ($this->input->post('task_id') as $key => $value)
{
$data2 = array(
'plan_id' => $planId,
'task_id' => $value
);
// echo "Index {$key}'s value is {$value}.";
$this->db->insert('plan_task_mapping', $data2);
}
//-------- HEAR I NEED A CODE TO UPDATE The V_T_S_M table-----------
}
after 1st table update i want to update the data in vendr_task_status_mapping table?????
IN THIS ANSWER YOU GET AN ERROR IF YOU CHANGE THE PLAN BUT USING THIS CODE YOU HAVE TO SIMPLY EDIT AND UPDATE IT ANGIN AND THIS MODEL IS CREATE A NEW ID FOR YOUR TASK AND INSERT IT AGAIN.
public function vendorUpdateModel($data)
{
$vendor_id = $this->input->post('vendor_id');
$data = array(
'category_id' => $this->input->post('category_id'),
'plan_id' => $this->input->post('plan_id'),
'city_id' => $this->input->post('city_id'),
'business_name' => $this->input->post('business_name'),
'owner_name' => $this->input->post('owner_name'),
'contact_no1' => $this->input->post('contact_no1'),
'contact_no2' => $this->input->post('contact_no2'),
'vendor_email' => $this->input->post('vendor_email'),
'subscription_date' => $this->input->post('subscription_date'),
'vendor_description' => $this->input->post('vendor_description'),
'vendor_address' => $this->input->post('vendor_address')
);
$this->db->where('vendor_id', $vendor_id);
$this->db->update('vendor',$data);
$this->db->where('vendor_id',$vendor_id);
$this->db->delete('vendor_task_status_mapping');
$this->db->select('task_mapp_id');
$this->db->where('plan_id',$this->input->post('plan_id'));
$query = $this->db->get('plan_task_mapping');
foreach($query->result() as $row)
{
$data2 = array(
'task_mapp_id' => $row->task_mapp_id,
'vendor_id' => $vendor_id,
'task_status' => '0'
);
$this->db->insert('vendor_task_status_mapping', $data2);
}
return;
}
If you added one field in plan_task_mapping table for add unique number then... As you mention your code:
$unique=array();
foreach ($this->input->post('task_id') as $key => $value)
{
$no=rand(0, 15);
$data2 = array(
'unique_no'=>$no,
'plan_id' => $planId,
'task_id' => $value
);
$unique[] = $no; //store no in array to use it.
// echo "Index {$key}'s value is {$value}.";
$this->db->insert('plan_task_mapping', $data2);
}
Before deleting plan_task_mapping table data. fetch that data.
function select()
{
$this->db->where('plan_id',$planId);
$Q = $this->db->get('plan_task_mapping');
if($Q->num_rows() > 0)
{
foreach ($Q->result_array() as $row)
{
$data[] = $row;
}
}
$Q->free_result();
return $data;
}
Then delete the data as you mention in you code:
$this->db->where('plan_id',$planId);
$this->db->delete('plan_task_mapping');
Then delete that old data from VTSM table:
$this->db->where('vendor_plan_task_mapping_id',$data[0]['id']); //this data[0]['id'] come form select(). change field name if required.
$this->db->delete('VTSM');
Here fetch that new inserted data by that unique no: //which we stored it in array.
foreach($unique as $u_no)
{
$this->db->where('unique_no',$u_no);
$Q = $this->db->get('plan_task_mapping');
if($Q->num_rows() > 0)
{
foreach ($Q->result_array() as $row1)
{
$plan[] = $row1;
}
}
$Q->free_result();
return $plan;
}
In above code we have fetched that new inserted data to get their id to insert status.
Now inserting status:
foreach($plan as $a)
{
$Sdata=array(
"plan_task_mapping_id"=>$a['id'], //this is new id change name if required
"status"="your new status");
$this->db->insert('VTSM',$Sdata);
}
Use $this->db->insert_batch(); instead of inserting in foreach loop.
Check at this link how to use it.

Codeigniter update cart if product exists

How to update an item quantity if the product already exists in shopping cart?
Here's my add to cart function:
public function add() {
$product= $this->products_model->listProduct($this->input->post('id_product'));
$data = array(
'id' => $this->input->post('id_product'),
'qty' => $this->input->post('qty'),
'price' => $product->price,
'name' => $product->title );
$this->cart->insert($data);
redirect('product/'.$product->id.'/'.url_title($product->title, 'dash', TRUE));
}
With this function, if the product exists in the cart, let's say with quantity of 8, if i add the same product with quantity of 1 it'll be 1 and not 9.
Thanks in advance.
#AFRC
you can try
public function add() {
$flag = TRUE;
$dataTmp = $this->cart->contents();
foreach ($dataTmp as $item) {
if ($item['id'] == 'sku_123ABC') {
echo "Found Id so updatig quantity";
$qtyn = $item['qty'] + 1;
$this->update($item['rowid'], $qtyn);
$flag = FALSE;
break;
}
}
if ($flag) {
$data = array(
'id' => 'sku_123ABC',
'qty' => 1,
'price' => 39.95,
'name' => 'T-Shirt',
);
$this->cart->insert($data);
echo "Inserting as not found in the cart";
}
echo "Add1 called";
}
I don't see where $produto is defined, shouldn't it be, instead, $product->price and $product->title, respectively?
According to the docs :
Important: The first four array
indexes above (id, qty, price, and
name) are required. If you omit any of
them the data will not be saved to the
cart.
Be sure to check if they're acqually set (maybe look for spelling errors, like, I shoot in the dark, 'qtd' instead of 'qty', or something like that).
Moreover, if you want to UPDATE a product already present, you need to use $this->cart->update() instead of $this->cart->insert()
Just check with this if you have options
$rowid == md5($items['id'].implode('', $items['options']));
if not
$rowid == md5($items['id']);
use this code for add to cart
if (count($this->cart->contents())>0){
foreach ($this->cart->contents() as $item){
if ($item['id']==$product->id){
$data = array('rowid'=>$item['rowid'],'qty'=>++$item['qty']);
$this->cart->update($data);
}else{
$data = array('id'=>$product->id,'qty'=>1,'price'=>$product->price,'name'=>$product->id,'options'=>array('image'=>$product->thumb,'product_name'=>$product->title));
$this->cart->insert($data);
}
}
I used AFRC's answer to create the code below, it may be helpful. Thanks for your reply it really helped me! You can call the cart function below if there is an id present matching in your cart update will occur, otherwise insert will. It'll also display the cart view reguardless of insert, update, or just display. Please note i have a separate function get_specific_craft that is being used to get the slug items data (such as price and name).
public function cart($slug = "")
{
if($slug != "")
{
$craft = $this->crafts_model->get_specific_craft($slug);
$flag = TRUE;
foreach ($this->cart->contents() as $item)
{
if ($item['id'] == $slug)
{
$qtyn = $item['qty'] + 1;
$dat = array(
'rowid' => $item['rowid'],
'qty' => $qtyn
);
$this->cart->update($dat);
$flag = FALSE;
break;
}
}
if ($flag)
{
$crt = array(
'id' => $craft['id'],
'qty' => 1,
'price' => $craft['price'],
'name' => $craft['name']
//'options' => array('Size' => 'L', 'Color' => 'Red')
);
$this->cart->insert($crt);
}
}
$this->load->view('cart' , $this->data);
}

Categories