开发者

PHP/MySQL - simple tagging system - updating article-tag links?

开发者 https://www.devze.com 2023-03-06 21:34 出处:网络
I want to build a simple tagging system for my news section DB setup (img borrowed from a previous post)

I want to build a simple tagging system for my news section

DB setup (img borrowed from a previous post)

PHP/MySQL - simple tagging system - updating article-tag links?

On my "Edit Article" screen, there are now tags sitting in an input field and the user can delete or type new tags. All good.

But when the page is submitted and I get this array of tag values, I'm thinking that I have to check each one against the 'Tag' table to see if it exists or not.

Is there any shortcut way of doing this or is it 开发者_如何转开发somehow possible to pass through tag_id=>tag_value? So far none of the preferred jQuery libraries seem to offer that: one, two


You should always check the submitted data on the server side as well. If you are using MYSQL, you can try this:

$sql = "SELECT a.* FROM (";
$first = true;
foreach( $submitted_tag_array as $v ) {
    $v = mysql_real_escape_string($v);
    $sql .= $first
        ? "\n\tSELECT '$v' AS tag"
        : "\n\tUNION ALL SELECT '$v'";
    $first = false;
}

$sql .= "\n) AS a"
    ."\nLEFT JOIN [tag] t ON t.tag_id = a.tag"
    ."\nWHERE t.tag_id IS NULL";

$result = mysql_query($sql);

if( $row = mysql_fetch_assoc($result) ) {
    // We found atleast one tag that doesn't exist in the database! Do something about it!
}

The above code assumes you get an array of tag_id's in the submit. If you instead get tag names, you just have to change

."\nLEFT JOIN [tag] t ON t.tag_name = a.tag"
0

精彩评论

暂无评论...
验证码 换一张
取 消