[英]Inserting PHP class properties as SQL query variables within the PHP class
我是一個認真的新手,試圖將一些 mysqli LAMP 代碼更新為 PDO/OOP。 我確信我的新代碼效率低下。 我只是將這個項目用作學習經驗。
我正在嘗試將一些 PHP 類屬性傳遞給同一 PHP 類中的方法內的 MySQL 查詢。 這將完成對單個 mysql 表的基本插入。 我已經嘗試過使用 PDO 准備好的語句和基本的 PDO::query 方法。
當我嘗試使用我的類的准備好的語句版本(下面的代碼)進行插入時,我在第 27 行(第一個 bindParam 行)收到“在非對象上調用成員函數 bindParam()”錯誤。
<?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);
}
}
雖然我可能會使用准備好的語句方法,但我很想知道我在這兩種方法上哪里出錯了。 謝謝你。
像這樣嘗試, '
存在語法問題, $this-note
應該是$this->note
$insertQueryWithNote = "INSERT INTO weight (weight_date,weight) VALUES ('$this->date','$this->weight','$this->note')";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.