试图将mysql_ *重写为pdo

时间:2015-06-22 09:04:19

标签: php mysql pdo

首先,我应该说我开始学习PDO并尝试重写一些旧的矿码。这是我在jquery / ajax / pdo / mysql注释系统的教程中找到的一个工作。 这是我尝试重写的mysql_*部分 - >文件submit.php将注释提交给数据库。

$arr = array();
$validates = Comment::validate($arr);

if($validates)
{
   /* Everything is OK, insert to database: */

   mysql_query("    INSERT INTO comments(name,url,email,body)
                VALUES (
                    '".$arr['name']."',
                    '".$arr['url']."',
                    '".$arr['email']."',
                    '".$arr['body']."'
                )");

  $arr['dt'] = date('r',time());
  $arr['id'] = mysql_insert_id();

  $arr = array_map('stripslashes',$arr);

  $insertedComment = new Comment($arr);

  /* Outputting the markup of the just-inserted comment: */

  echo json_encode(array('status'=>1,'html'=>$insertedComment->markup()));

}
else
{
    /* Outputtng the error messages */
    echo '{"status":0,"errors":'.json_encode($arr).'}';
}

这是我对这段代码的尝试。

$pdo = Database::connect();
$arr = array();
$validates = Comment::validate($arr);

if($validates)
{
     /* Everything is OK, insert to database: */
     $sql = $pdo->prepare("INSERT INTO comments ( name,url,email,body ) 
                            VALUES (:name, :url, :email, :body)");

                        $sql->execute(array(
                        ':name'     => $name,
                        ':url'          => $url,
                        ':email'    => $email,
                        ':body'     => $body

                        ));
     $arr['dt'] = date('r',time());
     $arr['id'] = $pdo->lastInsertId();

     $arr = array_map('stripslashes',$arr);

     $insertedComment = new Comment($arr);

     /* Outputting the markup of the just-inserted comment: */

     echo json_encode(array('status'=>1,'html'=>$insertedComment->markup()));

}
else
{
    /* Outputtng the error messages */
    echo '{"status":0,"errors":'.json_encode($arr).'}';
}

当我按下按钮Submit时,什么都没发生。没有在数据库中插入任何内容。按钮变为非活动状态。

如果需要我也可以显示javascript部分或表格。感谢' S

更新:这是comment.class.php,它也包含在submit.php中

class Comment
{
    private $data = array();

    public function __construct($row)
    {   
       /*
       /    The constructor
       */

       $this->data = $row;
    }

    public function markup()
    {
       // this just output the comment on page nothing special some html
    }

    public static function validate(&$arr)
    {

       $errors = array();
       $data    = array();

       // Using the filter_input function introduced in PHP 5.2.0

       if(!($data['email'] = filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)))
       {
            $errors['email'] = 'Wrong email.';
       }

       if(!($data['url'] = filter_input(INPUT_POST,'url',FILTER_VALIDATE_URL)))
       {
            // If the URL field was not populated with a valid URL,
            // act as if no URL was entered at all:

            $url = '';
       }

    // Using the filter with a custom callback function:

       if(!($data['body'] = filter_input(INPUT_POST,'body',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
       {
           $errors['body'] = 'Please enter your comment.';
       }

       if(!($data['name'] = filter_input(INPUT_POST,'name',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
       {
           $errors['name'] = 'Please enter your name.';
       }

       if(!empty($errors)){

        // If there are errors, copy the $errors array to $arr:

        $arr = $errors;
        return false;
       }  

       // If the data is valid, sanitize all the data and copy it to $arr:

       foreach($data as $k=>$v){
           $arr[$k] = mysql_real_escape_string($v);
       }

       $arr['email'] = strtolower(trim($arr['email']));

       return true;     
    } 

   private static function validate_text($str)
   {

      if(mb_strlen($str,'utf8')<1)
        return false;           

      $str = nl2br(htmlspecialchars($str));

      // Remove the new line characters that are left
      $str = str_replace(array(chr(10),chr(13)),'',$str);

      return $str;
   }
}

1 个答案:

答案 0 :(得分:1)

我不知道数组$arr = array();的来源,但在插入查询之前将其指定为null。所以这意味着,从字面上看,你没有在数据库中插入任何内容。所以检查你的阵列,也许就像是

$arr = array('name'=>'My Name', 'url'=>'url', 'email'=>'my email', 'body'=>'comment');

如果您的阵列没有任何问题,那么我认为您错过了数组的键。您可以将数组值存储到变量中,也可以立即使用它们。所以使用,

$pdo = Database::connect();
$arr = array();
$validates = Comment::validate($arr);

if($validates)
{
 /* Everything is OK, insert to database: */
 $sql = $pdo->prepare("INSERT INTO comments ( name,url,email,body ) 
                        VALUES (:name, :url, :email, :body)");

                    $sql->execute(array(
                    ':name'     => $arr['name'],
                    ':url'      => $arr['url'],
                    ':email'    => $arr['email'],
                    ':body'     => $arr['body']

                    ));
 $arr['dt'] = date('r',time());
 $arr['id'] = $pdo->lastInsertId();

 $arr = array_map('stripslashes',$arr);

 $insertedComment = new Comment($arr);

 /* Outputting the markup of the just-inserted comment: */

 echo json_encode(array('status'=>1,'html'=>$insertedComment->markup()));

}
else
{
/* Outputtng the error messages */
echo '{"status":0,"errors":'.json_encode($arr).'}';
}

我希望它会有所帮助。