Перейти до вмісту
Пошук в
  • Детальніше...
Шукати результати, які ...
Шукати результати в ...

Не происходит запись в БД


Recommended Posts

Всем привет.

Прошу помощи. Переделываю мод, но возникла проблема.

Что сделал не так.

Вывожу форму tpl-кой таким образом

<b><p style="text-align: center;"><?php echo $product_herfprod; ?></b><br /><input name="product_herfprod" type="text" value="" />
В БД в соответствующей таблице создано поле product_herfprod

Контроллер выглядит таким образом:

<?phpclass ControllerModulecheap extends Controller {	protected function index() {		if ($this->config->get('cheap_status')) {			$this->language->load('module/cheap');			$this->document->addScript('catalog/view/javascript/jquery/colorbox/jquery.colorbox-min.js');			$this->document->addStyle('catalog/view/javascript/jquery/colorbox/colorbox.css');			$this->document->addScript('catalog/view/javascript/jquery/jquery.maskedinput.min.js');			$this->document->addScript('catalog/view/javascript/cheap.js');			$this->data['heading_title'] = $this->language->get('heading_title');			if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/cheap.tpl')) {				$this->template = $this->config->get('config_template') . '/template/module/cheap.tpl';			} else {				$this->template = 'default/template/module/cheap.tpl';			}			$this->render();		}	}	public function getForm() {		$this->load->model('catalog/product');		$this->language->load('module/cheap');		$this->data['heading_title'] = $this->language->get('heading_title');				$this->data['text_work'] = $this->language->get('text_work');		$this->data['text_wait'] = $this->language->get('text_wait');		$this->data['entry_contact'] = $this->language->get('entry_contact');				$this->data['product_herfprod'] = $this->language->get('product_herfprod');		$this->data['button_send'] = $this->language->get('button_send');				if ($this->config->get('cheap_phone_mask_status')) {			$this->data['phone_mask'] = $this->config->get('cheap_phone_mask');		} else {			$this->data['phone_mask'] = '';		}		$this->data['phone_text'] = $this->config->get('cheap_phone_text');				$this->data['stock_status'] = 1;				if ($this->request->server['REQUEST_METHOD'] == 'POST') {				if (isset($this->request->post['product_herfprod'])) {      					$product_herfprod = $this->request->post['product_herfprod'];				} else {      					$product_herfprod = '';    				}			}		if (!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning')) {			$product_info = $this->model_catalog_product->getProduct($this->request->get['product_id']);			if (!$product_info['quantity'] || ($product_info['quantity'] < 0)) {				$this->data['error_warning'] = $this->language->get('error_stock');				if (!$this->config->get('config_stock_checkout')) {					$this->data['stock_status'] = 0;				}			}		}		if ($this->customer->isLogged()) {			$this->load->model('account/customer');			$this->data['text_customer'] = $this->language->get('text_customer');			$customer = $this->model_account_customer->getCustomer($this->customer->getId());			$data = array(				'contact' => $customer['telephone'],				'product_id' => $this->request->get['product_id']			);			$this->write($data);		}		if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/cheap_form.tpl')) {			$this->template = $this->config->get('config_template') . '/template/module/cheap_form.tpl';		} else {			$this->template = 'default/template/module/cheap_form.tpl';		}		$this->response->setOutput($this->render());	}	public function write($settings = array()) {		$this->language->load('module/cheap');		$this->load->model('catalog/cheap');		$this->load->model('setting/setting');		$json = array();		if ($settings) {			$contact = $settings['contact'];			$product_id = $settings['product_id'];		} elseif ($this->request->server['REQUEST_METHOD'] == 'POST') {			$contact = $this->request->post['contact'];			$product_id = $this->request->post['product_id'];			} else {			$product_id = 0;		}		if ($product_id) {			if ((utf8_strlen($contact) < 3) || (utf8_strlen($contact) > 50)) {				if ($this->config->get('cheap_phone_mask_status')) {					$json['error']['contact'] = $this->language->get('error_mask');				} else {					$json['error']['contact'] = $this->language->get('error_contact');				}			}												if (!isset($json['error'])) {				if ($this->config->get('cheap_phone_text')) {					$contact = $this->config->get('cheap_phone_text') . $contact;				}				$this->load->model('catalog/product');				$product_info = $this->model_catalog_product->getProduct($product_id);								$price = isset($product_info['special']) ? $product_info['special'] : $product_info['price'];				$total = $this->currency->format($price);				$data = array(					'contact' => $contact,					'product_id' => $product_id,					'product_herfprod' => $product_herfprod,					'product_name' => $product_info['name'],					'total' => $price,					'currency_id' => $this->currency->getId(),					'currency_code' => $this->currency->getCode(),					'currency_value' => $this->currency->getValue($this->currency->getCode())				);								$order_id = $this->model_catalog_cheap->addOrder($data);/*				if ($this->config->get('cheap_email_status')) {					$email_subject = sprintf($this->language->get('text_subject'), $this->language->get('heading_title'), $this->config->get('config_name'), $order_id);					$email_text = sprintf($this->language->get('text_order'), $order_id) . "\n\n";					$email_text .= sprintf($this->language->get('text_contact'), html_entity_decode($contact), ENT_QUOTES, 'UTF-8') . "\n";					$email_text .= sprintf($this->language->get('text_ip'), $this->request->server['REMOTE_ADDR'], ENT_QUOTES, 'UTF-8') . "\n\n";					$email_text .= sprintf($this->language->get('text_product'), html_entity_decode($product_info['name']), ENT_QUOTES, 'UTF-8') . "\n";					$email_text .= sprintf($this->language->get('text_date_order'), date('d.m.Y H:i'), ENT_QUOTES, 'UTF-8') . "\n\n";					$email_text .= sprintf($this->language->get('text_price'), $total, ENT_QUOTES, 'UTF-8');					$mail = new Mail();					$mail->protocol = $this->config->get('config_mail_protocol');					$mail->parameter = $this->config->get('config_mail_parameter');					$mail->hostname = $this->config->get('config_smtp_host');					$mail->username = $this->config->get('config_smtp_username');					$mail->password = $this->config->get('config_smtp_password');					$mail->port = $this->config->get('config_smtp_port');					$mail->timeout = $this->config->get('config_smtp_timeout');					$mail->setTo($this->config->get('config_email'));					$mail->setFrom($this->config->get('config_email'));					$mail->setSender($this->config->get('config_name'));					$mail->setSubject($email_subject);					$mail->setText($email_text);					$mail->send();				}*/				$json['success'] = $this->language->get('text_success');			}		}		$this->response->setOutput(json_encode($json));	}}?>

Ну а модель соответственно:

<?phpclass ModelCatalogcheap extends Model {	public function addOrder($data) {		$this->db->query("INSERT INTO " . DB_PREFIX . "cheap SET contact = '" . $this->db->escape($data['contact']) . "', product_id = '" . (int) $data['product_id'] . "', product_name = '" . $this->db->escape($data['product_name']) . "', product_herfprod = '" . $data['product_herfprod'] . "', total = '" . (float) $data['total'] . "', date_added = NOW(), currency_id = '" . (int) $data['currency_id'] . "', currency_code = '" . $this->db->escape($data['currency_code']) . "', currency_value = '" . (float) $this->db->escape($data['currency_value']) . "'");		$order_id = $this->db->getLastId();		$this->db->query("UPDATE " . DB_PREFIX . "product SET quantity = (quantity - 1) WHERE product_id = '" . (int) $data['product_id'] . "' AND subtract = '1'");		return $order_id;	}}?>
Собственно вопрос, почему данные вводимые в tpl-ке не записываются в БД. Что я накосячил в контроллере?

Прошу сильно не ругаться, опыта совсем нет, делаю модуль для своего сайта.

Заранее всем спасибо за помощь.

Змінено користувачем shoputils
spoiler
Надіслати
Поділитися на інших сайтах


        if ($settings) {
            $contact = $settings['contact'];
            $product_id = $settings['product_id'];
        } elseif ($this->request->server['REQUEST_METHOD'] == 'POST') {
            $contact = $this->request->post['contact'];
            $product_id = $this->request->post['product_id'];
            } else {
            $product_id = 0;
        }

и где тут про $product_herfprod ?

Надіслати
Поділитися на інших сайтах

Привожу к виду

        if ($settings) {
            $contact = $settings['contact'];
            $product_id = $settings['product_id'];
        } elseif ($this->request->server['REQUEST_METHOD'] == 'POST') {
            $contact = $this->request->post['contact'];
            $product_herfprod = $this->request->post['product_herfprod'];
            $product_id = $this->request->post['product_id'];
            } else {
            $product_id = 0;

        }

Ничего так же не происходит, запись не вносится

Надіслати
Поділитися на інших сайтах


Вот на этом мои знания и оканчиваются

 

Необходимо сделать так? :

if ($settings) {
			$contact = $settings['contact'];
			$product_id = $settings['product_id'];
		} elseif ($this->request->server['REQUEST_METHOD'] == 'POST') {
			$contact = $this->request->post['contact'];
			$product_herfprod = var_dump($this->request->post['product_herfprod']);exit;
			$product_id = $this->request->post['product_id'];
			} else {
			$product_id = 0;
		}
Надіслати
Поділитися на інших сайтах


Спасибо за ссылку, читал это после вашей подсказки про var_dump. Но к сожалению знания не позволяют все правильно сделать. Спасибо за помощь.

Надіслати
Поділитися на інших сайтах


А еще в tpl надо написать тег <form> указать ему action и метод POST и в этот тег поместить ваш input хотя бы... иначе что и куда у ваc вообще может отправляться
 

Змінено користувачем Waha
Надіслати
Поділитися на інших сайтах

  • 3 weeks later...

используйте var_dump

 

Лучше писать в журнал ошибок, чтоб не нарушать процесс выполнения, да и вообще это удобней для отладки:

$this->log->write($this->request->post['product_herfprod']);

Если в журнале ничего не будет или будет ошибка про неопределённый индекс product_herfprod - значит проблема в шаблоне, из которого это поле не отправляется на сервер (или вообще ничего не отправляется, по вашему коду непонятно, как вы форму с этим полем сабмитите).

Надіслати
Поділитися на інших сайтах


Створіть аккаунт або увійдіть для коментування

Ви повинні бути користувачем, щоб залишити коментар

Створити обліковий запис

Зареєструйтеся для отримання облікового запису. Це просто!

Зареєструвати аккаунт

Вхід

Уже зареєстровані? Увійдіть тут.

Вхід зараз
  • Зараз на сторінці   0 користувачів

    • Ні користувачів, які переглядиють цю сторінку

×
×
  • Створити...

Important Information

На нашому сайті використовуються файли cookie і відбувається обробка деяких персональних даних користувачів, щоб поліпшити користувальницький інтерфейс. Щоб дізнатися для чого і які персональні дані ми обробляємо перейдіть за посиланням . Якщо Ви натиснете «Я даю згоду», це означає, що Ви розумієте і приймаєте всі умови, зазначені в цьому Повідомленні про конфіденційність.