0
为什么我的代码是不是在这里工作,我认为我做了一些错误,但我不能确定它是否有人能发现什么我已经错在这里我会心存感激PHP类工作不
这里是我的代码:我在这里尝试使用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();
?>
你期待什么行为,你看到了什么?是否有任何错误或通知正在输出?你是否启用了['error_reporting'](http://php.net/manual/en/function.error-reporting.php)? – Sampson
“不工作”是一个非常宽泛的描述。你能更清楚地说明问题是什么。 – SDC
你已经在使用PDO了,这很好,但你并没有逃避你的数据。 PDO提供了一个特别的功能 - 而不是'。“'”。$ this - > $ field。“'”',使用'PDO :: Quote($ this - > $ field)'。 – SDC