Php创建然后插入数据错误

时间:2012-10-19 07:02:47

标签: php mysql

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

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

1 个答案:

答案 0 :(得分: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的其他信息:

Best way to prevent SQL injection in PHP