设置帖子

时间:2015-09-13 08:37:30

标签: php syntax blogs strlen

我获得了发布博客标题和正文以及其他一些内容的代码。现在我想使用strlen设置标题和正文的最小字符长度,我的代码是

 if(isset($_POST['submit'])) {
   $title=$_POST['title'];
   $body=$_POST['body'];
   $category=$_POST['category'];
   $title = mysql_real_escape_string($title);
   $body = mysql_real_escape_string($body);
   $posted_by = $user;
   $bio = $bio;
   $id=$_SESSION['id'];
   $date = date ('Y-m-d');
   $body = htmlentities($body);
   if ($title && $body && $category) {
      $query = mysql_query("INSERT INTO blogs (id, title, body, posted_by, bio, category_id, posted) VALUES ('$id', '$title', '$body', '$posted_by','$bio', '$category', '$date')");
      if($query) {
        echo "posted";
      }
      else {
        echo "error";
      }
   }else {
    echo "data missing";
   }
}

此代码工作正常,只想插入标题和正文的最小字符要求。我用strlen尝试了几个if else语句,但我不是编程专家所以我得到了语法错误。

3 个答案:

答案 0 :(得分:3)

这可能对你有帮助..

 if(isset($_POST['submit'])) {
           $title=$_POST['title'];
           if(strlen($title)<8)
           {
               //codes to handle error
           }

   $body=$_POST['body'];
   if(strlen($body)<80)
           {
               //codes to handle error
           }
   $category=$_POST['category'];
   $title = mysql_real_escape_string($title);
   $body = mysql_real_escape_string($body);
   $posted_by = $user;
   $bio = $bio;
   $id=$_SESSION['id'];
   $date = date ('Y-m-d');
   $body = htmlentities($body);
   if ($title && $body && $category) {
      if(strlen($title)>8 && strlen($body>80))
           {

      $query = mysql_query("INSERT INTO blogs (id, title, body, posted_by, bio, category_id, posted) VALUES ('$id', '$title', '$body', '$posted_by','$bio', '$category', '$date')");
           }
        else {
                  $query = 0;
              }
      if($query) {
        echo "posted";

      }
      else {
        echo "error";
      }
   }else {
    echo "data missing";
   }

答案 1 :(得分:1)

如果你想计算字符串的长度,可以使用“strlen”

if(strlen($title)>5 && strlen($body)>5) {
  // $title and $body is more than 5 bytes long
}else{
  // $title or $body is 5 or less than 5 bytes long
}

Documentation

答案 2 :(得分:1)

if(strlen($title)<=15 && strlen($body)<=500) {
   $query = mysql_query("INSERT INTO blogs (id, title, body, posted_by, bio, category_id, posted) VALUES ('$id', '$title', '$body', '$posted_by','$bio', '$category', '$date')");
      if($query) {
        echo "posted";
      }
}
else
{
echo "Minimum Character Requirments failed.";
}