开发者

PHP & MySQL problem

Okay I'm us开发者_JS百科ing strip_tags to get rid of html from when a user tags a post but when a user enters something like in the upcoming example.

I get five empty values entered into the database, which I don't want everything else is fine. How can i stop this?

,,,,,,,, ,, ,,,,a,d, <html> , ruby-on-rails , ad, <html>

I get the following entered into the database NOTE the commas are not entered into the database.

, , , a, d, , ruby-on-rails, ad, 

Here is my code.

$tags = preg_split('/,/', strip_tags($_POST['tag']), -1, PREG_SPLIT_NO_EMPTY);
$tags = array_map('trim', $tags);
$tags = str_replace(' ', '-', $tags);

ONLY the following should be entered into the database.

a,d,ruby-on-rails,ad 

Here is a quick example of my insert.

 for ($x = 0; $x < count($tags); $x++){
    $query1 = "INSERT INTO tags (tag) VALUES ('" . mysqli_real_escape_string($mysqli, strtolower($tags[$x])) . "')";
}


You should check if the values are empty(). If they are, omit them from your database insert query or mark them as "null".

Without seeing the database table design or any code that has to deal with the database, it is hard to say how we can better help you.

UPDATE

With the new information from the INSERT query, here is how you would apply the empty (untested pending syntax errors):

$tags = array_filter($tags, function ($v) { return !empty($v);});

for ($x = 0; $x < count($tags); $x++){
    $query1 = "INSERT INTO tags (tag) VALUES ('" . mysqli_real_escape_string($mysqli, strtolower($tags[$x])) . "')";
}

Should remove the empty values from the array, pending I did not make a simple mistake.

EDIT

Here is one option to do it, but yea. Since you are using the loop already, you can just add an if inside the loop. With the array_filter it should remove any empty values from the array.

Moved the function definition. The above should work.


Why don't you check if the string is empty before inserting it into the database?

for ($x = 0; $x < count($tags); $x++){
    if ($tags[$x] != '') {
         $query1 = "INSERT INTO tags (tag) VALUES ('" . mysqli_real_escape_string($mysqli, strtolower($tags[$x])) . "')";
    }
}


I think you just need to beef up what you split on.

I'd probably do something more like this

$input = ",,,,,,,, ,, ,,,,a,d, <html> , ruby-on-rails , ad, <html>";

$tags = preg_split( "/(?:\s*,\s*)+/", trim( strip_tags( $input ), ', ' ) );
$tags = array_map( 'mysqli_real_escape_string', str_replace( ' ', '-', $tags ) );

Then, when it comes to your query, take advantage of MySQL's multiple insert syntax

$query1 = "INSERT INTO tags (tag) VALUES ('" . implode( "'),('", $tags ) . "');";

But you may want to look into duplicate insert handling.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜