CodeIgniter:如何在输入之前检查重复的数据库表? [英] CodeIgniter: how do I check DB table for duplicates before entry?

查看:98
本文介绍了CodeIgniter:如何在输入之前检查重复的数据库表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个小应用程序,将csv文件的内容写入CodeIgniter的数据库,但我在写入之前检查dupes有困难。因为这是一个相当普遍的任务,我想知道一些专业人士(你)是如何做到的。对于上下文和比较,这里是我的(当前不工作)代码:

I'm writing a small application that will write the contents of a csv file to a database in CodeIgniter, but I'm having difficulty checking for dupes before write. Since this is a fairly common task, I was wondering how some of the professionals (you) do it. For context and comparison, here is my (currently non-working) code:

        $sql = "SELECT * FROM salesperson WHERE salesperson_name='" . $csvarray['salesperson_name'][$i] . "'";
        $already_exists = $this->db->query($sql); 

        if (sizeof($already_exists) > 0) {

            //add to database

        }

任何输入只是你吸! (我已经听到从我自己的大脑两个小时在这一点上)将非常感谢。感谢。

Any input at all short of "You suck!" (I already hear that from my own brain twice an hour at this point) will be greatly appreciated. Thanks.

推荐答案

你正在做什么工作,但如上所述比较应该是== 0 0。

What you're doing will work, but as above the comparison should be "== 0" not "> 0".

您也可以使用在num_rows方法中构建的CodeIgniters,而不是使用sizeof,如下所示:

You can also use CodeIgniters built in num_rows method instead of using sizeof, like so:

$sql = "your query";
$query = $this->db->query($sql);

if ($query->num_rows() == 0) {
  // no duplicates found, add new record
}

注意,如果你使用CodeIgniter,那么使用Active Record来构建你的查询而不是编写SQL是值得的。您可以在此处了解详情: CodeIgniter - Active Record

As a side note, if you're using CodeIgniter then it's worthwhile to use Active Record to build your queries instead of writing SQL. You can learn more about it here: CodeIgniter - Active Record

这篇关于CodeIgniter:如何在输入之前检查重复的数据库表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆