我的MySQL查询一直失败,我无法理解为什么,我读了它,显然我错过了表名等的反引号(`),所以我添加了它们而没有变化。这是代码:
$db = new PDO("mysql:host=".$db_host.";db_name=".db_name, $db_user, $db_pass);
try{
$check = $db->prepare("SELECT `userID` from `userData` WHERE `userID` = :accountID");
$check->bindParam(':accountID', $accid, PDO::PARAM_INT);
$check->execute();
if(!$check->execute()){
die(var_dump($db->errorInfo()));
}else{
if($check->rowCount() > 0) {
$creditsQuery = $db->prepare("SELECT `userCredits` FROM `userData` WHERE `userID` = :accountID3");
$creditsQuery->bindParam(":accountID3", $accid, PDO::PARAM_INT);
$creditsQuery->execute();
//Set Credits To Variable From Database Column
$credits = $creditsQuery->fetch(PDO::FETCH_ASSOC);
}else{
$sql = $db->prepare("INSERT INTO `userData` (`userID`, `userCredits`) VALUES (:accountID2, '0')");
$sql->bindParam(':accountID2', $accid, PDO::PARAM_INT);
$sql->execute();
if(!$sql){
die('Server Error: 404Insert, Please Contact A Member Of Staff If This Error Continues.');
}
}
}
}catch(PDOException $e){
die ("Server Error: 404Connection, Please Contact A Member Of Staff If This Error Continues.");
}
errorInfo行显示:array(3){[0] => string(5)" 00000" [1] => NULL [2] => NULL}
因此,数据库成功连接,因为try块不会抛出异常。所以我真的不知道。
感谢,
马特
答案 0 :(得分:1)
您的代码中有几处错误
$accid
不包含值bindParam
而不是bindValue
- 它们之间存在差异,非常重要请阅读我发布的代码的评论,并根据您的需要进行调整:
<?php
/**
* Create PDO object and set it into exception mode
*/
try {
$db = new PDO("mysql:host=".$db_host.";db_name=".db_name, $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
try {
// Replace with actual value
$user_id = 1;
// Pay close attention to IGNORE keyword - it's extremely important
// and it requires a unique index to be placed on userID column
// I assumed that userID is primary key
$query = "INSERT IGNORE INTO userData (userID, userCredits) VALUES (:userID, 0)";
$stmt = $db->prepare($query);
$stmt->bindValue(':userID', $user_id);
$stmt->execute();
} catch(PDOException $e) {
echo 'An error occurred: '. $e->getMessage();
}