PDO检查数据是否存在(如果不存在)

时间:2016-07-03 15:13:45

标签: php ajax function pdo

所以我想要的是我想检查一下这个人是否已经使用了代码,如果已经使用过,那么它应该死掉,否则设置来自$_POST['code']的数据并锁定它,所以它不能再改变 - (但只能删除数据库中的数据)

数据库名称=用户

在用户中,我有一个使用code_used

的结构设置
<?php
session_start();
include ('assets/includes/include.php');

if(isset($_POST['code'])) {
$SQLCheckExistens = $odb -> prepare("SELECT COUNT(*) FROM `users` WHERE `code_used` = :code");
$SQLCheckExistens -> execute(array(':code' => $_POST['code']));
$countCodes = $SQLCheckExistens -> fetchColumn(0);

if($countCodes = 0) {
    $SQLRedeemCode = $odb -> prepare("UPDATE `users` SET `code_used` = :code WHERE `steamid` = :SteamID");
    $SQLRedeemCode -> execute(array(':code' => $_POST['code'], ':SteamID' => $_SESSION['steamid']));

    die('Saved successfully!');
} else { 
    die('Error. You have already redeemed a code.'); 
}   
} else {
die();
}
?>

这是ajax

<script>            
function SetCode() {
var code = document.getElementById('code').value;

$.ajax( {
    type: 'post',
    url: 'redeem.php',
    data: "code=" + code,
    success: function(response) {
        console.log(response);
        document.getElementById('data_response').innerHTML = response;          
    }
});
}

这是函数

function getCode($UserID, $odb)
{
    $SQLUserInfo = $odb -> prepare("SELECT * FROM `users` WHERE `steamid` = :SteamID");
    $SQLUserInfo -> execute(array(':SteamID' => $UserID));
    $UserInfo = $SQLUserInfo->fetch(PDO::FETCH_ASSOC);

    return $UserInfo['code_used'];
}

1 个答案:

答案 0 :(得分:1)

您正在尝试为if语句分配一个值,该语句将在您的情况下返回true。它应该是:

if($countCodes == 0) { // UPDATE SQL ...

尝试使用MySQL返回的COUNT。或者,您可以使用PDOStatement::rowCount

$SQLCheckExistens = $odb -> prepare("SELECT COUNT(*) FROM `users` WHERE `code_used` = :code");
$SQLCheckExistens -> execute(array(':code' => $_POST['code']));
$result = $SQLCheckExistens -> fetch(PDO::FETCH_NUM);
$countCodes = $result[0];