PDO rowCount和fetchColumn均未返回正确的结果 [英] PDO rowCount and fetchColumn both not returning correct result

查看:125
本文介绍了PDO rowCount和fetchColumn均未返回正确的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了各种方法来使这段简短的代码起作用.它的作用是通过PDO连接到数据库,然后选择与post变量匹配的所有行.如果行数超过0,则将许可证密钥行更新为已使用"并回显true.

I've tried various things to get this short bit of code to work. What it does is it connects to the database via PDO and then selects all rows that match a post variable. If there is more than 0 rows, update the licensekey rows to be "used" and echo true.

我已经尝试了rowcount和fetchcolumn以及sql的count(*),但都没有显示出任何差异.在MySQL本身中,我使用了有效的许可证密钥,它确实返回了一行.

I have tried both rowcount and fetchcolumn and count(*) for sql, and none of shown any differences. In MySQL itself, I have used a valid licensekey and it indeed returns one row.

<?php
if(isset($_POST['licensekey'])) {

try {
    $db = new PDO("mysql:host=localhost;dbname=validation", "test", "test");
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die($e->getMessage());
}

$search = ("SELECT * FROM validated WHERE activationkey=:lk AND used='0'");
$result = $db->prepare($search);
$result->bindParam(":lk", $_POST['licensekey']);
$result->execute();

if($result->rowCount() > 0) {
    $used = ("UPDATE validated SET used='1' WHERE validated.activationkey=:lk");
    $result2 = $db->prepare($used);
    $result2->bindParam(":lk", $_POST['licensekey']);
    $result2->execute();

    echo "true";
} else {
    echo "false";
}

$db = null;
} else {
    exit();
}
?>

无论何时,每次都会返回false.

Every time it will return false no matter what.

这里似乎是什么问题?

推荐答案

实际上,您看不到在具有rowCount函数的数据库中选择了多少条记录.正如我在PHP文档中所读到的那样,许多选择查询不会返回受rowCount方法查询影响的行数.检查它以获取更多信息: http://php.net/manual/zh/pdostatement.rowcount .php

Actually you can't see how many records selected in DB with rowCount function. As i read in PHP Documentation many of select queries doesn't return how many rows affected by query with rowCount method. Check it for more information : http://php.net/manual/en/pdostatement.rowcount.php

如文档所述,您可以使用fetchColumn方法.

As doc says you can use fetchColumn method.

这篇关于PDO rowCount和fetchColumn均未返回正确的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆