这里我有一个将数据插入db的代码。它现在工作正常,但我希望标题至少包含4个字符,并且正文至少为500个字符。
这是我的代码:
<?php
if(isset($_POST['submit'])) {
//get blog data
$title=strip_tags($_POST['title']);
$body=strip_tags($_POST['body']);
$posted_by = $first_name;
$category=$_POST['category'];
$bio = $bio;
$userid=$_COOKIE['user'];
$date = date ('d-M-Y');
if ($title && $body && $category) {
$query = "INSERT INTO blogs (userid, title, body, posted_by, bio, category_id, posted) VALUES ('$userid', '$title', '$body', '$posted_by','$bio', '$category', '$date')";
$run = mysqli_query($con,$query);
if($query) {
echo "posted";
}
else {
echo "error";
}
}else {
echo "data missing";
}
}
?>
我尝试使用下面的代码来为标题和正文添加最低要求,但是即使标题包含超过5个字符,它也会在您提交数据时回显标题错误消息。
<?php
if(isset($_POST['submit'])) {
//get blog data
$title=strip_tags($_POST['title']);
$body=strip_tags($_POST['body']);
$posted_by = $first_name;
$category=$_POST['category'];
$bio = $bio;
$userid=$_COOKIE['user'];
$date = date ('d-M-Y');
if (strlen($title<5)) {
echo "Title must be of minimum 5 characters";
}
else {
if (strlen($body<500)) {
echo "Title must be of minimum 500 characters";
}
else {
$query = "INSERT INTO blogs (userid, title, body, posted_by, bio, category_id, posted) VALUES ('$userid', '$title', '$body', '$posted_by','$bio', '$category', '$date')";
$run = mysqli_query($con,$query);
if($query) {
echo "posted";
}
else {
echo "error";
}
}
}
}
?>
答案 0 :(得分:5)
这样的问题值得对未来读者解释这个问题。
您的代码失败的原因是:
if (strlen($title<5))
评估为:
function($string conditional)
语法为:
function($string) conditional
手册说明:
int strlen(string $ string)
从手册中摘录的例子:
if (strlen($foo) === 0) echo 'Null length is Zero <br>';
另外,正如评论中所述。您的查询受SQL注入。最好使用准备好的声明。
请参阅以下链接:
答案 1 :(得分:2)
我认为问题在于您使用的条件。
if (strlen($title<5))
应该是
if (strlen($title)<5)
同样
if (strlen($body<500))
是
if (strlen($body)<500)
答案 2 :(得分:0)
试试这个:
<?php
if(isset($_POST['submit'])) {
//get blog data
$title=strip_tags($_POST['title']);
$body=strip_tags($_POST['body']);
$posted_by = $first_name;
$category=$_POST['category'];
$bio = $bio;
$userid=$_COOKIE['user'];
$date = date ('d-M-Y');
if (strlen($title) < 5) {
echo "Title must be of minimum 5 characters";
}else {
if (strlen($body) <500 ) {
echo "Body must be of minimum 500 characters";
}else {
$query = "INSERT INTO blogs (userid, title, body, posted_by, bio, category_id, posted) VALUES ('$userid', '$title', '$body', '$posted_by','$bio', '$category', '$date')";
$run = mysqli_query($con,$query);
if($query) {
echo "posted";
}else {
echo "error";
}
}
}
}
?>