我有一个包含 4 个项目的 html 表单。
title
和 content
是必需的。
link
和 image
是可选的。
所以这就是我写的,但我无法将数据插入我的数据库中。 我的 url 和 image 条件语句中是否有错误?谢谢
if($_SERVER['REQUEST_METHOD'] == "POST") {
$ttt = strlen(htmlspecialchars(trim($_POST['title'])));
$ccc = strlen(htmlspecialchars(trim($_POST['content']))); // count title and content charters
$title = htmlspecialchars(trim($_POST['title']));
$content = htmlspecialchars(trim($_POST['content']));
$url = htmlspecialchars(trim($_POST['url']));
$image = htmlspecialchars(trim($_POST['image']));
if($url!=''){
if ( !preg_match( '|^(ht|f)tp(s?))://|', $url ){
echo "wrong";
mysql_close($db);
}
} // if $url is not empty, judge is it began as a http:// ? else close the db link
if($image!=''){
if ( !getimagesize($image)){
echo "wrong";
mysql_close($db);
}
} // if $image is not empty, use getimagesize judge is it a real image? else close the db link
if(($ttt > 2 && $ttt < 201) && ($ccc > 29 && $ccc < 1001)) {
$sql= "INSERT INTO msg (title, content,image,link) VALUES ('".$title."','".$content."', '".$image."', '".$url."')";//if title charters between 3-200 and content charters between 30-1000, do insert into thing
if(mysql_query($sql))
{
echo "insert done";
}else{
echo "insert wrong";
}
}else{
echo "your title or content is out of the words limit";
}
}
mysql_close($db);
最佳答案
改变:
if($link!=''){
if ( !preg_match( '|^(ht|f)tp(s?))://|', $url ){
echo "wrong";
mysql_close($db);
}
}
到
if($url !=''){
if ( !preg_match( '|^(ht|f)tp(s?))://|', $url ){
echo "wrong";
mysql_close($db);
}
}
为了我们能够帮助yuou更好的展示你的$sql语句;
更新:
很难找出这样的问题,这是您可以做的,看看问题是什么:
$result = mysql_query($sql) or die ('Error: 'mysql_error());
这样你就可以看到查询中的错误是什么,我很确定这是一个转义问题,所以这里是你可以添加的内容;
$title = htmlspecialchars(trim($_POST['title']));
$content = htmlspecialchars(trim($_POST['content']));
$url = htmlspecialchars(trim($_POST['url']));
$image = htmlspecialchars(trim($_POST['image']));
$title = mysql_real_escape_string($title);
$content = mysql_real_escape_string($content);
$url = mysql_real_escape_string($url);
$image = mysql_real_escape_string($image);
这样如果有特殊字符就会被转义
关于php mysql插入条件判断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5940507/