Joomla使用JDatabase插入数据,其中表名存储在php变量中

时间:2016-06-13 09:35:12

标签: php mysql joomla

描述:我创建的数据库名称自动由主表名组成,并附加相对于下拉菜单中所选内容的全名。

代码:

       if ($leagueSelect === $result['leagueName'] && $divisionSelect === $result['divisionID'] && $tourType === 'robin') {

            $tableName = "footleague_".$leagueSelect.$divisionSelect;
            /****CREATE TABLE****/

            $db = JFactory::getDBO();
            $query = $db->getQuery(true);

            $query = "CREATE TABLE IF NOT EXISTS `".( $tableName )."` (
                        `id` INT(11) NOT NULL AUTO_INCREMENT,
                        `round` TEXT NULL,
                        `logoHome` TEXT NULL,
                        `home` TEXT NULL,
                        `usrHome` TEXT NULL,
                        `scoreHome` INT(11) NULL,
                        `scoreAway` INT(11) NULL,
                        `logoAway` TEXT NULL,
                        `away` TEXT NULL,
                        `usrAway` TEXT NULL,
                        `confirm` INT(11),
                      PRIMARY KEY (`id`)
                )";

            $db->setQuery($query);

            $result = $db->execute();

            if ($result == true) {
                echo 'Table created successfully!';    
            }else{
                echo "Something went wrong with table creation. Please try again.";
            } 
    }

这非常有效,它会创建一个新表和所有列。 将数据存储到此表时会出现问题。我需要能够获取存储在变量中的表名并将数据存储到其中。与CREATE TABLE中相同。

我试过这样:

    $query = "INSERT INTO ".$tableName." (round, logoHome, home, usrHome, logoAway, away, usrAway),
                              VALUES ('".$round."' , '".$logoHome."' , '".$home."' , '".$usrHome."' , '".$logoAway."' , '".$away."' , '".$usrAway."')";

                    $db->setQuery($query);

                    $result = $db->execute();

...但它没有给我任何错误,也没有存储数据。

我也尝试过使用stdClass对象,但我不知道如何获取表名:

    $data = new stdClass();
    $data->round = $round;
    $data->home = $home;
    $data->usrHome = $usrHome;
    $data->logoHome = $logoHome;
    $data->away = $away;
    $data->usrAway = $usrAway;
    $data->logoAway = $logoAway;

    $db = JFactory::getDBO();
    $db->insertObject($tableName, $data);

我怎样才能让它发挥作用?

谢谢。

1 个答案:

答案 0 :(得分:0)

我解决了这个问题:

    $data = new stdClass();
    $data->round = $round;
    $data->home = $home;
    $data->usrHome = $usrHome;
    $data->logoHome = $logoHome;
    $data->away = $away;
    $data->usrAway = $usrAway;
    $data->logoAway = $logoAway;

    $db = JFactory::getDBO();
    $db->insertObject($tableName, $data);

    if ($result == true) {
         echo 'Tournament was created successfully!';
    }else{
         echo 'ERROR!';
    }