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/