php - PDO数据库用户存在控制

标签 php mysql pdo php-7

if(isset($_GET['id'])){
    $nome = $_GET['nome'];
    $cognome = $_GET['cognome'];
    $id = $_GET['id'];
    $sql = "UPDATE utenti SET nome = :nome, cognome = :cognome WHERE id = :id";
    $req = $dbh->prepare($sql);
    $req->execute(
        array(
            ":nome" => $nome,
            ":cognome" => $cognome,
            ":id" => $id,
            )
        );
} else {
    $nome = $_GET['nome'];
    $cognome = $_GET['cognome'];
    $sql = "INSERT INTO utenti (nome, cognome) VALUES (:nome, :cognome)";
    $req = $dbh->prepare($sql);
    $req->execute(
        array(
            ":nome" => $nome,
            ":cognome" => $cognome,
            )
        );
}

大家好。我有这段代码,可以在数据库中插入或更新表单的数据。我想包括一个“if”检查,以确保您正在检查该用户是否已存在于数据库中。我能怎么做?谢谢

最佳答案

试试这个:

               $nome = $_GET['nome'];
            //Searching the nome in the database
                    $req = $dbh->prepare("SELECT COUNT(*) AS anzahl FROM user WHERE Benutzername = :nome");
            //Counts the rows with the given nom
                    $req->bindParam(':nome', $nome, PDO::PARAM_STR);
                    $req->execute();
                    $result = $req->fetch();
                    if ($result[0] > 0) {
            //already exists - A row was found 
                        echo "Already exists";
                    }
                    else {
            //not existing - There was no row with that username
                     "Your Insertquery, use $req2 here"
                    }

编辑 2:现在应该可以工作了 ^^

关于php - PDO数据库用户存在控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47176347/

相关文章:

php - 将 URL 传递到联系表单

php - 如何根据今天的日期和截止日期选择行

php - 数据库未更新 - php PDO

php - 从非 XML 文档进行 XML 解析

php - WooCommerce 可变产品 : keep only "min" price with a custom label

mysql - 优化GROUP BY&ORDER BY查询

php - 为什么我的订阅页面没有将字段放入 MySQL 数据库中?

php - 提交按钮更新查询

PHP 将 vars 发布到 var 名称可以使用 PDO 吗?

php - SQLSTATE[42000] : Syntax error or access violation: 1064 Error in setting Variable in bindparam