我正在尝试通过pdo进行mysql插入。插入工作正常,但我需要一些if else规则,因为pdo对我来说不熟悉所以无法绕过它。
这是插入代码:
$qry = $dbh->prepare(
'INSERT INTO statistics (page, who, ip) VALUES (?, ?, ?)');
$qry->execute(array($pdotitle, $name, $ip));
这可以正确地说明,但我需要制定一个规则,从统计信息中选择行并检查是否已存在具有用户ip的行。
类似的东西:
$ip = $_SERVER['remote_addr']
$qry = $dbh->prepare(
'SELECT * FROM statistics WHERE page = :pdotitle);
$qry->execute(array($pdotitle)');
if (ip == '$ip') { /**do nothing**/ } else { /**do insert**/ }
我该怎么做?
答案 0 :(得分:2)
你可能想到了这个:
$ip = $_SERVER['remote_addr']
$qry = $dbh->prepare(
'SELECT * FROM statistics WHERE page = :pdotitle AND ip = :ip');
$qry->execute(array($pdotitle, $ip));
$row = $qry->fetch();
if (!is_null($row)) { /**do insert**/ }
你应该做的是正确使用SQL。在UNIQUE
列上添加ip
约束,您可以执行
// insert each ip only only and ignore the rest
$qry = $dbh->prepare(
'INSERT IGNORE INTO statistics (page, who, ip) VALUES (?, ?, ?)'
);
// but maybe you really want to keep the table updated
$qry = $dbh->prepare(
'REPLACE INTO statistics (page, who, ip) VALUES (?, ?, ?)'
);