2014-03-13 68 views
0

我新的PHP和MySQL,我想在一个数据库中,已经工作得很好,直到我试图使用PDO的准备方法插入数据。它返回捕获错误,我不明白为什么 - 我也想知道是否最好的做法是使用未命名的占位符或命名的占位符?将数据插入MySQL数据库使用PDO

用户名和密码变量在我的代码和数据捕获从较早使用$_POST用户定义的。

编辑:的getMessage()错误显示SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'username' cannot be null

if (!empty($user) && (!empty($password))) { 
    try { 
     $results = $db->prepare("INSERT INTO user_info (username, pass) VALUES (?,?)"); 
     $results->bindParam(1,$username); 
     $results->bindParam(2,$password); 
     $results->execute(); 
    } catch (Exception $e) { 
     echo "Could not insert data in to the database"; 
    } 
} 
+0

'回声$ E->的getMessage();'看看是什么错误。 – xdazz

+0

SQLSTATE [23000]:完整性约束冲突: –

+0

你引用'$ user'然后引用'$ username' 1048列 '用户名' 不能为空。这是什么? – JBES

回答

0

你有两个不同的变量名。你检查$user,以确保它不是empty()但后来你告诉绑定$username第一个参数。你只需要重命名其中的一个来匹配其他的。

0

试试这一个。

if (!empty($user) && (!empty($password))) { 
try { 
    $results = $db->prepare("INSERT INTO user_info (username, pass) VALUES (?,?)"); 
    $results->bindParam(1,$user); 
    $results->bindParam(2,$password); 
    $results->execute(); 
} catch (Exception $e) { 
    echo "Could not insert data in to the database"; 
} 

}

请先尝试自己查找错误。