【发布时间】:2016-05-31 07:27:59
【问题描述】:
所以我在 php 上使用一个小脚本来管理网页,并且我要进行项目注册,所以我获取所有参数并将它们发送到脚本以构建数据库 (mysql) 的 INSERT。这是我的一段代码:
//Getting the params
$title = $_POST["title"];
$date = $_POST["date"];
$hour = $_POST["hour"];
$description = $_POST["description"];
$link = $_POST["link"];
$speaker = $_POST["speaker"];
$site = $_POST["site"];
$file = $_POST["file"];
//Link and File are optional, so I'll be using NULL instead if they're empty
$link = !empty($link) ? ("'".$link."'") : ("'". NULL ."'");
$file = !empty($file) ? ("'".$file."'") : ("'". NULL ."'");
//Now I'm ready to build the query
$query = "INSERT INTO ".$type;
$query = $query . "(title,data,hour,description,link,speaker,site,file)";
$query = $query . "VALUES (";
$query = $query . "'" .$title."'";
$query = $query . ",'".$date."'";
$query = $query . ",'".$hour."'";
$query = $query . ",'".$description."'";
$query = $query . ",".$link;
$query = $query . ",'".$speaker."'";
$query = $query . ",'".$site."'";
$query = $query . ",".$file.")";
//Finally, I'll be sending the INSERT as a query using:
$result = mysql_query($query);
if(!$result)
echo "SQL Error"
所以,我总是进入错误语句。 我在同一网页上的其他脚本中插入了其他脚本,它们运行良好,这个模仿了它们。我已经检查过:
- mysql_connect() 和 mysql_select_db() 都可以
- 我使用的数据库用户有权执行 INSERT
- 数据库连接(使用 SELECT 查询检查)
任何提示将不胜感激。
[已解决] 字符串没有转义,所以引号破坏了查询。因此,如果您仍然存在这种问题并使用已弃用的 mysql _ API,您可能还需要 mysql_escape_string 方法(检查Escaping single quote in PHP when inserting into MySQL)。
【问题讨论】:
-
输入你的表格结构以及表格的编码
-
停止使用已弃用的
mysql_API。使用mysqli_或PDO代替准备好的语句 -
调用mysql_error()函数,找出错误所在。
-
$type变量来自哪里。您的代码也可用于 sql 注入 -
@ytturi,你有没有在下面检查我的答案并尝试过。
标签: php mysql error-handling