$tag = mysql_real_escape_string($_GET['tag']);
$tag = str_replace("-", " ", $_GET['tag']);
$query = mysql_query("SELECT * FROM tags WHERE name = '$tag'");
$row = mysql_fetch_assoc($query);
if (!mysql_num_rows($query)) exit('That tag dont exist.');
I have a tag with spaces in its name, how should i do to replace the spaces with hyphens? I think the above code should work but it doesnt :/
Update:
$tag = str_replace(' ', '-', $_GET['tag']);
$tag = mysql_real_escape_string($tag);
$query = mysql_query("SELECT * FROM tags WHERE name = '$tag'");
$row = mysql_fetch_assoc($query);
if (!mysql_num_rows($query)) exit('That tag dont exist');
Db tags
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL
INSERT INTO `tags` (`id`, `name`) VALUES
(1, 'test'),
(2, 'test test'),
(3, 'test test test test');
(3, 'test test test test');Either store the tags with hypens instead of spaces,
(3, 'test-test-test-test')
$tag = mysql_real_escape_string($_GET['tag']);
$query = "SELECT * FROM tags WHERE name = '$tag'";
$result = mysql_query($query) or die(mysql_error());
if ( false===($row=mysql_fetch_assoc($result)) ) exit('No such tag.');
Other way around:
$tag = str_replace(' ', '-', $_GET['tag']);
$tag = mysql_real_escape_string($tag);
(When you see str_replace(A, B, C)
, think "replace A with B in C")
(Also, escaping the string should happen after everything else. And you accidentally used $_GET['tag']
instead of $tag
your second time.)