PHP如何检查记录是否存在(PDO)

时间:2018-07-21 11:52:00

标签: php pdo

我尝试在以下记录不存在时进行插入

0

它仍然插入到重复名字的数据库中。并尝试找到here的可接受答案,但我无法使其正常工作。

1 个答案:

答案 0 :(得分:1)

起初,您没有为您的:first_name令牌提供适当的值

// Let's say value to match = $_POST['first_name']

$query = $db->query("SELECT * FROM people WHERE first_name = :first_name");
$statement = $db->prepare($query);

// Specify value to match in the `execute` call
$statement->execute(array(':first_name' => $_POST['first_name']));

//Now try this to confirm if the result is fetched

if ($statement->fetch())
{
    echo "First name Exist";
}

//else it doesn't exist fetch!
else
{
    $query = "INSERT INTO people (first_name, last_name) VALUES (:first_name, :last_name)";
    $statement = $db->prepare($query);
    for($count = 0; $count<count($_POST['hidden_first_name']); $count++)
    {
    $data = array(
    ':first_name' => $_POST['hidden_first_name'][$count],
    ':last_name' => $_POST['hidden_last_name'][$count]
    );
    $statement->execute($data);
    }  
}