首页 > 解决方案 > 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));
    }
}
?>

标签: php

解决方案


$this您可以inside使用类而不是使用直接名来执行此操作。

  1. 如果您属于outside该类,那么您需要创建一个实例,Resdatalog然后访问/分配值给变量,如下所示。

     $ResdatalogInstance = new Resdatalog;
     $ResdatalogInstance->Location="assign some values";
    
  2. 如果是static这样public static $Location;,那么你可以这样做,Resdatalog::$Location或者self::$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));
        ^^

推荐阅读