MySql查询 - 检查数据是否存在,如果是,则获取id,如果没有,则添加数据并获取id

时间:2015-01-31 07:08:57

标签: php mysql mysqli

我可以用php / mysqli执行多步骤。

所以,表只有两列 ID,名称

两者都是独一无二的 我想检查数据库中是否有Name,如果可用则获取ID 如果它不可用,请在数据库中添加Name并获取ID。

我可以使用需要多个sql查询的php / mysql来实现 是否有办法(检查数据库,如果不存在,添加它并获取ID)只有一个mysql查询并获取ID?

提前致谢!

我的代码(MySQLi程序)

function abc($name) {
    global $conn;
    $checkName = mysqli_query($con,"SELECT * FROM category WHERE name=".mysql_real_escape_string($name));
    if (mysqli_num_rows($checkName) > 0) {
        $inputName = mysqli_query($con,"INSERT INTO category (name) VALUES ('".mysql_real_escape_string($name)."')");
        if (!$inputName) { die(mysqli_error($conn)); }
        $checkName2 = mysqli_query($con,"SELECT * FROM category WHERE name=".mysql_real_escape_string($name));
        while($blahblah = mysqli_fetch_assoc($checkName2)) {
            $returnData[] = $blahblah;
        }
    } else {
        while($blahblah = mysqli_fetch_assoc($checkName)) {
            $returnData[] = $blahblah;
        }
    }
    return $blahblah;
}

2 个答案:

答案 0 :(得分:1)

只需一行就可以完成。使用" INSERT IGNORE INTO .."或者"替换为......"。 This页面引用。

答案 1 :(得分:0)

如果你使用面向对象的MySQLi,你就是这样做的:

$mysqli = new mysqli(...);
$name = "Something";

$query = $mysqli->prepare("SELECT id, name FROM table WHERE name=?");
$query->bind_param('s', $something);
$query->execute();
$query->bind_result($id, $name);
$query->store_result();
if($query->num_rows == 1) {
    return $id;
} else {
    $queryTwo = $this->mysqli->prepare("INSERT INTO table VALUES('', ?);");
    $queryTwo->bind_param('s', $name);
    $queryTwo->execute();
    $queryTwo->close();

    $queryThree = $this->mysqli->prepare("SELECT id FROM table WHERE name=?");
    $queryThree->bind_param('s', $name);
    $queryThree->execute();
    $queryThree->bind_result($id);
    $queryThree->store_result();
    while($queryThree->fetch()) {
        return $id;
    }
    $queryThree->free_result();
    $queryThree->close();
}
$query->free_result();
$query->close();