I can only add one item to my cart at a time.
The previous item I add to the cart will just get replaced here is my method I use:
public function addcart(){
if(isset($this->session->userdata)){
$type = $this->session->userdata('type');
$username = $this->session->userdata('username');
$this->db->select('id_product ,price');
$query = $this->db->get('product', array('title'=> $this->input->post('title')));
$cart['product'] = $this->cart->contents();
if($query->num_rows() >0){
$row = $query->row();
$id = $row->id_product;
$cart['product'][$id] = array(
'id' => $row->id_product,
'qty' => $this->input->post('quantity'),
'price' => $row->price,
'name' => $this->input->post('title'),
//'options' => array('Size' => 'L', 'Color' => 'Red')
);
$this->cart->insert($cart['product'][$id]);
}
}
}
check what $cart['product'] = $this->cart->contents(); returns to you
if there is a problem there it probably reset your array of products and then you insert the second product and get a total cart of one product
I think you are using $this->db->get() badly, you are searching product by string, which is not "correct". What happens if you have same (title) identical products? You get the first one/second one?
please adjust your table as follows
id, title, price... 'custom fields', active
make id as autoincrement, active as boolean (so you can later turn on/off product)
Make your method accept parameters:
public function addcart( $id = FALSE ) {
if ($id === FALSE || !is_numeric($id)) {
//wrong ID do nothing or throw alert or inform user about it
redirect('');
}
if(isset($this->session->userdata)) {
$type = $this->session->userdata('type');
$username = $this->session->userdata('username');
$this->db->select('id_product ,price');
$query = $this->db->get('product', array('id' => $id, 'active' => '1'));
$cart['product'] = $this->cart->contents();
if($query->num_rows() >0) {
$row = $query->row();
$id = $row->id_product;
$cart['product'][$id] = array(
'id' => $row->id_product,
'qty' => $this->input->post('quantity'),
'price' => $row->price,
'name' => $this->input->post('title'),
//'options' => array('Size' => 'L', 'Color' => 'Red')
);
$this->cart->insert($cart['product'][$id]);
}
}
}
Happy cod(e)igniting.
Related
I have this code here:
$userid = Secure($_POST[ 'username' ]);
$user = $db->where('username', $userid)->getOne('users',array('id','web_device_id','is_pro'));
$is_user_matches = $db->where('user_id', $user['id'])->where('like_userid', self::ActiveUser()->id)->getOne('likes', array('id'));
$id = $db->where('user_id', self::ActiveUser()->id)->where('like_userid', $user['id'])->getValue('likes', 'id');
$saved = false;
if ($id > 0) {
$saved = $db->where('id', $id)->update('likes', array(
'user_id' => self::ActiveUser()->id,
'like_userid' => $user['id'],
'is_like' => 1,
'is_dislike' => 0,
'created_at' => date('Y-m-d H:i:s')
));
} else {
if(isUserLiked($user['id']) === false) {
$saved = $db->insert('likes', array(
'user_id' => self::ActiveUser()->id,
'like_userid' => $user['id'],
'is_like' => 1,
'is_dislike' => 0,
'created_at' => date('Y-m-d H:i:s')
));
}
}
These are the actions that occur when a user presses the LIKE button!
Now, my question is. How can I add in addition to these codes, an UPDATE for a table in mysql?
I would like that when a user gives a Like to a person, he will count automatically.
mysql_query("
UPDATE users
SET likes = likes + 1
WHERE id = '".$user['id']."'
");
I tried to add this code but I couldn't. I don't think I'm adding it where it should be. Can you show me an example please?
I am having a problem passing a variable to be saved as INT in MySQL. The closest thing I could find to my issue is this question but I have already verified that I am not using single and double quotes. When I print_r($this->session->userdata('subdomain')) I see the correct subdomain id on my screen (in this case 10), but when I try passing this using $params it always save subdomain_id as 0 and I can not figure out why.
Here is Project_assignees_model:
function add_prefix_project_assignees($params)
{
$this->db->insert('prefix_project_assignees',$params);
return $this->db->insert_id();
}
Here is my Project controller (Specifically it is the $assignees array):
function edit($entry_id)
{
$this->load->library('form_validation');
$this->form_validation->set_rules('client_id','Client Id','required|integer');
$this->form_validation->set_rules('title','Project Title','required|max_length[255]');
$this->form_validation->set_rules('project_status','Project Status','required');
$this->form_validation->set_rules('project_details','Project Details','required');
$this->form_validation->set_rules('project_estimated_hours','Project Estimated Hours','required|max_length[255]');
$this->form_validation->set_rules('end','Project Deadline','required');
if($this->form_validation->run())
{
date_default_timezone_set("America/New_York");
$date = date("Y-m-d h:i:sa");
$params = array(
'subdomain_id' => $this->session->userdata('subdomain'),
'client_id' => $this->input->post('client_id'),
'title' => $this->input->post('title'),
'project_status' => $this->input->post('project_status'),
'project_details' => $this->input->post('project_details'),
'project_last_updated' => $date,
'project_estimated_hours' => $this->input->post('project_estimated_hours'),
'start' => $this->input->post('start'),
'end' => $this->input->post('end'),
'owner_id' => get_current_user_id(),
);
$prefix_projects_id = $this->Project_model->update_prefix_projects($entry_id,$params);
$assignees = array(
'subdomain_id' => $this->session->userdata('subdomain'),
'project_id' => $entry_id,
'user_id' => $this->input->post('assignee'),
);
$this->load->model('Project_assignee_model');
$insertAssignees = array();
for ($i = 0; $i < count($assignees['user_id']); $i++)
{
//Get user_id from ID
$userID = $assignees['user_id'][$i];
$insertAssignees[$i] = array('project_id' => $entry_id, 'user_id' => $assignees['user_id'][$i]); // $insert is ready for insert_batch
$prefix_assignees = $this->Project_assignee_model->add_prefix_project_assignees($insertAssignees[$i]);
}
//redirect('project/index');
}
else
{
$this->load->model('Client_model');
$data['prefix_clients'] = $this->Client_model->get_all_prefix_clients();
$data['prefix_projects'] = $this->Project_model->get_prefix_projects($entry_id);
$data['prefix_users'] = $this->aauth->list_users();
$this->load->model('Project_assignee_model');
$data['prefix_assignees'] = $this->Project_assignee_model->get_prefix_project_assignees($entry_id);
$this->load->view('project/edit',$data);
}
}
Why does print_r show the correct subdomain_id but when it is saved to database it saves as 0?
*******UPDATE*******
Just for reference, this works:
$assignees = array(
'subdomain_id' => 10,
'project_id' => $entry_id,
'user_id' => $this->input->post('assignee'),
);
But this does not (Even though printing the userdata for subdomain gives me 10):
$assignees = array(
'subdomain_id' => $this->session->userdata('subdomain'),
'project_id' => $entry_id,
'user_id' => $this->input->post('assignee'),
);
Sometimes I guess it just takes writing it out for others before I realize my problem. When I loop through each assignee to add them to the table I realized I was not passing the subdomain_id with it.
I had this:
$insertAssignees[$i] = array('project_id' => $entry_id, 'user_id' => $assignees['user_id'][$i]); // $insert is ready for insert_batch
Needed to be changed to have subdomain_id included
$insertAssignees[$i] = array('subdomain_id' => $this->session->userdata('subdomain'), 'project_id' => $entry_id, 'user_id' => $assignees['user_id'][$i]); // $insert is ready for insert_batch
I am working on populating the database tables. The table have fields which some of them are enum.
Consider a user which have a field status , whose values can be active, inactive etc. Assume we can modify the configuration values and running the script the data can be populated accordingly.
Let us represent the user table whose status field as
'status' => array(
'active' => 3,
'inactive',
'deleted',
),
In this case assume we need to create 3 users with status , active. 1 user with status inactive and 1 with deleted.
The table may be having more enum fields. So the config can expand. Depending on the configuration and fields the values will be multiples.
Consider the below example.
Eg :
$config = array(
'table1name' => array(
'field1' => array(
'active' => 3,
'inactive',
'deleted',
),
'field2' => array(
'admin',
'user',
'editor'
),
....,
'more-fields' => array(
'more-values',
)
),
'table2name' => array(
'field1' => array(
'active',
'inactive',
'deleted',
),
)
);
In this case there need to populate table1 whose field field1 with active, inactive, deleted and roles with admin, user, editor etc. ( The active, inactive etc are provided just for example. It can be just values. )
The idea is to generate more users depending on the count if any provided.
Eg :
'status' => array(
'active' => 10,
'inactive' => 2,
'deleted' => 3,
),
'roles' => array(
'admin' => 2,
'user',
'editor'
)
....,
'more-fields' => array(
'more-values',
)
So that there will be
10 * 4 => active users (10 * 2 active admin / 10 active user, 10 active editor ) +
2 * 4 => inactive users ( 2 inactive admin , 1 user, 1 editor ) +
3 * 4 => deleted users in total.
I am struggling to build the algorithm for the same.
array(
'status' => array(
'active' => 10,
'inactive' => 2,
'deleted' => 3,
),
'roles' => array(
'admin' => 2,
'user',
'editor'
),
....,
'more-fields' => array(
'more-values',
)
)
// In this example you can see we have not covered the fields of the table when they are more than 1 on save.It looks we need to build the array with values first.
foreach ($config as $table => $fields) {
foreach ($fields as $field => $values ) {
foreach ($values as $key => $statusCount) {
if (is_string($key)) {
$model = new User();
$model->$field = $key;
$model->another = 'value';
$model->save();
} else {
for ($i = 0; $i< $statusCount; $i++) {
$model = new User();
$model->$field = $key;
$model->another = 'value';
$model->save();
}
}
}
}
}
UPDATE :
Changes made according to #the-fourth-bird answer https://stackoverflow.com/a/33354032/487878
Problem is it only look for 2 fields, the fields can be 1 or n.
Are you looking for a setup like this? (Not sure what the fields for the User can be, I used 'role' and 'admin' in this example.)
$fields = array(
'status' => array(
'active' => 10,
'inactive' => 2,
'deleted' => 3,
),
'roles' => array(
'admin',
'user',
'editor'
)
);
$roles = $fields['roles'];
$statuses = $fields['status'];
foreach ($roles as $role) {
foreach ($statuses as $status => $statusCount) {
for ($i = 0; $i< $statusCount; $i++) {
$model = new User();
$model->role = $role;
$model->status = $status;
}
}
}
// Update with dynamic properties
<?php
class table1name {
public function save() {}
}
class table2name {
public function save() {}
}
$config = array(
'table1name' => array(
'field1' => array(
'active' => 3,
'inactive',
'deleted',
),
'field2' => array(
'admin',
'user' => 2,
'editor'
),
'more-fields' => array(
'more-values' => 2,
),
'color' => array(
'blue' => 2,
'red'
),
),
'table2name' => array(
'field1' => array(
'active',
'inactive',
'deleted',
),
)
);
// Adjust data structure
// If the key is a string, turn the key into values for the given multiplier in the same array.
// Then unset the key.
foreach ($config as $table => $fields) {
foreach ($fields as $field => $values ) {
foreach ($values as $key => $statusCount) {
if (is_string($key)) {
for ($i = 0; $i< $statusCount; $i++) {
$config[$table][$field][] = $key;
}
unset($config[$table][$field][(string)$key]);
}
}
}
}
$cartesians = [];
// If you want all the possible combinations for for example the 'table1name', you need a cartesian product. Used the function from this page:
//http://stackoverflow.com/questions/6311779/finding-cartesian-product-with-php-associative-arrays
function cartesian($input) {
$input = array_filter($input);
$result = array(array());
foreach ($input as $key => $values) {
$append = array();
foreach($result as $product) {
foreach($values as $item) {
$product[$key] = $item;
$append[] = $product;
}
}
$result = $append;
}
return $result;
}
// Create the cartesian products for all the keys in the $config array.
foreach ($config as $key => $tables) {
$cartesians[$key] = cartesian($tables);
}
// Loop all the objects created by the cartesian function.
foreach ($cartesians as $objectName => $cartesian) {
foreach($cartesian as $key => $value) {
$model = new $objectName();
$model->$key = $value;
$model->save();
}
}
I have created a component in joomla 2.5 that creates a new article and adds that article to a menu item.
Creating the article is working fine, but I am having some trouble with creating the menu item.
I have the following code:
//add the article to a menu item
$menuTable = JTable::getInstance('Menu', 'JTable', array());
$menuData = array(
'menutype' => 'client-pages',
'title' => $data[name],
'type' => 'component',
'component_id' => 22,
'link' => 'index.php?option=com_content&view=article&id='.$resultID,
'language' => '*',
'published' => 1,
'parent_id' => '1',
'level' => 1,
);
// Bind data
if (!$menuTable->bind($menuData))
{
$this->setError($menuTable->getError());
return false;
}
// Check the data.
if (!$menuTable->check())
{
$this->setError($menuTable->getError());
return false;
}
// Store the data.
if (!$menuTable->store())
{
$this->setError($menuTable->getError());
return false;
}
The error seems to be with setting the parent_id and level. On debugging libraries/joomla/database/tablenested.php sets the parent_id and level to 0. This caused the following error on my administrator page:
Warning: str_repeat() [function.str-repeat]: Second argument has to be greater than or equal to 0 in /Applications/MAMP/htdocs/joomla_2_5/administrator/components/com_menus/views/items/tmpl/default.php on line 129
Try using JTableNested::setLocation($referenceId, $position = 'after'):
$table->setLocation($parent_id, 'last-child');
I also think that you need to rebuild the path:
// Rebuild the tree path.
if (!$table->rebuildPath($table->id)) {
$this->setError($table->getError());
return false;
}
If it still doesn't work, try to find out what MenusModelItem::save does that you don't.
$table->setLocation($parent_id, 'last-child');
is all that is needed to ensure that left/right values are created correctly for the new menu item. There is no need to rebuild the path as this is now handled by JTableMenu's store method.
Additionally, the convenience method "save" can be used to bind, check and store the menu item:
$menuItem = array(
'menutype' => 'client-pages',
'title' => $data[name],
'type' => 'component',
'component_id' => 22,
'link' => 'index.php?option=com_content&view=article&id='.$resultID,
'language' => '*',
'published' => 1,
'parent_id' => $parent_id,
'level' => 1,
);
$menuTable = JTable::getInstance('Menu', 'JTable', array());
$menuTable->setLocation($parent_id, 'last-child');
if (!$menuTable->save($menuItem)) {
throw new Exception($menuTable->getError());
return false;
}
Somehow $menutable does not update parent_id and level in database table so you have to manually update those two fields by joomla query.
$menuTable = JTable::getInstance('Menu', 'JTable', array());
$menuData = array(
'menutype' => 'client-pages',
'title' => $data[name],
'type' => 'component',
'component_id' => 22,
'link' => 'index.php?option=com_content&view=article&id='.$resultID,
'language' => '*',
'published' => 1,
'parent_id' => '1',
'level' => 1,
);
// Bind data
if (!$menuTable->bind($menuData))
{
$this->setError($menuTable->getError());
return false;
}
// Check the data.
if (!$menuTable->check())
{
$this->setError($menuTable->getError());
return false;
}
// Store the data.
if (!$menuTable->store())
{
$this->setError($menuTable->getError());
return false;
}
$db = $this->getDbo();
$qry = "UPDATE `#__menu` SET `parent_id` = 1 , `level` = 1 WHERE `id` = ".$menuTable->id;
$db->setQuery($qry);
$db->query();
This code worked for me
JTable::addIncludePath(JPATH_ADMINISTRATOR.'/components/com_menus/tables/');
$menuTable =& JTable::getInstance('menu', 'menusTable');
$menuData = array(
'menutype' => 'client-pages',
'title' => 'mytrialmenu',
'type' => 'component',
'component_id' => 22,
'link' => 'index.php?option=index.php? option='com_content&view=article&id='.$resultID,
'language' => '*',
'published' => 1,
'parent_id' => 'choose some parent',
'level' => 1,
);
// Bind data
if (!$row->bind($menuData))
{
$this->setError($menuTable->getError());
return false;
}
// Check the data.
if (!$row->check())
{
$this->setError($menuTable->getError());
return false;
}
// Store the data.
if (!$row->store())
{
$this->setError($menuTable->getError());
return false;
}
I think the reason is menusTable extends JnestedTable which is required for manipulating lft and rgt fields in the menu table
I have an array in this form:
$data = array(
array(
'id' => '1',
'bar' => 'foo',
'page' => 'front',
),
array(
'id' => 'bar',
'bar' => 'foo',
'page' => 'front',
),
array(
'id' => 'different,
'bar' => 'bar',
'page' => 'back',
),
array(
'id' => 'another',
'title' => __("Custom CSS",'solidstyle_admin'),
'foo' => 'bar',
'page' => 'back',
),
);
And I want to list all ids grouped by pages and saved as variables, so if the above array is an input then output will look just like this one:
$front = array('1','bar');
$back = array('different','another');
//$data['page'] = array($id1, $id2, (...));
I was trying to do that using foreach and this is how it starts:
function my_output() {
foreach($data as $something) {
$id = $something['id'];
$page = $something['page'];
}
return $output;
}
I was trying multiple foreach loops, and the best result I got was:
front = 1
front = bar
back = different
back = another
But I have absolutely no idea how to achieve what I want to do, I don't want anyone to do my job, just any hints? Keep in mind I'm a bit new to PHP and I don't know too much about arrays.
Thank you!
Sounds like you want:
$ids = array();
foreach ($data as $page) {
$pageName = $page['page'];
// create an empty array for your IDs
if (!isset($ids[$pageName])) {
$ids[$pageName] = array();
}
// add to the array of IDs
$ids[$pageName][] = $page['id'];
}
var_dump($ids); // array('front' => array('1', 'bar'), ...
Stick with the loop idea and do a conditional check.
function my_output() {
$front = array();
$back = array();
foreach($data as $something) {
$id = $something['id'];
$page = $something['page'];
if ($page === 'front') {
$front[] = $id;
} else if ($page === 'back') {
$back[] = $id;
}
}
// Not sure what you want to return here, but you could return an array of pages
$output = array('front' => $front, 'back' => $back);
return $output;
}
This will return something similar to:
$output = array(
'front' => array(
0 => '1',
1 => 'bar',
),
'back' => array(
0 => 'something',
1 => 'another',
)
)
Edit: Keep in mind that my answer only accounts for the two pages you listed in your answer. If you have more pages you can also use what cbuckley's answer showed.