One Little Error...
I'm writing a URL shortener... I have this one error that i just can't seem to get rid of. I feel its really obvious but I'm not seeing it.
(I'm a noob ;) ) Here's the Error:
'mysql_result(): supplied argument is not a valid MySQL result resource in <b>/home2/bythewa1/public_html/jbgc/func.inc.php</b> on line <b>23'
And here's my code from that page.
<?php
include("db.inc.php");
function is_min($url)
{
return(preg_match("/jbgc\.me/i", $url)) ? true : false;
}
function gen_code()
{
$charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
return substr(str_shuffle($charset), 0, 6);
}
function exists($code) {
$code = mysql_real_escape_string($code);
$code_exists = mysql_query("SELECT COUNT('url_id') FROM 'mini_shortener' WHERE 'code'= '$code' LIMIT 1");
return (mysql_result($code_exists, 0) == 1) ? true : false;
}
开发者_JAVA百科
function shorten($url, $code){
$url = mysql_real_escape_string($url);
$code = mysql_real_escape_string($code);
mysql_query("INSERT INTO 'mini_shortener' VALUES('', '$url', '$code')");
return $code;
}
?>
You have errors in your SQL queries -- and should use the mysql_error()
function to find out more about those errors ;-)
Still, in your case, you are using the following query :
SELECT COUNT('url_id')
FROM 'mini_shortener'
WHERE 'code'= '$code'
LIMIT 1
you should not use single-quotes arround the fields names -- but backticks : `
Same in your second query, btw.
With MySQL :
- Single-quotes
'
are use arround literal-strings, - and Backticks
` are use arround names.
SELECT COUNT('url_id') FROM 'mini_shortener' WHERE 'code' = ...
You can't select from a string literal. Try using back-ticks instead of single-quotes.
SELECT COUNT(`url_id`) FROM `mini_shortener` WHERE `code` = ...
The cases where you put column names in single-quotes aren't syntax errors, but they probably don't do what you intend. For instance, 'code' = '$code'
will be true only when $code is literally the string 'code'. It does not compare $code to the contents of the column code
.
Likewise you need to use back-ticks for the table name in your INSERT statement:
INSERT INTO `mini_shortener` VALUES('', '$url', '$code')
For review:
- MySQL Reference Manual 8.1.1. Strings
A string is a sequence of bytes or characters, enclosed within either single quote (“'”) or double quote (“"”) characters. If the ANSI_QUOTES SQL mode is enabled, string literals can be quoted only within single quotation marks because a string quoted within double quotation marks is interpreted as an identifier.
- MySQL Reference Manual 8.2. Identifiers
The identifier quote character is the backtick (“`”). If the ANSI_QUOTES SQL mode is enabled, it is also permissible to quote identifiers within double quotation marks.
精彩评论