为什么我的代码不能在这里工作我认为我做错了但是我无法确定是否有人能在这里发现我弄错了我会感激不尽
这是我的代码:我在这里尝试使用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();
?>
答案 0 :(得分:0)
什么不能正常工作?无论如何,你的SQL是错误的,因为它需要空格。
'INSERT INTO '.self::$table_name.' SET '.$this->attributes();
顺便说一句,你还应该在SQL中转义表和字段名称。