繁体   English   中英

在 PHP 类中插入 PHP 类属性作为 SQL 查询变量

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM