PHP&;MySQL问题

PHP&;MySQL问题,php,mysql,Php,Mysql,我想知道如何从数组中检查一个值,看看它是否在数据库中,如果它没有再次添加到数据库中。如何使用PHP和MySQL实现这一点 PHP代码 for ($x = 0; $x < count($cat_id); $x++){ $cat_query = "INSERT INTO posts_categories (category_id, post_id, date_created) VALUES ('" . mysqli_real_escape_string($mysqli, strip_t

我想知道如何从数组中检查一个值,看看它是否在数据库中,如果它没有再次添加到数据库中。如何使用PHP和MySQL实现这一点

PHP代码

for ($x = 0; $x < count($cat_id); $x++){
    $cat_query = "INSERT INTO posts_categories (category_id, post_id, date_created) VALUES ('" . mysqli_real_escape_string($mysqli, strip_tags($cat_id[$x])) . "', '" . mysqli_real_escape_string($mysqli, strip_tags($post_id)) . "', NOW())";
}
    if(isset($cat_id)){

        for($x = 0; $x < count($cat_id); $x++){
            $check_query = mysqli_query($mysqli,"SELECT category_id FROM posts_categories WHERE category_id = '" . $cat_id[$x] ."' AND post_id = '" . $post_id . "'");

            if ($check_query == TRUE) {
                unset($cat_id[$x]);
            }
        }


        for($x = 0; $x < count($cat_id); $x++){
            $cat_query = "INSERT INTO posts_categories (category_id, post_id, date_created) VALUES ('" . mysqli_real_escape_string($mysqli, strip_tags($cat_id[$x])) . "', '" . mysqli_real_escape_string($mysqli, strip_tags($post_id)) . "', NOW())";
        }
    }
for($x=0;$x
修改PHP代码

    if(isset($cat_id)){

        for($x = 0; $x < count($cat_id); $x++){
            $check_query = mysqli_query($mysqli,"SELECT category_id FROM posts_categories WHERE category_id = '" . $cat_id[$x] ."' AND post_id = '" . $post_id . "'");

            if ($check_query == TRUE) {
                unset($cat_id[$x]);
            }
        }


        for($x = 0; $x < count($cat_id); $x++){
            $cat_query = "INSERT INTO posts_categories (category_id, post_id, date_created) VALUES ('" . mysqli_real_escape_string($mysqli, strip_tags($cat_id[$x])) . "', '" . mysqli_real_escape_string($mysqli, strip_tags($post_id)) . "', NOW())";
        }
    }
if(isset($cat_id)){
对于($x=0;$x
您可以使用。

当您使用mysqli时,您可能应该使用准备好的语句(从安全性和性能的角度来看)


注意:我还使用了INSERT IGNORE,因此如果键存在,则INSERT将自动失败。

这会阻止我添加或更新表行吗?不,它会告诉MySql您想插入一行,但如果它已经存在(根据主键确定,在这种情况下可能应该是
category\u id
+
post\u id
),它不应尝试插入新记录,而应更新现有记录。您通常会在查询的更新部分更新列
updated\u at
或类似内容。我希望停止添加或更新具有重复值的表行。存在INSERT IGNORE。。(见下文)啊是-
插入。。“忽略”
在这种情况下可能更好。新发布的代码与您的代码不完全匹配,这是我在尝试新事物时最熟悉的地方。当然,这是行不通的。。他正在使用mysqli,而您已经发布了一个MySQLIB示例!哦,我发帖的时候没说清楚。mysqli中肯定有类似/相同的功能吗?
$stmt   =   $mysqli->prepare("INSERT IGNORE INTO posts_categories (category_id, post_id, date_created) VALUES (?, ?, ?)");

// Should use a prepared statement here.
foreach ($categories as $key => $cat) {

    // Bind params
    $stmt->bind_param('iis', $cat, $post_id, 'NOW()');

    // Exectute the query
    $stmt->execute();
}

// Close the connection!
$mysqli->close();