无法使用变量字符串MYSQL错误获得表名

时间:2018-10-01 21:36:20

标签: php mysql database pdo

 if ($_GET['category'] == "ebooks")
{ $tableName = $smallsubcodewithoutspace.'_ebooks';
  $sectionTitle = "Ebook";
}
elseif ($_GET['category'] == "syllabus")
{ $tableName = $smallsubcodewithoutspace.'_syllabus';
  $sectionTitle = "Syllabus";
}
elseif ($_GET['category'] == "pnotes")
{ $tableName = $smallsubcodewithoutspace.'_pnotes';
  $sectionTitle = "Practical Note";
}
elseif ($_GET['category'] == "assignments")
{ $tableName = $smallsubcodewithoutspace.'_assignments';
  $sectionTitle = "Assignment";
}
elseif ($_GET['category'] == "tnotes")
{ $tableName = $smallsubcodewithoutspace.'_tnotes';
  $sectionTitle = "Theory Notes";
}

//if form has been submitted process it
    if(isset($_POST['submit'])){

        $_POST = array_map( 'stripslashes', $_POST );

        //collect form data
        extract($_POST);

        //very basic validation
        if($contentTitle ==''){
            $error[] = 'Please enter the Content Title !';
        }



        if($contentLink ==''){
            $error[] = "Please enter the Content Link !";
        }

        if(!isset($error)){

            try {

                //insert into database
                $stmt = $db->prepare("INSERT INTO `$tableName` (contentTitle,contentLink,contentAuthor) VALUES (:contentTitle, :contentLink, :contentAuthor)") ;
                $stmt->execute(array(
                    ':contentTitle' => $contentTitle,
                    ':contentLink' => $contentLink,
                                        ':contentAuthor' => $contentAuthor
                ));

                //redirect to index page
                header('Location: add-content.php?notallowed=true');
                exit;

            } catch(PDOException $e) {
                echo $e->getMessage();
            }

        }

    }

    //check for any errors
    if(isset($error)){
        foreach($error as $error){
            echo '<div align="center" class="alertpk"><div class="alert alert-warning" role="alert">'.$error.'</div></div>';
        }
    }

实际上,当我尝试使用变量插入表名称时,问题就开始了。表存在于数据库中。总共有5个数据库,我将根据用户选择在其中插入数据,但是在执行表单时,会抛出一个错误:

  

SQLstate [42000]:语法错误或访问冲突1103,表名''

不正确

3 个答案:

答案 0 :(得分:0)

错误INCORRECT TABLE NAME ''错误表示您在$tableName中没有值。您的$_GET['category']未获取可识别的值,或者extract($_POST)正在将$tableName更改为空值。

答案 1 :(得分:0)

我找到了解决方案,我在try中移动了tableVariables部分,现在可以使用了。

答案 2 :(得分:-1)

var转储您的变量,发布以查看出现了什么值。