我是一个认真的新手试图将一些mysqli LAMP代码更新为PDO / OOP。我确信我的新代码效率低下。我只是将这个项目用作学习经历。
我正在尝试将一些PHP类属性传递给同一PHP类中的方法内的MySQL查询。这将完成基本插入到单个mysql表中。我已经尝试使用PDO预处理语句和基本的PDO :: query方法。
当我使用我的类的预准备语句版本(下面的代码)尝试插入时,我在第27行(第一个bindParam行)上得到“对非对象的成员函数bindParam()的调用”。 / p>
<?php
class weightInfoInsert
{
// properties
private $date;
private $weight;
private $note;
private $dbc;
private $insertQueryWithNote;
private $sth;
// methods
public function __construct($date, $weight, $note, $dbc)
{
$this->date = $date;
$this->weight = $weight;
$this->note = $note;
$this->dbc = $dbc;
}
public function insertWeightWithNote()
{
$insertQueryWithNote = ' INSERT INTO weight (weight_date,weight,weight_note) VALUES ( :date, :weight, :note ) ';
$sth = $this->dbc->prepare($insertQueryWithNote);
$sth->bindParam(':date', $this->date, PDO::PARAM_STR, 8);
$sth->bindParam(':weight', $this->weight, PDO::PARAM_STR, 5);
$sth->bindParam(':note', $this->note, PDO::PARAM_STR);
$this->sth->execute();
}
}
当我使用PDO :: query()方法(下面的代码)尝试插入时,我在第23行(查询语句行)上得到“语法错误,意外'$ this'(T_VARIABLE)”。
<?php
class weightInfoInsert
{
// properties
private $date;
private $weight;
private $note;
private $dbc;
private $insertQueryWithNote;
// methods
public function __construct($date, $weight, $note, $dbc)
{
$this->date = $date;
$this->weight = $weight;
$this->note = $note;
$this->dbc = $dbc;
}
public function insertWeight()
{
$insertQueryWithNote = ' INSERT INTO weight (weight_date,weight) VALUES ('$this->date','$this->weight','$this-note') ';
$this->dbc->query($insertQueryWithNote);
}
}
虽然我可能会使用预备语句方法,但我最好知道两种方法在哪里出错了。谢谢。
答案 0 :(得分:1)
尝试这样,'
存在语法问题,而$this-note
应为$this->note
$insertQueryWithNote = "INSERT INTO weight (weight_date,weight) VALUES ('$this->date','$this->weight','$this->note')";