PHP中的键值数组语法

我用PDO写了一些PHP代码。我对PHP语法很陌生,所以我按照PHP文档来写。我在$params = array(…语句中得到一个语法错误。也许语法问题是对全局变量的引用,但这是我在PHP文档中找到的引用。

这是我的代码。

<?php

/*
    Sets up a PDO object for the ResDatLog table
*/

class Resdatalog
{  
    // database connection and table name
    private $_conn;
    private $_table_name = "ResDataLog";

    // object properties
    public $ID;
    public $Location = null;
    public $Temperature;
    public $Humidity;
    public $Pressure;
    public $RecDate;
    public $AmbientTemp;
    public $AmbientHum;
    public $AmbientPressure;

    /* 
        constructor with $db as database connection
    */
    public function __construct($db)
    {
        $this->conn = $db;
    }

    /* 
        Reads all columns of the entire table ($table_name)
    */
    function read() 
    {
        // select all query
        $query = "SELECT *
                FROM
                " . $this->table_name . "
                ORDER BY 
                    id DESC";

        // prepare query statement
        $stmt = $this->conn->prepare($query);

        // execute query
        $stmt->execute();
        return $stmt;
    }
    function insert()
    {
        // insert a new row into the table_name table
        $sql = 'INSERT Location, Temperature, Humidity, Pressure, RecDate,
         AmbientTemp, AmbientHum, AmbientPressure into '
         . $this->table_name . 
         ' VALUES (:Location,:Temperature, :Humidity, 
         :Pressure, :RecDate, :AmbientTemp, :AmbientHum, :AmbientPressure)';

        $sth = $this->conn->prepare($sql);

        $params = array(
            ':Location' => ResDataLog->Location,
            ':Temperature'=> ResDataLog->Temperature,
            ':Humidity'=> ResDataLog->Humidity,
            ':Pressure'=> ResDataLog->Pressure,
            ':RecDate'=> ResDataLog->RecDate,
            ':AmbientTemp'=> ResDataLog->AmbientTemp,
            ':AmbientHum'=> ResDataLog->AmbientHum,
            ':AmbientPressure'=> ResDataLog->AmbientPressure);


         Return($$sth->execute($params));
    }
}
?>

解决方案:

你可以用 $this 随你 inside 的类,而不是直接使用 阶层 名。

  1. 如果你是 outside 类的实例,那么你就需要制作一个关于 Resdatalog 然后像下面这样访问assign值给变量。

     $ResdatalogInstance = new Resdatalog;
     $ResdatalogInstance->Location="assign some values";
    
  2. 如果是 static 喜欢 public static $Location;,那么你可以这样做。Resdatalog::$Locationself::$Location.

    $params = array(
      ':Location' => $this->Location,
       ':Temperature'=> $this->Temperature,
      ':Humidity'=> $this->Humidity,
      ':Pressure'=> $this->Pressure,
      ':RecDate'=> $this->RecDate,
      ':AmbientTemp'=> $this->AmbientTemp,
      ':AmbientHum'=> $this->AmbientHum,
      ':AmbientPressure'=> $this->AmbientPressure
    

    );

另外,你还需要删除多余的 $ 符号从这一行。

 return ($sth->execute($params));
        ^^

给TA打赏
共{{data.count}}人
人已打赏
未分类

对表进行排序 Vue.js

2022-9-8 7:31:21

未分类

如何在我的C#代码中永久地改变一个类的公共变量。

2022-9-8 7:31:23

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索