0

为什么我的代码在这里不起作用我认为我做错了但我无法确定是否有人能在这里发现我做错了什么

这是我的代码:我在这里尝试使用 php 类在数据库中插入新行

<?php
$connection = new PDO('mysql:dbname=master;host=localhost','root','123');
/*if($connection)
{
    echo 'Database is connected successfully';
}
else
     {
    echo 'please connect to a database';
}*/
class Topics
{
    public $id;
    public $title;
    public $body;
    public static $table_name = 'topics';
    public static $fields = array ('title','body');
    private function attributes()
    {
        $string = array();  
        foreach (self::$fields as $field) 
        {
            if (!empty($field)) {
                if(is_int($this->$field))
                {
                    $string[] = $field." =".$this->$field;
                }
                else
                {
                    $string[] = $field." ="."'".$this->$field."'";
                }

            }   

        }
        return join(',', $string);
    }
    public function add()
    {
        global $connection;
        $sql = 'INSERT INTO'.self::$table_name.'SET'.$this->attributes();
        $number_of_affected_rows = $connection->exec($sql);
        if($number_of_affected_rows >0)
        {
            $this->id = $connection->lastInsertId();
        }
        return ($number_of_affected_rows>0) ? $number_of_affected_rows : FALSE;
    }
}
$mohamed = new Topics();
$mohamed->title = 'Hello';
$mohamed->body = 'Hello world again';
return $mohamed->add();
?>
4

1 回答 1

0

什么不正确?无论如何,您的 SQL 都是错误的,因为它需要空格。

'INSERT INTO '.self::$table_name.' SET '.$this->attributes();

顺便说一句,您还应该在 SQL 中转义表和字段名称。

于 2012-11-28T13:47:11.900 回答