Visualizzazione risultati 1 fino 4 di 4

Discussione: $stmt->bindParam

  1. #1
    beestatus non è connesso Neofita
    Data registrazione
    22-10-2016
    Residenza
    north garda lake
    Messaggi
    14

    Predefinito $stmt->bindParam

    buongiorno

    DOMANDA:
    utilizzare una variable anzichè una stringa come primo argomento di
    Codice:
    bindparam
    cioè trasformare questo:
    Codice:
    $stmt->bindParam(":variable_name",$variable_value,PDO::PARAM_STR);
    in questo:
    Codice:
    $stmt->bindParam($variable_name,$variable_value,PDO::PARAM_STR);
    Vi cerco di illustrare:

    attraverso questo codice io carico dati in ingresso sul database FUNZIONA
    Codice PHP:
    <?php

    require_once '../shared/Logger.php';
    require_once
    '../shared/Temperature_Config0.1.php';

    class
    DBManager {
    private
    $dbh;
    //print(":weigth1");
    const _SAVE_DATA = "INSERT INTO apidata(temperature,luminosity,humidity,pressure) VALUES(:temperature,:luminosity,:humidity,:pressure)";
    const
    _SELECT_TEMPERATURE = "SELECT temperature,date_format(date_time, '%k:%i') Date FROM `apidata`";

    public function
    __construct($conn) {
    $this->dbh = $conn;
    }

    /**
    * This function saves the temperature value on the db
    * @param string $temperature
    * @throws Exception is used in case of exception
    */
    public function save_data($temperature,$luminosity,$humidity,$pressure,$weights) {
    try {

    echo(
    "start");
    $stmt = $this->dbh->prepare(self::_SAVE_DATA);

    $stmt->bindParam(":temperature",$temperature,PDO::PARAM_STR);
    $stmt->bindParam(":luminosity",$luminosity,PDO::PARAM_STR);
    $stmt->bindParam(":humidity",$humidity,PDO::PARAM_STR);
    $stmt->bindParam(":pressure",$pressure,PDO::PARAM_STR);
    $stmt->execute();
    } catch (
    PDOException $ex) {
    Logger::log($ex->getCode(), $ex->getMessage());
    throw new
    Exception("Failed save luminosity");
    }
    }


    /**
    * This function recovers the temperature values
    * @throws Exception is used in case of exception
    * @return $result is a array with the result of the query
    */
    public function select_temperature() {
    try {
    $stmt = $this->dbh->prepare(self::_SELECT_TEMPERATURE);
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    return
    $result;
    } catch (
    PDOException $ex) {
    Logger::log($ex->getCode(), $ex->getMessage());
    throw new
    Exception("Impossible load last 5 posts, there was an error");
    }
    }
    }
    ?>
    ora devo inserire dei dati che sono in una lista, sono stringhe così formate:
    Codice PHP:
    $weights = (1w123,2w456,3,789)
    quindi ho inserito questa parte di codice
    Codice PHP:
    foreach( $weights as $value)
    {
    //echo $value."<br />";
    $weight = explode('w',$value);
    $index = $weight[0];
    $weight = $weight[1];
    echo ((
    $index)."<br />");
    //$column = ":weight"."1";
    if ($index != ""){
    $column = ":weight".$index;
    $stmt->bindParam($column, $weight,PDO::PARAM_STR);
    echo(
    $column." ".$weight."<br />");
    }
    }
    ed ho ottenuto questo che però NON FUNZIONA:
    Codice PHP:
    <?php

    require_once '../shared/Logger.php';
    require_once
    '../shared/Temperature_Config0.1.php';

    class
    DBManager {
    private
    $dbh;
    //print(":weigth1");
    const _SAVE_DATA = "INSERT INTO apidata(temperature,luminosity,humidity,pressure,weight1) VALUES(:temperature,:luminosity,:humidity,:pressure,:weight1)";
    const
    _SELECT_TEMPERATURE = "SELECT temperature,date_format(date_time, '%k:%i') Date FROM `apidata`";

    public function
    __construct($conn) {
    $this->dbh = $conn;
    }

    /**
    * This function saves the temperature value on the db
    * @param string $temperature
    * @throws Exception is used in case of exception
    */
    public function save_data($temperature,$luminosity,$humidity,$pressure,$weights) {
    try {

    echo(
    "start");
    $stmt = $this->dbh->prepare(self::_SAVE_DATA);


    foreach(
    $weights as $value)
    {
    //echo $value."<br />";
    $weight = explode('w',$value);
    $index = $weight[0];
    $weight = $weight[1];
    echo ((
    $index)."<br />");
    //$column = ":weight"."1";
    if ($index != ""){
    $column = ":weight".$index;
    $stmt->bindParam($column, $weight,PDO::PARAM_STR);
    echo(
    $column." ".$weight."<br />");
    }
    }

    $stmt->bindParam(":temperature",$temperature,PDO::PARAM_STR);
    $stmt->bindParam(":luminosity",$luminosity,PDO::PARAM_STR);
    $stmt->bindParam(":humidity",$humidity,PDO::PARAM_STR);
    $stmt->bindParam(":pressure",$pressure,PDO::PARAM_STR);
    $stmt->execute();
    } catch (
    PDOException $ex) {
    Logger::log($ex->getCode(), $ex->getMessage());
    throw new
    Exception("Failed save luminosity");
    }
    }


    /**
    * This function recovers the temperature values
    * @throws Exception is used in case of exception
    * @return $result is a array with the result of the query
    */
    public function select_temperature() {
    try {
    $stmt = $this->dbh->prepare(self::_SELECT_TEMPERATURE);
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    return
    $result;
    } catch (
    PDOException $ex) {
    Logger::log($ex->getCode(), $ex->getMessage());
    throw new
    Exception("Impossible load last 5 posts, there was an error");
    }
    }
    }
    ?>
    Grazie per l'attenzione

  2. #2
    karl94 non è connesso Staff AV
    Data registrazione
    03-10-2005
    Messaggi
    17,744

    Predefinito

    In che senso non funziona? Visualizzi un messaggio di errore? Cosa succede?

  3. #3
    beestatus non è connesso Neofita
    Data registrazione
    22-10-2016
    Residenza
    north garda lake
    Messaggi
    14

    Predefinito

    EDIT!
    nessun messaggio, semplicemente non vengono caricati i dati sul database.
    la cosa curiosa è che,
    questo codice funziona:

    Codice PHP:
    foreach( $weights as $value)
    {
    //echo $value."<br />";
    $weight = explode('w',$value);
    $index = $weight[0];
    $weight = $weight[1];
    echo ((
    $index)."<br />");
    //$column = ":weight"."1";
    if ($index != ""){
    $column = ":weight"."1";
    $stmt->bindParam($column, $weight,PDO::PARAM_STR);
    echo(
    $column." ".$weight."<br />");
    }
    }
    e quello di prima, cioè questo, no
    Codice PHP:
    foreach( $weights as $value)
    {
    //echo $value."<br />";
    $weight = explode('w',$value);
    $index = $weight[0];
    $weight = $weight[1];
    echo ((
    $index)."<br />");
    //$column = ":weight"."1";
    if ($index != ""){
    $column = ":weight".$index;//cambia solo questa riga
    $stmt->bindParam($column, $weight,PDO::PARAM_STR);
    echo(
    $column." ".$weight."<br />");
    }
    }
    Ultima modifica di beestatus : 06-01-2017 alle ore 09.46.10 Motivo: correzione codice x comprensibilità

  4. #4
    mzanella non è connesso AlterGuru
    Data registrazione
    29-12-2015
    Messaggi
    1,954

    Predefinito

    Non ho letto tutto il codice ma, a colpo d'occhio ci sono dei problemi qui:
    Codice PHP:
    foreach ($weights as $value)
    {
    // echo $value."<br />";
    $weight = explode('w', $value);
    $index = $weight[0];
    $weight = $weight[1];
    echo ((
    $index)."<br />");
    //$column = ":weight"."1";
    if ($index != ""){
    $column = ":weight".$index;
    $stmt->bindParam($column, $weight, PDO::PARAM_STR);
    echo(
    $column." ".$weight."<br />");
    }
    }
    In _SAVE_DATA prevedi l'inserimento di un campo weight1, ma il quel brano di codice chiami bindParam all'interno di un ciclo ricavando l'indice dall'elemento di turno.
    Probabilmente c'è un'incongruenza tra il numero di parametri richiesti in _SAVE_DATA e quelli che imposti con bindParam. Nel codice in cui sostituisci $index con "1" il problema si "risolve" in quanto usi bindParam sempre sulla stessa "chiave", sovrascrivendola.

    Altra osservazione: con bindParam il binding è tra parametro e nome della variabile, usandolo in un ciclo tutti i parametri vengono associati al nome della variabile $weight[1], quindi avranno tutti lo stesso valore. Dovresti usare piuttosto bindValue.

    Non è direttamente collegato, ma questa cosa è proprio brutta :
    Codice PHP:
    $weight = $weight[1];
    $weight smette di essere un vettore e diventa inspiegabilmente una stringa. Usa nomi diversi per variabili diverse, oppure qualcosa come:
    Codice PHP:
    list($index, $weight) = explode('w', $value);
    Potresti anche utilizzare empty per verificare che $index non sia un valore vuoto:
    Codice PHP:
    if (!empty($index))

Regole di scrittura

  • Non puoi creare nuove discussioni
  • Non puoi rispondere ai messaggi
  • Non puoi inserire allegati.
  • Non puoi modificare i tuoi messaggi
  •