0

插入数据库时​​遇到错误,这是我正在使用的代码

class DB_Functions 
{

private $db;

//put your code here
// constructor
function __construct() {
    require_once 'DB_Connect.php';
    // connecting to database
    $this->db = new DB_Connect();
    $this->db->connect();
}

// destructor
function __destruct() {

}

/**
 * Storing new user
 * returns user details
 */
public function storeUnit($email, $unit, $maint, $attent, $done) {
    $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die (mysql_error());
    mysql_select_db(DB_DATABASE, $con);
    $var = mysql_query('select 1 from `table_name`');
    if ($var !== FALSE){
        $format = 'Y-m-d G:i:s';
        $date = date($format);
        mysql_query("CREATE TABLE '$email'( Col1 VARCHAR, Col2 VARCHAR,Col3 VARCHAR, Col4 VARCHAR, Col5 VARCHAR),$con");
        $result =  mysql_query("INSERT INTO '$email'(Col1, Col2 ,Col3 , Col4 , Col5) VALUES('$unit', '$done', '$attent', '$maint', '$date')");
    } else {
        $result = mysql_query("INSERT INTO '$email'(Col1, Col2 ,Col3 , Col4 , Col5) VALUES('$var2', '$var3', '$var4', '$var5', '$date')");
    }

    // check for successful store
    if ($result) {
        // get unit details 
        $uid = mysql_insert_id(); // last inserted id
        $result = mysql_query("SELECT * FROM users WHERE Col1 = $var2");
        // return unit details
        return mysql_fetch_array($result);
    } else {
        return false;
    }
}
4

1 回答 1

3

错误在这里

mysql_query("CREATE TABLE '$email'( Col1 VARCHAR, Col2 VARCHAR,Col3 VARCHAR, 
                 Col4 VARCHAR, Col5 VARCHAR),$con");
                                            ^ this one

变量$con不应包含在字符串中

mysql_query("CREATE TABLE '$email'( Col1 VARCHAR, Col2 VARCHAR,Col3 VARCHAR,
                 Col4 VARCHAR, Col5 VARCHAR)",$con);

另一件事是您创建了一个数据类型的列,varchar但您没有指定其容量。它应该是

CREATE TABLE '$email'( Col1 VARCHAR(50), ....

关于预防的附加信息SQL INJECTION

在 PHP 中防止 SQL 注入的最佳方法

于 2012-10-19T07:04:52.560 回答