How to insert multiple radio button values with PH

2020-02-07 10:49发布

问题:

I'm working on a CMS with PHP OOP. In this project, there is a feature for users to add new Telegram Channel. For this feature, I added this form which also contains the action codes:

    <?php 
if(isset($_POST['submit'])){
    $token = $_POST['token'];
    $cat = $_POST['cat'];
    $ads = $_POST['ads'];
    $key = $_POST['keyboard'];
    $tel = new Telegram();
    $notice = $tel->AddNew($token,$cat,$ads,$key);
}
?>
<div class='content-wrapper'>
    <section class='content-header'>
        <h1>
            Add New Telegram Account
            <small>You can add a new Telegram channel here</small>
        </h1>
        <ol class='breadcrumb'>
            <li class='active'>telegram.php</li>
        </ol>
    </section>
    <?php 
    if($dataSet->GetLevel()==1)
    { echo "
        <section class='content'>
            <div class='row'>
                <div class='col-md-6'>
                    <div class='box box-primary'>
                        <div class='box-header with-border'>
                            <h3 class='box-title'>Required Information</h3>
                        </div>
                        ";
                        if(isset($notice['success_message'])){
                            echo "
                                <div class='alert alert-success'>
                                    <strong>Hey!</strong> ".$notice['success_message'].".
                                </div>
                            ";
                        }
                        echo "
                        <form role='form' method='POST' action=''>
                            <div class='box-body'>
                                <div class='form-group'>
                                    <label>Token Number</label>
                                    <input type='text' class='form-control' placeholder='Enter token' name='token' required>
                                    <a href='#' style='color:purple;'>Having problem while getting token</a>
                                </div>
                                <div class='form-group'>
                                    <label>Select Category</label>
                                    <select name='cat' class='form-control'>
                                        <option value='empty'>---</option>
                                        <option value='technology'>Technology</option>
                                        <option value='4fun'>Game & Fun</option>
                                        <option value='news'>News</option>
                                        <option value='tools'>Tools</option>
                                        <option value='learning'>Learning</option>
                                        <option value='traditional'>Traditional</option>
                                        <option value='media'>Media</option>
                                    </select>
                                </div>
                                <div class='form-group'>
                                    <div class='radio'>
                                        <label>
                                            <input type='radio' name='ads' id='optionsRadios1' value='on' checked>
                                            Set ads on</br>
                                            <input type='radio' name='ads' id='optionsRadios1' value='off'>
                                            Set ads off
                                        </label>
                                    </div>
                                </div>
                                <div class='form-group'>
                                    <div class='checkbox'>
                                        <label>
                                            <input type='checkbox' name='keyboard' value='with_keyboard'>
                                            Use dedicated keyboard for this bot
                                        </label></br>
                                        <label>
                                            <input type='checkbox' name='keyboard' value='without_keyboard'>
                                            Show keyboard at groups
                                        </label></br>
                                        <label>
                                            <input type='checkbox' name='answer' value='answer_messages_chats' checked>
                                            In private chats, just anwser the pre defined messages
                                        </label></br>
                                        <label>
                                            <input type='checkbox' name='answer' value='answer_messages_groups' checked>
                                            In groups, just answer the pre defined messages
                                        </label>
                                    </div>
                                </div>
                            </div>
                            <div class='box-footer'>
                                Visit <a href='https://zite.pouyavagefi.com/documentation/telegram.php'>Telegram</a> Social Media Documentation.
                            </div>
                            <div class='box-footer'>
                                <button name='submit' type='submit' class='btn btn-primary'>Submit</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </section> "; 
    }else{
        echo "
        <section class='content'>
            <div class='alert alert-warning'>
                <strong>Access Denied!</strong> You don\'t have permission to access this page.
            </div> 
        </section> "; 
    }
    ?>
</div>

As you can at the top, I have called a class which is called Telegram.class.php and this class goes like this:

    <?php 
class Telegram
{   
    protected $notice = array();
    private $db;
    public function __construct()
    {
        $this->db = new Connection();
        $this->db = $this->db->dbConnect();
    }
    public function AddNew($token,$cat,$ads,$key)
    {
        if(!empty($token)&&!empty($cat)&&!empty($ads))
        {
            for ($i=0;$i<sizeof($ads);$i++)
            {
                for ($i=0;$i<sizeof($key);$i++)
                {
                    $new = $this->db->prepare("INSERT INTO channels (token_number, category_name, ads_set, keyboard_status) VALUES (?, ?, "/*.$ads[$i].*/", "/*.$key[$i].*/")");
                    $new->bindParam(1,$token);
                    $new->bindParam(2,$cat);
                    $new->bindParam(3,$ads);
                    $new->bindParam(4,$key);
                    $new->execute();
                    $notice['success_message'] = "New Telegram Channel was successfully added";
                    return $this->notice;
                }
            }

        }
    }
    public function getNotice()
    {
        return $this->notice;
    }
}
?>

Because I want to add multiple checkboxes into table, I used this for loop inside the method Add_New (According to this question):

for ($i=0;$i<sizeof($ads);$i++)
        {
            for ($i=0;$i<sizeof($key);$i++)
            {
                $new = $this->db->prepare("INSERT INTO channels (token_number, category_name, ads_set, keyboard_status) VALUES (?, ?, "/*.$ads[$i].*/", "/*.$key[$i].*/")");
                $new->bindParam(1,$token);
                $new->bindParam(2,$cat);
                $new->bindParam(3,$ads);
                $new->bindParam(4,$key);
                $new->execute();
                $notice['success_message'] = "New Telegram Channel was successfully added";
                return $this->notice;
            }
        }

I know it's not correct but I don't know the right way to add these $ads[$i] and $key[$i] variables into the insert statement...

So if you know how to do this in the correct order, please let me know.. thanks!

回答1:

Simply use implode and explode functions of PHP. While saving data, implode it like following:

$key = implode(", ", $_POST['keyboard']);
$tel = new Telegram();
$notice = $tel->AddNew($token,$cat,$ads,$key);

Replace first parameter of implode ", " according to your need.

For displaying use explode like following: $id = explode(", ", $DbRes->keyboard);

Once you convert your array to string then no need for looping inside your class. See updated code of class as below:

<?php 
class Telegram
{   
    protected $notice = array();
    private $db;
    public function __construct()
    {
        $this->db = new Connection();
        $this->db = $this->db->dbConnect();
    }
    public function AddNew($token,$cat,$ads,$key)
    {
        if(!empty($token)&&!empty($cat)&&!empty($ads))
        {

            $new = $this->db->prepare("INSERT INTO channels (token_number, category_name, ads_set, keyboard_status) VALUES (?, ?, ".$ads.", ".$key.")");
            $new->bindParam(1,$token);
            $new->bindParam(2,$cat);
            $new->bindParam(3,$ads);
            $new->bindParam(4,$key);
            $new->execute();
            $notice['success_message'] = "New Telegram Channel was successfully added";
            return $this->notice;
        }
    }
    public function getNotice()
    {
        return $this->notice;
    }
}
?>

This will help you to build your understanding. You need to convert Array to string so that mysql database can store it. This post can also be helpful: Save PHP array to MySQL?



回答2:

Make use of the constructor

First thing first, your addNew function can really be read as "create a new instance of this object", which is really the job of __construct. The other problem here is that the Telegram object has to create multiple instances. However, calling $tel = new Telegram(); implies one and only one instance of the object. Your nested for loops should therefore belong to the script page, os opposed to inside the object.

Refactor the database connection

Currently, your Database connection is being initialized within the object. Now your object has two responsibilities: Managing a Telegram and communicating with the database. I would suggest creating the connection object outside of Telegram and, to stay as Object-Oriented as possible, pass it to the object. This answer explains this part pretty well.

Breaking down some functions

Right now, the constructor of the object is doing two things: it creating an instance of the object, and it is persisting it to the database. Ideally you would want those two process to be decoupled from each other. This allows you to create an instance of Telegram and perform validation on it before it is saved to the database, leaving your constructor nice and clean.

Telegram class:

<?php 
class Telegram
{   
    protected $notice = '';
    private $_token;
    private $_cat;
    private $_ads;
    private $_key

    public function __construct($token, $cat, $ads, $key)
    {
        $this->_token = $token;
        $this->_cat = $cat;
        $this->_ads = $ads;
        $this->_key = $key;
    }

    public function saveToDb(PDO $con)
    {
        $new = $this->con->prepare("INSERT INTO channels (token_number, category_name, ads_set, keyboard_status) VALUES (?, ?, "/*.$ads[$i].*/", "/*.$key[$i].*/")");
        $new->bindParam(1,$this->_token);
        $new->bindParam(2,$this->_cat);
        $new->bindParam(3,$this->_ads);
        $new->bindParam(4,$this->_key);
        $new->execute();
        $this->notice['success_message'] = "New Telegram Channel was successfully added";
        return $this->notice;
    }

    public function getNotice()
    {
        return $this->notice;
    }

    public function getToken()
    {
        return $this->_token;
    }

    public function getCat()
    {
        return $this->_cat;
    }

    public function getAds()
    {
        return $this->_ads;
    }

    public function getKey()
    {
        return $this->_key;
    }
}
?>

Form script:

<?php 
    if(isset($_POST['submit'])){
        $db = new Connection();
        $db = $this->db->dbConnect();

        $token = $_POST['token'];
        $cat = $_POST['cat'];
        $ads = $_POST['ads'];
        $key = $_POST['keyboard'];

        $notices = array();
        if(!empty($token)&&!empty($cat)&&!empty($ads))
        {
            for ($i=0; $i < count($this->_ads); $i++)
            {
                for ($j=0; $j < count($this->_key);$j++)
                {
                    $tel = new Telegram($token, $cat, $ads[$i], $key[$j]);
                    $notices[] = $tel->saveToDb($db); // keep a notice for each object created
                }
            }
        }
    }
?>
<div class='content-wrapper'>
/* ... */


标签: php oop mysqli