PHP MySQL : How to determine if value already exists in database

标签 php mysql pdo parameterized-query

我有一个表单按钮,我需要根据用户输入以及该输入是否已存在于我的数据库中来执行两项不同的操作。如果输入不存在,则该按钮将创建一条新记录。如果确实存在,则现有记录将被更新。

这是我现在的 PDO 查询:

/* First, we need to discover whether the Proposal No. entered already exists in the
database. If it doesn't, then a new record will be created. If                                                                            
it does, then an existing record will be updated. */
$pNoExists = $con->prepare("SELECT ProposalNo FROM ptfp1"); 
$pNoExists->execute();
$row = $pNoExists->fetch(PDO::FETCH_ASSOC);

当我运行 $row = $pNoExists->fetch(PDO::FETCH_ASSOC); 时通过 while 循环,该字段的所有值都存在。现在我只需要一些关于如何在按钮设置中使用它的指导。这就是我想做的:

if($_POST['ButtonPush'] && input doesn't exist) {
  Create new record;
}
else {
  Update existing record;
}

很简单,对吧?但它却让我无法理解。

最佳答案

鉴于你所拥有的,我会做:

if($_POST['ButtonPush'] && array_search($all_values, $input_value)) {
    Create new
}
else {
    Update
}

但是,就像上面的评论一样,您可能只想在“SELECT”语句中添加一个 where 子句,这样您就不会每次都获取整个数据库表内容。而且,甚至可以将 SELECT 转换为 SELECT COUNT 以减少请求的数据量。

关于PHP MySQL : How to determine if value already exists in database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19037404/

相关文章:

php - 从两个 mysql 表中获取数据,其中一个表的行连接到另一个表中的许多行

mysql - 如何在mysql主表的单个查询中连接关系表中的值

MySQL 使用 * 以及连接表中的列名

mysql - 计算mysql View 中的单词数

php - 不带变量的 pdo 插入

php - 使用 PHP/MySQL,如何从具有多值列内容的表中进行选择

php - 如何在 PHP 中将 csv 数据插入 mysql 数据库

php - MySQL 语法根据混合变量以及从另一个表中选择记录来插入新行

php - PDO rowCount() 适用于 MySQL 但不适用于 SQL Server 2008 R2

php - UNIQUE 用户名列未更新