php - 检查数据库中是否存在记录

标签 php mysql sql pdo

enter image description here我正在从事另一个类(class)项目,我想做的是检查数据库是否存在一行。

我在论坛上看到了几种不同的方法,但似乎没有一种有效。我在这件事上花了大约 12 个小时,这已经成为一种浪费时间的事情。

这是我尝试过的代码的最后一次迭代:

$ciid = $_POST['categoryid'];

$check = $db->prepare("SELECT categoryid, imgid FROM catType WHERE categoryid = $ciid AND imgid = $imgID ");
    $check->bindParam(categoryid,$ciid);
    $check->bindParam(imgid,$imgID);
    $check->execute();
        if($check->rowCount() > 0 ){
            echo "dqowdhnoqwhd";

            } else {
    /*run working insert */

}

 /* the form that passes the $_POST value */
        echo "<p><input type=\"checkbox\" name=\"catname[]\" value=\"".$row['categoryid']."\" />" . $row['cName'] . " </p>";
        echo "<p><input type=\"hidden\" name=\"".$imgID."\" value=\"".$imgID."\"/></p>"; 

就目前情况而言,我没有收到任何错误,但它也没有告诉我该记录已经在数据库中。当我添加新记录时,它只是复制它。

数组:

Array
(
    [catname] => Array
        (
            [0] => 1
        )

    [111] => 111
    [icud] => update category
)

我在 phpMyAdmin 中运行了查询,公式满足了我的要求。

最佳答案

您的代码(例如 bind_param() 用法)建议您想要使用参数化查询,但您不会在查询中为您尝试绑定(bind)的参数留下任何位置。试试这个:

$ciid = $_POST['categoryid'];

$stmt = $db->prepare("SELECT COUNT(*) FROM catType WHERE categoryid = ? AND imgid = ?");
$stmt->execute(array($ciid, $imgID));
$count = $stmt->fetchColumn();
if($count > 0) {
    echo "dqowdhnoqwhd";
} else {
/*run working insert */
}

来自the documentation的注释关于numRows():

If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

相反,由于您没有从数据库中获取任何有用的内容,因此您只需对匹配的行执行 COUNT() 即可。 fetchColumn() 函数将拉取结果集中下一行的第一列;方便地提取单个值。

关于php - 检查数据库中是否存在记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34280552/

相关文章:

php - Symfony爬虫无法访问twig表单

php - 在sql中查找与html按钮的id具有相同id的记录并生成模态

MySQL - future n天的默认时间戳

sql - 访问另一个数据库中的sys.sql_modules

mysql - 在sql嵌套查询中比较同一个表

php - 使用curl 和访问 token 发布JSON。出现 : Illegally formatted input field! 错误。广告API

php - 确定何时在方法链中调用了最后一个方法

php - Wordpress wp_head() 标题标签不工作

php - Mysql_query 不会将 id 复制到另一行

mysql - INSERT INTO(具有许多列连接的 SELECT(具有更多连接、求和...)、合并、月份...)