简体   繁体   English

尝试将mysql_ *重写为pdo

[英]Trying to rewrite mysql_* to pdo

First of all I should say that I started to learn PDO and trying to rewrite some old mine codes. 首先,我应该说,我开始学习PDO并尝试重写一些旧的防雷代码。 Here is one that I found on tutorial for a jquery/ajax/pdo/mysql comment system which is working. 这是我在正在运行的jquery / ajax / pdo / mysql注释系统的教程中找到的一个。 This is the mysql_* part which I'm trying to rewrite -> file submit.php which submits the comments to database. 这是我要重写的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).'}';
}

Here is my try of this piece of code. 这是我对这段代码的尝试。

$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).'}';
}

When I hit button Submit just nothing happen. 当我按下“ Submit按钮时,什么也没有发生。 Didn't insert anything into database. 没有向数据库中插入任何内容。 And the button become inactive. 并且按钮变为非活动状态。

If need I can show javascript part or the form as well. 如果需要,我也可以显示javascript部分或表格。 Thank's 谢谢

UPDATE: This is the comment.class.php which is included also into the submit.php 更新:这是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;
   }
}

I don't know the source of the array $arr = array(); 我不知道数组的来源$arr = array(); , but it is assigned to null before the insert query. ,但在插入查询之前将其分配为null。 So it means, literally you are inserting nothing into the database. 因此,这意味着从字面上看,您什么都没有插入数据库。 So check your array well, maybe it was to be like 因此,请检查您的阵列,也许就像

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

And if there is nothing wrong with your array then I think you are missing the keys of the array. 而且,如果您的阵列没有问题,那么我认为您缺少该阵列的键。 You can either store the array values into variables or use them straight away. 您可以将数组值存储到变量中,也可以立即使用它们。 So use , 所以用

$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).'}';
}

I hope it will help. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM