I run this code and I do not update
$sql="DATEDIFF(fecha_recepcion,now())";
$data=array('dias_restantes'=>$sql);
$this->db->where('estado',1);
$this->db->update('factura',$data);
I want to do something like
UPDATE `factura` SET `dias_restantes` = DATEDIFF(fecha_recepcion,now()) WHERE `estado` = 1
I want to do with Active Record of CodeIgniter.
<?php
$estado_id = 1;
$data = array(
'dias_restantes' => 'DATEDIFF(fecha_recepcion,now())'
);
$this->db->where('estado', $estado_id);
$this->db->update('factura', $data);
Si quieres ver los errores, utiliza. $this->db->_error_message(); después de $this->db->update().
Te invito a que revises la página oficial.
http://ellislab.com/codeigniter/user-guide/database/active_record.html
$this->db->query("UPDATE `factura` SET `dias_restantes` = DATEDIFF(fecha_recepcion,now()) WHERE `estado` = 1 ");
Related
I have an external paiement application service who take care about the paiements from my shopping application .
I have a form method Post to the service to send the data and the service valide the payment transaction .
<form method="POST" action="https://paiement.systempay.fr/vads-payment/">
...
<input type="submit" name="payer" value="Payer"/></form>
</form>
I would like to post also a request method from my payment controller to update my items who was paid
here my controller wish i would like to be run when the user click on "payer" also
public function postCheckoutCreditCard(Request $request)
{
if(!Session::has('Cart')){
return view('shop.panier');
}
$oldCart = Session::get('Cart') ;
$cart = new Cart($oldCart);
$items = $cart->items;
if(Input::get('payer')) {
// on inject le nouveau statut de la licence
foreach ($items as $item) {
$item['item']->statut_licence_id = LicenceStatut::where('id', '4')->firstOrFail()->id;
$item['item']->valid_licence_id = LicenceValid::where('id', '1')->firstOrFail()->id;
$item['item']->save();
}
$order = new Order;
$prefix = 'F';
$date = Carbon::now();
$saison = Saison::where('dt_deb', '<', $date)->where('dt_fin', '>', $date)->value('lb_saison');
$saison_deb = substr($saison, 2, 2);
$saison_fin = substr($saison, -2);
$num_facture_exist = true;
while ($num_facture_exist) {
$num_facture = $prefix . $saison_deb . $saison_fin . substr(uniqid(rand(), true), 4, 4);
if (!Order::where('num_facture', '=', $num_facture)->exists()) {
$order->num_facture = $num_facture;
$num_facture_exist = false;
}
}
$order->structure_id = Structure::where(['id' => Auth::user()->structure->id])->firstOrFail()->id;
$order->cart = serialize($cart);
$order->date_achat = Carbon::now();
$order->payment_method = 'Carte de Crédit';
$order->etat_paiement = 'Facture Réglée';
$order->save();
Auth::user()->notify(new InvoicePaid($order));
$federation = Structure::where('id', '1')->first();
Mail::to($federation->adresse_email_structure)->send(new NouvelleCommande($order));
Session::forget('Cart');
return redirect('home')->with('status', "Votre paiement à été effectué avec sucess , votre numéro de facture : . $order->num_facture est disponible dans la rubrique Mes cotisation ");
}
}
I'm not sure how to do this . someone could help me ? thanks in advance
I would change the form action to your Controller and then use Guzzle to call the external route. Check here about Guzzle (http://docs.guzzlephp.org/en/latest/quickstart.html#post-form-requests).
Call something like this in your Controller:
$response = $client->request('POST', 'https://paiement.systempay.fr/vads-payment/', [
'form_params' => [
'field_name' => 'abc',
]
]);
Then check the response and return something based on it.
i have already one Ajax form on my wordpress website. Now, i need a second one. So i duplicate the function in Function.php. But it does'nt work.
The first form is contact. The second one is inscription. The first one work great.
But for the second one, nothing happen when i try to send...
Here my code.
add_action( 'wp_ajax_contact', '_ajax_contact' );
add_action( 'wp_ajax_nopriv_contact', '_ajax_contact' );
function _ajax_contact() {
/*-----------------------------------------------------------------------------------*/
/* On vérifie le nonce de sécurité
/*-----------------------------------------------------------------------------------*/
check_ajax_referer( 'ajax_contact_nonce', 'security' );
/*-----------------------------------------------------------------------------------*/
/* Protection des variables
/*-----------------------------------------------------------------------------------*/
$subject = wp_strip_all_tags( $_POST['subject'] ); // Sujet du message
$name = wp_strip_all_tags( $_POST['name'] ); // Nom de l'expéditeur
$sender = sanitize_email( $_POST['email'] ); // Adresse e-mail de l'expéditeur
$message = nl2br( stripslashes( wp_kses( $_POST['message'], $GLOBALS['allowedtags'] ) ) );
/*-----------------------------------------------------------------------------------*/
/* Gestion des headers
/*-----------------------------------------------------------------------------------*/
$headers = array();
$headers[] = 'FROM : ' . $name . ' <' . $sender .'>' . "\r\n";
/*-----------------------------------------------------------------------------------*/
/* Gestion du message
/*-----------------------------------------------------------------------------------*/
ob_start();
include( get_template_directory() . '/inc/mail/contact.php' );
$mail = ob_get_contents();
ob_end_clean();
/*-----------------------------------------------------------------------------------*/
/* Envoie de l'e-mail
/*-----------------------------------------------------------------------------------*/
// Support d'un contenu HTML dans l'email
add_filter( 'wp_mail_content_type', create_function('', 'return "text/html";') );
if( wp_mail( 'emailtest#gmail.com', '[subject] Contact', $mail, $headers ) ) {
// Tout est ok, on avertit l'utilisateur
wp_send_json( 'success' );
}
else {
// Il y a une erreur avec le mail, on avertit l'utilisateur
wp_send_json( 'error' );
}
}
/*-----------------------------------------------------------------------------------*/
/* Second form
/*-----------------------------------------------------------------------------------*/
add_action( 'wp_ajax_inscription', '_ajax_inscription' );
add_action( 'wp_ajax_nopriv_inscription', '_ajax_inscription' );
function _ajax_inscription() {
/*-----------------------------------------------------------------------------------*/
/* On vérifie le nonce de sécurité
/*-----------------------------------------------------------------------------------*/
check_ajax_referer( 'ajax_inscription_nonce', 'security' );
/*-----------------------------------------------------------------------------------*/
/* Protection des variables
/*-----------------------------------------------------------------------------------*/
$subject = wp_strip_all_tags( $_POST['subject'] ); // Sujet du message
$name = wp_strip_all_tags( $_POST['name'] ); // Nom de l'expéditeur
$sender = sanitize_email( $_POST['email'] ); // Adresse e-mail de l'expéditeur
$message = nl2br( stripslashes( wp_kses( $_POST['message'], $GLOBALS['allowedtags'] ) ) );
/*-----------------------------------------------------------------------------------*/
/* Gestion des headers
/*-----------------------------------------------------------------------------------*/
$headers = array();
$headers[] = 'FROM : ' . $name . ' <' . $sender .'>' . "\r\n";
/*-----------------------------------------------------------------------------------*/
/* Gestion du message
/*-----------------------------------------------------------------------------------*/
ob_start();
include( get_template_directory() . '/inc/mail/contact.php' );
$mail = ob_get_contents();
ob_end_clean();
/*-----------------------------------------------------------------------------------*/
/* Envoie de l'e-mail
/*-----------------------------------------------------------------------------------*/
// Support d'un contenu HTML dans l'email
add_filter( 'wp_mail_content_type', create_function('', 'return "text/html";') );
if( wp_mail( 'testemail#gmail.com', $subject, $mail, $headers ) ) {
// Tout est ok, on avertit l'utilisateur
wp_send_json( 'success' );
}
else {
// Il y a une erreur avec le mail, on avertit l'utilisateur
wp_send_json( 'error' );
}
}
Looking at your code, the first thing I would try to do is to rename fields with name='name'. I coded a lot of forms and in almost every case, WP wouldn't post my forms, because it has reserved field with name='name'.
Also, activate WP_DEBUG mode to show all errors and try to look for JavaScript errors with Firebug or the browser console.
Thank for your answer, finally i have found another solution. The problem was not in this file..
It was on my form file. I forgot to change a value on the send button.
My mistake :
<input type="hidden" name="action" value="contact" />
<?php wp_nonce_field( 'ajax_inscription_nonce', 'security' ); ?>
<input id="send-message" type="submit" value="Envoyer">
The good code
<input type="hidden" name="action" value="inscription" />
<?php wp_nonce_field( 'ajax_inscription_nonce', 'security' ); ?>
<input id="send-message" type="submit" value="Envoyer">
Thanks a lot.
I am using joomla 3.1.1 and joomshopping. i need to insert values in another table at same time when user register on website. In user controller i need to insert values in my custom table. can i use a direct insert query in my controller file. this is function in controller file to register user. Where i can put my code to insert data in another table.
function registersave(){
JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
$mainframe = JFactory::getApplication();
$jshopConfig = JSFactory::getConfig();
$config = JFactory::getConfig();
$db = JFactory::getDBO();
$params = JComponentHelper::getParams('com_users');
$lang = JFactory::getLanguage();
$lang->load('com_users');
$post = JRequest::get('post');
JPluginHelper::importPlugin('captcha');
$dispatcher = JDispatcher::getInstance();
$res = $dispatcher->trigger('onCheckAnswer',$post['recaptcha_response_field']);
if(!$res[0]){
JError::raiseWarning('','Invalid Captcha');
$this->setRedirect("index.php?option=com_jshopping&controller=user&task=register",'','',$jshopConfig->use_ssl);
}
else
{
JPluginHelper::importPlugin('jshoppingcheckout');
$dispatcher = JDispatcher::getInstance();
if ($params->get('allowUserRegistration')==0){
JError::raiseError( 403, JText::_('Access Forbidden'));
return;
}
$usergroup = JTable::getInstance('usergroup', 'jshop');
$default_usergroup = $usergroup->getDefaultUsergroup();
if (!$_POST["id"]){
}
$post['username'] = $post['u_name'];
$post['password2'] = $post['password_2'];
//$post['name'] = $post['f_name'].' '.$post['l_name'];
$post['mailing_list'] = $post['mailing_list'];
$hear = '';
$post['where_did_you_purchase'] = $post['where_did_you_purchase'];
$post['ages_of_your_children'] = $agesofchilderen;
$post['comments_or_suggestions'] = $post['comments_or_suggestions'];
$post['vehicle_2'] = $post['vehicle_2_model'].'-'.$post['vehicle_2_year'];
if ($post['birthday']) $post['birthday'] = getJsDateDB($post['birthday'], $jshopConfig->field_birthday_format);
$dispatcher->trigger('onBeforeRegister', array(&$post, &$default_usergroup));
$row = JTable::getInstance('userShop', 'jshop');
$row->bind($post);
$row->usergroup_id = $default_usergroup;
$row->password = $post['password'];
$row->password2 = $post['password2'];
if (!$row->check("register")){
JError::raiseWarning('', $row->getError());
$this->setRedirect(SEFLink("index.php?option=com_jshopping&controller=user&task=register",1,1, $jshopConfig->use_ssl));
return 0;
}
$user = new JUser;
$data = array();
$data['groups'][] = $params->get('new_usertype', 2);
$data['email'] = JRequest::getVar("email");
$data['password'] = JRequest::getVar("password");
$data['password2'] = JRequest::getVar("password_2");
//$data['name'] = $post['f_name'].' '.$post['l_name'];
$data['username'] = JRequest::getVar("u_name");
$useractivation = $params->get('useractivation');
$sendpassword = $params->get('sendpassword', 1);
if (($useractivation == 1) || ($useractivation == 2)) {
jimport('joomla.user.helper');
$data['activation'] = JApplication::getHash(JUserHelper::genRandomPassword());
$data['block'] = 1;
}
//echo $row->getTableName();
//print_r($row);
//die("kkk");
$user->bind($data);
$user->save();
$row->user_id = $user->id;
unset($row->password);
unset($row->password2);
if (!$db->insertObject($row->getTableName(), $row, $row->getKeyName())){
JError::raiseWarning('', "Error insert in table ".$row->getTableName());
$this->setRedirect(SEFLink("index.php?option=com_jshopping&controller=user&task=register",1,1,$jshopConfig->use_ssl));
return 0;
}
}
}
Try this,
Please do not edit Joomla core files.
If you need to add register data on your custom table the create a User Plugin.
Joomla provides lot of plugin events in your case you can use onUserAfterSave. event
Create a User plugin with onUserAfterSave event then simply use the Joomla DB library to your custom table entries.
Hope it helps..
I uploaded my product images as follow: an image with 1234 id will be uploaded in img/p/1/2/3/4/1234-large_default.jpg when i viewed the product information related to the image, a default file (product image unavailable) is displayed.
my code for adding images to database
$res = "insert into "._DB_PREFIX_."image (`id_product`,`position`,`cover`) values
(".$id_product.",1, 1)";
if (!Db::getInstance()->execute($res))
die('Erreur etc.');
$id_image = Db::getInstance()->Insert_ID();
$res = "insert into "._DB_PREFIX_."image_lang (`id_image`,`id_lang`) values (".$id_image.", 1)";
if (!Db::getInstance()->execute($res))
die('Erreur etc.');
$res = "insert into "._DB_PREFIX_."image_lang (`id_image`,`id_lang`) values (".$id_image.", 2)";
if (!Db::getInstance()->execute($res))
die('Erreur etc.');
$stmt = "insert into "._DB_PREFIX_."image_shop(`id_image`,`id_shop`,`cover`) values (".$id_image.",1,1)";
$folders = str_split($id_image);
$i = 0;
$base_uri ='var/www/autospareparts.se.com/img/p/';
$folders = str_split($id_image);
$i = 0;
$base_uri ='/var/www/autospareparts.se.com/img/p/';
while( $i <sizeof($folders) )
{
$base_uri .= $folders[$i].'/';
if($i==(sizeof($folders) -1))
{if(!is_dir( $base_uri))
if(!mkdir($base_uri, 0777, true))
die('Echec lors de la création des répertoires...');
download_remote_file('http://pic1.aldoc.eu/PicData /'.$pic,$base_uri.$id_image.'large_default.jpg' );
}
//fin else
$i++;
}
I showed the code of mytheme/product.tpl i found
$link->getImageLink($product->link_rewrite, $cover.id_image, 'large_default')
which return img/p/fr-default-large_default.jpg
Can you tell me what's wrong?
Thanks
$image = new Image($id_image);
$image_url = _PS_BASE_URL_._THEME_PROD_DIR_.$image->getExistingImgPath().".jpg";
OR if images got path like img/p/1/2/3/4-1234.jpg:
function imgurl($img_id){
$ids="".$img_id;
$result="";
for ($i=0;$i<strlen($ids);$i++){
$result.=$ids[$i]."/";
}
$result.=$img_id;
return $result;
}
I have developed simple application, i have generated checkbox in grid dynamically from database, but my problem is when user select the checkbox and other required field from grid and press submit button, it adds duplicate value, so i want to know how can i check the checkbox value & other field value with database value while submitting data to database.
following code i use to generate all selected items and then save too db
foreach ($this->addattendee->results as $key=>$value)
{
//print_r($value);
$id = $this->Attendee_model->save($value);
}
i am using codeigniter....can any one give the idea with sample code plz
{
$person = $this->Person_model->get_by_id($id)->row();
$this->form_data->id = $person->tab_classid;
$this->form_data->classtitle = $person->tab_classtitle;
$this->form_data->classdate = $person->tab_classtime;
$this->form_data->createddate = $person->tab_crtdate;
$this->form_data->peremail = $person->tab_pemail;
$this->form_data->duration = $person->tab_classduration;
//Show User Grid - Attendee>>>>>>>>>>>>>>>>>>>>>>>>
$uri_segment = 0;
$offset = $this->uri->segment($uri_segment);
$users = $this->User_model->get_paged_list($this->limit, $offset)->result();
// generate pagination
$this->load->library('pagination');
$config['base_url'] = site_url('person/index/');
$config['total_rows'] = $this->User_model->count_all();
$config['per_page'] = $this->limit;
$config['uri_segment'] = $uri_segment;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
// generate table data
$this->load->library('table');
$this->table->set_empty(" ");
$this->table->set_heading('Check', 'User Id','User Name', 'Email', 'Language');
$i = 0 + $offset;
foreach ($users as $user)
{
$checkarray=array('name'=>'chkclsid[]','id'=>'chkclsid','value'=>$user->user_id);
$this->table->add_row(form_checkbox($checkarray), $user->user_id, $user->user_name, $user->user_email,$user->user_language
/*,anchor('person/view/'.$user->user_id,'view',array('class'=>'view')).' '.
anchor('person/update/'.$user->user_id,'update',array('class'=>'update')).' '.
anchor('person/showattendee/'.$user->user_id,'Attendee',array('class'=>'attendee')).' '.
anchor('person/delete/'.$user->user_id,'delete',array('class'=>'delete','onclick'=>"return confirm('Are you sure want to delete this person?')"))*/ );
}
$data['table'] = $this->table->generate();
//end grid code
// load view
// set common properties
$data['title'] = 'Assign Attendees';
$msg = '';
$data['message'] = $msg;
$data['action'] = site_url('person/CreateAttendees');
//$data['value'] = "sssssssssssssssssss";
$session_data = $this->session->userdata('logged_in');
$data['username'] = "<p>Welcome:"." ".$session_data['username']. " | " . anchor('home/logout', 'Logout')." | ". "Userid :"." ".$session_data['id']; "</p>";
$data['link_back'] = anchor('person/index/','Back to list of Classes',array('class'=>'back'));
$this->load->view('common/header',$data);
$this->load->view('adminmenu');
$this->load->view('addattendee_v', $data);
}
The code is quite messy but I have solved a similar issue in my application I think, I am not sure if its the best way, but it works.
function save_vote($vote,$show_id, $stats){
// Check if new vote
$this->db->from('show_ratings')
->where('user_id', $user_id)
->where('show_id', $show_id);
$rs = $this->db->get();
$user_vote = $rs->row_array();
// Here we are check if that entry exists
if ($rs->num_rows() == '0' ){
// Its a new vote so insert data
$this->db->insert('show_ratings', $rate);
}else{
// Its a not new vote, so we update the DB. I also added a UNIQUE KEY to my database for the user_id and show_id fields in the show_ratings table. So There is that extra protection.
$this->db->query('INSERT INTO `show_ratings` (`user_id`,`show_id`,`score`) VALUES (?,?,?) ON DUPLICATE KEY UPDATE `score`=?;', array($user_id, $show_id, $vote, $vote));
return $update;
}
}
I hope this code snippet gives you some idea of what to do.
maybe i have same trouble with you.
and this is what i did.
<?php
public function set_news(){
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$query = $this->db->query("select slug from news where slug like '%$slug%'");
if($query->num_rows()>=1){
$jum = $query->num_rows() + 1;
$slug = $slug.'-'.$jum;
}
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text')
);
return $this->db->insert('news', $data);
}
?>
then it works.