在我之前检查过一个值之后,如何设置更改SQL DB中的字段?

时间:2016-05-17 15:39:31

标签: php mysql pdo

enter image description here

因此。我有这张桌子。在我检查代码(例如1234)中存在代码后,我正在尝试将可用性字段的值从0更新为1.

以下是我写的代码:

<?php 
if(isset($_POST['kodi'])) {
try {
$sql = "SELECT codevalue FROM codes WHERE codevalue = ? AND availability = 0";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(1, $_POST['kodi']);
$stmt->execute(); }
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();}

if($stmt->rowCount() > 0){
header('Location: http://mysite/userpage');
$q = "UPDATE codes SET availability = '1' WHERE codevalue= ?";
$stmt->bindParam(1, $_POST['kodi']);
$stmt = $dbh->prepare($q);
$stmt->execute($q);} else {
echo "Code Not Exists"; }

带有$ dbh变量的部分:

$dbh = new PDO("mysql:host=$hostname;dbname=x",$username,$password);

HTML:

<form action ="thispage.php" method ="POST">
<input name="kodi" type="text" class="form-control" placeholder="Enter Code" aria-describedby="basic-addon1">
</form>

当我尝试它时,它会重定向到我的用户页面,但字段可用性仍为0.

1 个答案:

答案 0 :(得分:1)

if(isset($_POST['kodi'])) {
$sql = "SELECT codevalue FROM codes WHERE codevalue = ? AND availability = 0";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(1, $_POST['kodi']);
$stmt->execute();
$result = $stmt->fetchAll();
if(!empty($result)) {
header('Location: http://mysite/userpage');
$q = "UPDATE codes SET availability = '1' WHERE codevalue= ? AND availability = 0";
$stmt->bindParam(1, $_POST['kodi']);
$stmt = $dbh->prepare($q);
$stmt->execute($q);
} else {
echo "Code Not Exists"; 
} 
}