-1 php
这里我有一个将数据插入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";
}
}
?>
Run Code Online (Sandbox Code Playgroud)
我尝试使用下面的代码来为标题和正文添加最低要求,但是即使标题包含超过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";
}
}
}
}
?>
Run Code Online (Sandbox Code Playgroud)
这样的问题值得对未来读者解释这个问题.
您的代码失败的原因是:
if (strlen($title<5))
Run Code Online (Sandbox Code Playgroud)
评估为:
function($string conditional)
当语法是:
function($string) conditional
手册说明:
int strlen(string $ string)
从手册中拉出的示例:
if (strlen($foo) === 0) echo 'Null length is Zero <br>';
Run Code Online (Sandbox Code Playgroud)
另外,正如评论中所述.您的查询受SQL注入.最好使用准备好的声明.
请参考以下链接: