如何使用 PHP OOP 插入多个单选按钮值

Posted

技术标签:

【中文标题】如何使用 PHP OOP 插入多个单选按钮值【英文标题】:How to insert multiple radio button values with PHP OOP 【发布时间】:2018-03-06 09:23:14 【问题描述】:

我正在使用CMSphp OOP。在这个项目中,用户可以添加新的 Telegram 频道。对于此功能,我添加了此表单,其中还包含操作代码:

    <?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>

正如你在顶部所看到的,我调用了一个名为 Telegram.class.php 的类,这个类是这样的:

    <?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;
    

?>

因为我想在表格中添加多个复选框,所以我在方法Add_New中使用了这个for循环(根据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;
            
        

我知道这不正确,但我不知道将这些 $ads[$i]$key[$i] 变量添加到插入语句...

如果您知道如何按正确的顺序执行此操作,请告诉我.. 谢谢!

【问题讨论】:

【参考方案1】:

利用构造函数

首先,您的addNew 函数可以真正理解为“创建此对象的新实例”,这确实是__construct 的工作。这里的另一个问题是Telegram 对象必须创建多个实例。但是,调用$tel = new Telegram(); 意味着只有一个 对象实例。因此,您嵌套的 for 循环应该属于脚本页面,而不是对象内部。

重构数据库连接

目前,您的数据库连接正在对象内初始化。现在您的对象有两个职责:管理电报和与数据库通信。我建议在 Telegram 之外创建连接对象,并尽可能保持面向对象,将其传递给对象。 This answer 很好地解释了这部分。

分解一些功能

现在,对象的构造函数正在做两件事:创建对象的实例,并将其持久化到数据库中。理想情况下,您希望这两个进程彼此分离。这允许您创建Telegram 的实例并在将其保存到数据库之前对其执行验证,从而使您的构造函数保持整洁。

电报类:

<?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;
    

?>

表单脚本:

<?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'>
/* ... */

【讨论】:

【参考方案2】:

简单地使用 PHP 的 implode 和 explode 函数。在保存数据时,像下面这样内爆它:

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

根据需要替换 implode ", " 的第一个参数。

为了显示使用爆炸如下: $id = explode(", ", $DbRes->keyboard);

一旦将数组转换为字符串,就无需在类中循环。查看更新的类代码如下:

<?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;
    

?>

这将帮助您加深理解。您需要将数组转换为字符串,以便 mysql 数据库可以存储它。这篇文章也有帮助:Save PHP array to MySQL?

【讨论】:

那么类呢,类文件没有变化? 是的,课程将被更改。如果值已转换为字符串,则无需在数组上循环。答案已更新。

以上是关于如何使用 PHP OOP 插入多个单选按钮值的主要内容,如果未能解决你的问题,请参考以下文章

如何从 PHP 中的单选按钮发送值属性 [关闭]

如何通过 PHP 将多个单选按钮值作为所有单独的值传递给 MYSQL 数据库,但将它们分成组?

如何在 PHP 中使用 AJAX 获取选中的单选按钮值?

如何从多个单选组传递单选按钮值?如何解决返回第一个值?

如何使用 Javascript 和 Ajax 将 HTML 单选按钮值传递给 PHP 变量?

如何使单选按钮返回布尔值真/假而不是开/关