douqi1625 2014-05-05 17:45
浏览 62
已采纳

如果记录不存在,我怎么才能插入记录?

I am currently making a simple IP banning script and I am at the stage of inserting the IP address into the database. The HTML form I created for this consists of two fields; the IP address and a reason:

<td width="70%"><h4>Ban New IP:</h4>(Enter IP to be banned)</td>
    <td width="30%">
    <form method="post" action="">
     IP Address: <input type="text" id="ip" name="ip" autocomplete="off" maxlength="15" /><br /><br />
     Enter Reason: <input type="text" id="reason" name="reason" autocomplete="off" maxlength="255" /><br /><br />
     <input type="submit" id="submit" name="submit" value="Ban IP" /><br /><br />

My database contains one table titled banned_ips and three columns id, ip and reason. The insert statement I have created works perfectly however I want to check to see if the IP already exists. At the moment it will just insert the IP even if there is one matching it. This is my current query:

<?php

if ($_POST) {
    if ($_POST['ip'] != '') {
        if (strlen($_POST['ip']) <= 15) {
            $ip = $_POST['ip'];

            $ip_clean = htmlentities($ip);

            if (isset($ip_clean)) {
                // SQL insert
                $insert_ip = $db->prepare("INSERT INTO `banned_ips` (ip) VALUES (?)");
                $insert_ip->bind_param('s', $ip_clean);

                if ($insert_ip->execute()) {
                    // Successful insert
                    $_SESSION['successful_insert'] = 'Success';
                }
            }
        }
    }
}

 ?>

What I would like to do is check to see if the IP address already exists when they go to insert a new IP. I have looked at other questions asked here on stackoverflow and a lot of the time I saw WHERE NOT EXISTS however none that I found showed any examples with prepared statements.

  • 写回答

3条回答 默认 最新

  • dqd22496 2014-05-05 17:49
    关注

    Just make ip field a unique field.

    mysql will then prevent duplication

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器