如何将数组插入数据库打开购物车? [英] How insert array to database in open cart?

查看:202
本文介绍了如何将数组插入数据库打开购物车?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过添加行表和通过自动完成的用户输入构建动态输入,然后将 PRODUCT_ID 存储在< input name =idpvalue =>例如用户输入两次(HP& Computer)


$ b

$ b

名称产品| PRODUCT_ID


  1. HP = 2945




  2. 应该在数组中是=(2945,8654)

      class ControllerItemItem extends Controller {//Controller/Item/Item.php 
    private $ error = array();

    public function index(){
    $ this-> language-> load('item / item');
    $ b $ this-> document-> setTitle($ this-> language-> get('heading_title'));

    $ this-> load-> model('item / item');

    $ this-> getList();

    $ b $ protected function getList(){

    if(isset($ this-> request-> get ['head_text_field'])){
    $ head_text_field = $ this-> request-> get ['head_text_field'];
    } else {
    $ head_text_field = null;


    if(isset($ this-> request-> get ['title_text_field'])){
    $ title_text_field = $ this-> request-> ;得到[ 'title_text_field'];
    } else {
    $ title_text_field = null;


    if(isset($ this-> request-> get ['max'])){
    $ max = $ this-> request-> ;获得[ '最大'];
    } else {
    $ max = null;
    }

    if(isset($ this-> request-> get ['idp'])){
    $ product = $ this-> request-> ;得到[ 'IDP'];
    $ product2 = array();
    foreach($ product as $ p)
    {
    $ product2 [] = $ p;
    }

    } else {
    $ product = null;


    $ b // BREADCRUMBS //
    $ this-> data ['breadcrumbs'] = array();

    $ this-> data ['breadcrumbs'] [] = array(
    'text'=> $ this-> language-> get('text_home'),
    'href'=> $ this-> url-> link('common / home','token ='。$ this-> session-> data ['token'],'SSL '),
    'separator'=> false
    );

    $ this-> data ['breadcrumbs'] [] = array(
    'text'=> $ this-> language-> get('text_module'),
    'href'=> $ this-> url-> link('extension / module','token ='。$ this-> session-> data ['token'],'SSL '),
    'separator'=>'::'
    );

    $ this-> data ['breadcrumbs'] [] = array(
    'text'=> $ this-> language-> get('heading_title'),
    'href'=> $ this-> url-> link('module / item','token ='。$ this-> session-> data ['token'],'SSL '),
    'separator'=>'::'
    );
    // END //

    //调用语言//
    $ this-> data ['heading_title'] = $ this-> language-> get 'HEADING_TITLE');
    $ this-> data ['entry_head'] = $ this-> language-> get('entry_head');
    $ this-> data ['entry_title'] = $ this-> language-> get('entry_title');
    $ this-> data ['entry_product'] = $ this-> language-> get('entry_product');
    $ this-> data ['entry_max_item'] = $ this-> language-> get('entry_max_item');
    $ this-> data ['button_save'] = $ this-> language-> get('button_save');
    $ this-> data ['button_cancel'] = $ this-> language-> get('button_cancel');
    // END //

    $ this-> data ['cancel'] = $ this-> url-> link('extension / module','token =' 。$ this-> session-> data ['token'],'SSL');
    $ this-> data ['action'] = $ this-> url-> link('item / item / insert','token ='。$ this-> session-> data ['token'],'SSL');
    $ this-> data ['token'] = $ this-> session-> data ['token'];


    $ data = array(
    'head_text_field'=> $ head_text_field,
    'title_text_field'=> $ title_text_field,
    'max' => $ max
    );

    $ this-> template ='item / item.tpl';
    $ this-> children = array(
    'common / header',
    'common / footer'
    );

    $ this-> response-> setOutput($ this-> render());


    $ b public function insert()
    {

    $ this-> language-> load('item / item );
    $ b $ this-> document-> setTitle($ this-> language-> get('heading_title'));

    $ this-> load-> model('item / item'); ($($ this-> request-> server ['REQUEST_METHOD'] =='POST')&& $ this-> validateForm()){


    // $这 - > model_item_item-> insert_head($这 - >请求 - >交);
    $ this-> model_item_item-> insert_detail($ this-> request-> post);
    $ b $ // this-> session-> data ['success'] = $ this-> language-> get('text_success');
    // $ this->重定向($ this-> url->链接('item / item','token ='。$ this-> session-> data ['token']] ,'SSL'));


    $ b protected function validateForm(){
    if(!$ this-> user-> hasPermission('modify','item / item ')){
    $ this-> error ['warning'] = $ this-> language-> get('error_permission'); ($ utf8_strlen($ this-> request-> post ['head_text_field'])< 1)||(utf8_strlen($ this-> request- > post ['head_text_field'])> 64)){
    $ this-> error ['head'] = $ this-> language-> get('error_head');


    if(!$ this-> request-> post ['title_text_field']){
    $ this-> error ['title'] = $这 - >语言 - >获得( 'error_title');
    }

    if(!$ this-> error){
    return true;
    } else {
    return false;




    $ p $这是用于模型:

      class ModelItemItem extends Model {
    public function insert_head($ data)
    {
    $ this-> db- > query(INSERT INTO.DB_PREFIX。show_product SET head_text ='。$ this-> db-> escape($ data ['head_text_field'])。'',title_text ='。$ this- > db-> escape($ data ['title_text_field'])。'',max_item ='。$ this-> db-> escape($ data ['max'])。');


    public function insert_detail($ product2)
    {
    foreach($ product2 as $ detail)
    {
    // $ this - > db-> query(INSERT INTO.DB_PREFIX。show_product_detail SET product_id ='。$ this-> db-> escape($ detail ['product'])。');
    }
    echo $ detail [0];

    code










    $ b $ p


    $ b

    这是查看:

     <?php echo $ header; ?> 
    < div id =content>
    < div class =breadcrumb>
    <?php foreach($ breadcrumbs as $ breadcrumb){?>
    <?php echo $ breadcrumb ['separator']; ?>< a href =<?php echo $ breadcrumb ['href'];?>><?php echo $ breadcrumb ['text']; ?>< / A>
    <?php}?>
    < / div>
    <?php if($ error_warning){?>
    < div class =warning><?php echo $ error_warning; ?>< / DIV>
    <?php}?>
    <?php if($ success){?>
    < div class =success><?php echo $ success; ?>< / DIV>
    <?php}?>
    < div class =box>
    < div class =heading>
    < h1>< img src =view / image / product.pngalt =/> <?php echo $ heading_title; ?>< / H1>
    < div class =buttons>< a onclick =$('#form')。submit(); class =button><?php echo $ button_save; ?>< / a>< a href =<?php echo $ cancel;?> class =button><?php echo $ button_cancel; ?>< / A>< / DIV>
    < / div>
    < div class =content>
    < form action =<?php echo $ action;?> method =postenctype =multipart / form-dataid =form>
    < table class =form>
    < tr>
    < td>< span class =required> *< / span> <?php echo $ entry_head; ?>< / TD>
    < td>< input type =textname =head_text_fieldvalue =placeholder =Input Head Textsize =40/>
    <?php if($ error_head){?>
    < span class =error><?php echo $ error_head; ?>< /跨度>
    <?php}?>
    < / td>
    < / tr>
    < tr>
    < td>< span class =required> *< / span> <?php echo $ entry_title; ?>< / TD>
    < td>< textarea name =title_text_fieldplaceholder =Input Title Textstyle =width:230px;/>< / textarea>
    <?php if($ error_title){?>
    < span class =error><?php echo $ error_title; ?>< /跨度>
    <?php}?>
    < / td>
    < / tr>
    < tr>
    < td><?php echo $ entry_max_item; ?>< / TD>
    < td>
    < select name =maxid =maxitem> ($ i = 1; $ i <= 6; $ i ++)
    {
    if($ i == 1)
    echo
    <?php
    < option selected ='selected'value =。$ i。>。$ i。< / option>;
    else
    echo< option value =。$ i。>。$ i。< / option>;
    }
    ?>
    < / select>
    < / td>
    < / tr>
    < tr>
    < td><?php echo $ entry_product; ?>< / TD>
    < td>< input type =textid =productname =productvalue =placeholder =Input Productsize =40/>< / td>
    < td>< input type =hiddenid =idpname =idpvalue =/>< / td>
    < / tr>
    < tr>
    < td>< / td>
    < td>
    < table>
    < tr>
    < td>< input type =buttonid =ADDvalue =Add Item>< / td>
    < td>< input type =resetid =RESETvalue =Reset>< / td>
    < / tr>
    < / table>
    < / td>
    < / tr>
    < tr>

    < / tr>
    < / table>

    < table border =1id =tblnamecellpadding =5cellspacing =5>
    < thead>
    < tr>
    < td>
    总项目
    < / td>
    < td>
    Id Item
    < / td>
    < td>
    名称项目
    < / td>
    < td>
    删除
    < / td>
    < tr>
    < / thead>
    < tbody align =center>
    < / tbody>
    < / table>
    < / form>
    < / div>
    < / div>
    < / div>
    < script type =text / javascript><! -
    $('input [name = \\''product'''')。autocomplete({
    delay:100,
    source:function(request,response){
    $ .ajax({
    url:'index.php?route = catalog / product / autocomplete& token =< php echo $ token;?>& filter_name ='+ encodeURIComponent(request.term),
    dataType:'json',
    success:function(json){
    response($。 map(json,function(item){
    return {
    label:item.name,
    value:item.product_id
    }
    }));
    }}
    });
    },
    select:function(event,ui){
    $('input [name = \\''product \\'''')。 val(ui.item.label);
    $('input [name = \'idp\']')。val(ui.item.value);
    return false;
    },

    焦点:功能(事件,用户界面){
    返回false;
    }
    });

    // - >< / script>
    < Script type =text / javascript>
    $(document).ready(function(){
    var item = 1;
    var isAllowed = 3;
    var isSet = 0;
    $(' ADD())。click(function(){
    var maxitem = parseInt($(#maxitem).val(),10); //从html中的最大项目
    var iCount = 0;
    如果($('#product')。val()){//检查输入的产品
    if(item< = maxitem)
    {
    iCount = $ #tblname tbody tr')。length + 1;
    szTr =< tr>< td>;
    szTr = szTr + iCount +< / td>;
    szTr = szTr +< td>+ $('#idp').val()+< / td>;
    szTr = szTr +< td& ('product')。val()+< / td>;
    szTr = szTr +< td>< input type ='button'class ='DEL'value ='DELETE'>< ; / td>;
    szTr = szTr +< / tr>;
    $('#tblname tbody ').append(szTr);
    item + = 1;
    isSet = 1;
    restFormOpts();
    }
    else
    {
    alert(Max Limit !!!);
    }
    } else {alert('Enter Product !!!');}
    });
    $ b $ //删除行
    $('body')。on('click','#RESET',function(){
    item = 1;
    isAllowed = 3;
    isSet = 0;
    $(#maxitem)。attr(disabled,false);
    $('。DEL')。parents('tr ').remove();
    }); (),'input.DEL',function(){
    $(this).parents('tr')。remove() ;
    item - = 1;
    });

    函数restFormOpts()
    {
    if(isSet === isAllowed){
    $(#ADD)。attr(disabled,true) ;
    $(#maxitem)。attr(disabled,false);
    }
    else {
    $(#ADD)。attr(disabled,false);
    $(#maxitem)。attr(disabled,true);
    }
    }
    });
    < / script>
    <?php echo $ footer; ?>

    当我尝试向我的数据库插入查询时,只能得到1个数字。 b

    然后我试着Echo来确保变量是正确的,但它是错误的,结果是最后一个用户输入(计算机,在数组(8,6,5,4))?它应该是(2945,8654)不是(8,6,5,4)?

    有人可以帮我解决这个问题吗?我已经尝试解决这个问题1个星期仍然没有希望:($ / b>

    解决方案

    如果你想插入数组变量数据库中,首先需要对它们进行编码然后插入它们。

    例如$ abc = array(3,45,6,78,89);

    查询:INSERT INTO。DB_PREFIX。show_product_detail SET product_id ='。$ this-> db-> escape(json_encode($ abc))。'


    I build dynamic input by add row table, and user input by autocomplete, then I store PRODUCT_ID in <input name="idp" value="">

    E.g User input twice times (HP & Computer)

    Name Product | PRODUCT_ID

    1. HP = 2945

    2. COMPUTER = 8654

    Should be in array is = (2945,8654)

    This is for Controller:

    class ControllerItemItem extends Controller { //Controller/Item/Item.php
    private $error = array(); 
    
    public function index() {
        $this->language->load('item/item');
    
        $this->document->setTitle($this->language->get('heading_title')); 
    
        $this->load->model('item/item');
    
        $this->getList();
    }
    
    protected function getList(){
    
        if (isset($this->request->get['head_text_field'])){
            $head_text_field = $this->request->get['head_text_field'];
        } else {
            $head_text_field = null;
        }
    
        if (isset($this->request->get['title_text_field'])){
            $title_text_field = $this->request->get['title_text_field'];
        } else {
            $title_text_field = null;
        }
    
        if (isset($this->request->get['max'])){
            $max = $this->request->get['max'];
        } else {
            $max = null;
        }
    
        if(isset($this->request->get['idp'])){ 
            $product = $this->request->get['idp'];
            $product2 = array();
            foreach($product as $p)
            {
                $product2[] = $p;
            }
    
        }else {
            $product = null;
        }
    
    
        // BREADCRUMBS //
        $this->data['breadcrumbs'] = array();
    
        $this->data['breadcrumbs'][] = array(
            'text'      => $this->language->get('text_home'),
            'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
            'separator' => false
        );
    
        $this->data['breadcrumbs'][] = array(
            'text'      => $this->language->get('text_module'),
            'href'      => $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL'),
            'separator' => ' :: '
        );
    
        $this->data['breadcrumbs'][] = array(
            'text'      => $this->language->get('heading_title'),
            'href'      => $this->url->link('module/item', 'token=' . $this->session->data['token'], 'SSL'),
            'separator' => ' :: '
        );
        // END //
    
        // Call Language //
        $this->data['heading_title'] = $this->language->get('heading_title');
        $this->data['entry_head'] = $this->language->get('entry_head');
        $this->data['entry_title'] = $this->language->get('entry_title');
        $this->data['entry_product'] = $this->language->get('entry_product');
        $this->data['entry_max_item'] = $this->language->get('entry_max_item');
        $this->data['button_save'] = $this->language->get('button_save');
        $this->data['button_cancel'] = $this->language->get('button_cancel');
        // END //
    
        $this->data['cancel'] = $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL');
        $this->data['action'] = $this->url->link('item/item/insert', 'token=' . $this->session->data['token'], 'SSL');
        $this->data['token'] = $this->session->data['token'];
    
    
        $data   =   array(
            'head_text_field'   =>  $head_text_field,
            'title_text_field'  =>  $title_text_field,
            'max'               =>  $max
        );
    
        $this->template = 'item/item.tpl';
        $this->children = array(
            'common/header',
            'common/footer'
        );
    
        $this->response->setOutput($this->render());
    
    }
    
    public function insert()
    {
    
        $this->language->load('item/item');
    
        $this->document->setTitle($this->language->get('heading_title')); 
    
        $this->load->model('item/item');
    
        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
            //$this->model_item_item->insert_head($this->request->post);
            $this->model_item_item->insert_detail($this->request->post);
    
            //$this->session->data['success'] = $this->language->get('text_success');
            //$this->redirect($this->url->link('item/item', 'token=' . $this->session->data['token'], 'SSL'));
        }
    }
    
    protected function validateForm() {
        if (!$this->user->hasPermission('modify', 'item/item')) {
            $this->error['warning'] = $this->language->get('error_permission');
        }
    
        if ((utf8_strlen($this->request->post['head_text_field']) < 1) || (utf8_strlen($this->request->post['head_text_field']) > 64)) {
            $this->error['head'] = $this->language->get('error_head');
        }
    
        if (!$this->request->post['title_text_field']) {
            $this->error['title'] = $this->language->get('error_title');
        }
    
        if (!$this->error) {
            return true;
        } else {
            return false;
        }
    }
    

    This is for Model :

    class ModelItemItem extends Model { 
    public function insert_head($data)
    {
        $this->db->query("INSERT INTO " . DB_PREFIX . "show_product SET head_text = '" . $this->db->escape($data['head_text_field']) . "', title_text = '" . $this->db->escape($data['title_text_field']) . "', max_item = '" . $this->db->escape($data['max']) . "'");
    }
    
    public function insert_detail($product2)
    {
        foreach($product2 as $detail)
        {
            //$this->db->query("INSERT INTO " . DB_PREFIX . "show_product_detail SET product_id = '". $this->db->escape($detail['product']) . "'");
        }
        echo $detail[0];
    }
    

    }

    This is for view :

        <?php echo $header; ?>
    <div id="content">
      <div class="breadcrumb">
        <?php foreach ($breadcrumbs as $breadcrumb) { ?>
        <?php echo $breadcrumb['separator']; ?><a href="<?php echo $breadcrumb['href']; ?>"><?php echo $breadcrumb['text']; ?></a>
        <?php } ?>
      </div>
      <?php if ($error_warning) { ?>
      <div class="warning"><?php echo $error_warning; ?></div>
      <?php } ?>
      <?php if ($success) { ?>
      <div class="success"><?php echo $success; ?></div>
      <?php } ?>
      <div class="box">
        <div class="heading">
          <h1><img src="view/image/product.png" alt="" /> <?php echo $heading_title; ?></h1>
          <div class="buttons"><a onclick="$('#form').submit();" class="button"><?php echo $button_save; ?></a><a href="<?php echo $cancel; ?>" class="button"><?php echo $button_cancel; ?></a></div>
        </div>
        <div class="content">
          <form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data" id="form">
            <table class="form">
            <tr>
                <td><span class="required">*</span> <?php echo $entry_head; ?></td>
                <td><input type="text" name="head_text_field" value="" placeholder="Input Head Text" size="40"/>
                    <?php if ($error_head) { ?>
                        <span class="error"><?php echo $error_head; ?></span>
                    <?php } ?>
                </td>
            </tr>
            <tr>
                <td><span class="required">*</span> <?php echo $entry_title; ?></td>
                <td><textarea name="title_text_field" placeholder="Input Title Text" style="width:230px;"/></textarea>
                    <?php if ($error_title) { ?>
                        <span class="error"><?php echo $error_title; ?></span>
                    <?php } ?>
                </td>
            </tr>
            <tr>
                <td><?php echo $entry_max_item; ?></td>
                <td>
                    <select name="max" id="maxitem">
                    <?php
                    for($i=1; $i<=6; $i++)
                    {
                        if($i == 1)
                            echo "<option selected='selected' value=".$i.">".$i."</option>";
                        else
                            echo "<option value=".$i.">".$i."</option>";
                    }
                    ?>
                    </select>
                </td>
            </tr>
            <tr>
                <td><?php echo $entry_product; ?></td>
                <td><input type="text" id="product" name="product" value="" placeholder="Input Product" size="40"/></td>
                <td><input type="hidden" id="idp" name="idp" value="" /></td>
            </tr>
            <tr>
                <td></td>
                <td>
                <table>
                    <tr>
                        <td><input type="button" id="ADD" value="Add Item"></td>
                        <td><input type="reset" id="RESET" value="Reset"></td>
                    </tr>
                </table>
                </td>
            </tr>
            <tr>
    
            </tr>
            </table>
    
            <table border="1" id="tblname" cellpadding="5" cellspacing="5">
                <thead>
                <tr>
                    <td>
                        Total Item
                    </td>
                    <td>
                        Id Item
                    </td>
                    <td>
                        Name Item
                    </td>
                    <td>
                        DELETE
                    </td>
                <tr>
                </thead>
                <tbody align="center">
                </tbody>
            </table>
          </form>
        </div>
      </div>
    </div>
    <script type="text/javascript"><!--
    $('input[name=\'product\']').autocomplete({
        delay: 100,
        source: function(request, response) {
            $.ajax({
                url: 'index.php?route=catalog/product/autocomplete&token=<?php echo $token; ?>&filter_name=' +  encodeURIComponent(request.term),
                dataType: 'json',
                success: function(json) {       
                    response($.map(json, function(item) {
                        return {
                            label: item.name,
                            value: item.product_id
                        }
                    }));
                }
            });
        }, 
        select: function(event, ui) {
            $('input[name=\'product\']').val(ui.item.label);
            $('input[name=\'idp\']').val(ui.item.value);
            return false;
        },
    
        focus: function(event, ui) {
            return false;
        }
    });
    
    //--></script>
    <Script type="text/javascript">
    $(document).ready(function(){
        var item = 1;
        var isAllowed   = 3;
        var isSet       = 0;
        $('#ADD').click(function(){
            var maxitem = parseInt($("#maxitem").val(), 10); //from max item in html
            var iCount = 0;
            if($('#product').val()){  // check input product
                if( item <= maxitem )
                {
                    iCount = $('#tblname tbody tr').length + 1;
                    szTr = "<tr><td>";
                    szTr = szTr + iCount + "</td>";
                    szTr = szTr +   "<td>" +$('#idp').val() +"</td>";
                    szTr = szTr +   "<td>" +$('#product').val() +"</td>";
                    szTr = szTr +   "<td><input type='button' class='DEL' value='DELETE'></td>";
                    szTr = szTr +   "</tr>";                     
                    $('#tblname tbody').append(szTr);
                    item +=1;
                    isSet = 1;
                    restFormOpts();
                }
                else
                {
                    alert ("Max Limit !!!");
                }
            }else{alert('Enter Product !!! ');}
        });
    
        // for delete row
        $('body').on('click','#RESET', function() {
            item        = 1;
            isAllowed   = 3;
            isSet       = 0;
            $("#maxitem").attr("disabled",false);
            $('.DEL').parents('tr').remove();
        });
    
        $('body').on('click', 'input.DEL', function() {
            $(this).parents('tr').remove();  
            item -= 1;
        });
    
        function restFormOpts()
        {
            if(isSet === isAllowed) {
                $("#ADD").attr("disabled",true);
                $("#maxitem").attr("disabled",false);
            }
            else {
                $("#ADD").attr("disabled",false);
                $("#maxitem").attr("disabled",true);
            }
        }
    });
    </script>
    <?php echo $footer; ?>
    

    When I try insert query to my database, value only 1 number.

    Then I try Echo for make sure variable is correct but it's wrong, the result is the last user input (Computer, in array(8,6,5,4))? it's should be (2945,8654) not (8,6,5,4)?

    Can some one help me for fix this?? I already try fix this problem for 1 week still no hope :(

    解决方案

    If you want to insert array variables in database, First you need encode them and then insert them .

    Ex. $abc = array(3,45,6,78,89) ;

    Query : "INSERT INTO " . DB_PREFIX . "show_product_detail SET product_id = '". $this->db->escape(json_encode($abc)) . "'

    这篇关于如何将数组插入数据库打开购物车?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆