在插入php sql之前检查表是否存在

时间:2015-04-15 15:52:42

标签: php mysql sql

我在尝试将数据输入之前检查表是否存在。我正在尝试mysql_query并得到我应该使用mysqli的错误,但它似乎对我不起作用。

到目前为止,这是我的代码:

$AllData = $_POST["table"];
foreach ($AllData as $sigleData) {
    $table = $sigleData['name'];
    $columns = implode(", ", $sigleData['columns']);
    $columnData = implode(" ',' ", $sigleData['data']);

    // Insert into database tuple data      
    $sqlQuery = "INSERT INTO " . $table . " ( " . $columns . ") VALUES( '" . $columnData . "')";


    if ($dbConnectionT->query($sqlQuery) == TRUE) {
        echo "database updated";
        echo "</br>";
    } 
}

2 个答案:

答案 0 :(得分:0)

表名被接受为POST参数,认真!! - 糟糕的做法。 您可以对表存在进行各种检查,如

DESC tbl_name;
SHOW CREATE TABLE tbl_name;
SHOW TABLES like 'tbl_name';

答案 1 :(得分:0)

尝试这种方式使用此自定义函数检查table是否存在,然后insert行到您的数据库。

function check_table_exist($table){
    global $dbConnection; // see here global connection variable
    $sql = "SHOW tables LIKE '".$table."'";
    $res = $dbConnection->query($sql);
    return ($res->num_rows > 0);
}

#check第一个表是否存在

if(check_table_exists($table)){
 $sqlQuery = "INSERT INTO " . $table . " ( " . $columns . ") VALUES( '" . $columnData . "')";
 //do other stuff........
}else{
    echo "Table Not Exists";
    die('Going Out');
 }