在查询中使用来自$ get的变量

时间:2017-08-24 20:34:12

标签: php sql excel variables

拥有一个包含2个函数的php脚本。 在第一个函数中,查询使用$ get来获取时间和日期。 第二个功能是让我尝试使用第一个函数中的变量。

public function Execute( ) {


    if( $_GET['from'] && $_GET['to'] ){

        $from = $_GET['from'];
        $to = $_GET['to'];


       $query =  "SELECT * from historie_ordre where kode = ? AND time BETWEEN ? AND ? AND  order by time desc";
       $orders = DB::query( $query, $kode,  $from, $to )->fetchAll( DB::FETCH_ASSOC );


        Util::Debug( $orders  );
        $this->stats = $orders;

    }

    $this->kode = $kode;
    $this->from = $from;
    $this->to = $to;


}

第二次失败:

     public function XLS(  ) {


 //trying to use this:
$from = intval($_GET['from']);
$to = intval($_GET['to']);
$kode = intval($_GET['kode']);



     $query =  "SELECT * from historie_ordre where kode = $kode AND time BETWEEN $from AND $to AND  order by time desc"; 

        $orders = DB::query( $query, $kode,  $from, $to )->fetchAll( DB::FETCH_ASSOC );


         $this->setTemplate( false );

         $oldreporting = error_reporting( 0 );

         require_once 'Spreadsheet/Excel/Writer.php';

// Creating a workbook
$workbook = new Spreadsheet_Excel_Writer();

// sending HTTP headers
$workbook->send('stabburet_stats.xls');

// Creating a worksheet
$worksheet =& $workbook->addWorksheet('My first worksheet');

// overskrift
//$worksheet->write(0, 0, 'Antall');
$worksheet->write(0, 1, 'kode');
$worksheet->write(0, 2, 'name');
$worksheet->write(0, 3, 'adress');


$i=1;
// for å få inn verdiane
foreach( $orders as $order ){
    $i++;
    //$worksheet->write($i, 0, $order['antall']);
    $worksheet->write($i, 1, $order['kode']);
    $worksheet->write($i, 2, utf8_decode( $order['name'] ) );
    $worksheet->write($i, 3, utf8_decode ($order['adress']) );


}        

// Sender fila
$workbook->close();
         error_reporting( $oldreporting );

      }



    }

第一个功能正常。第二个是仅使用“硬编码”变量。

1 个答案:

答案 0 :(得分:0)

您在评论中指出,您需要更加小心并始终如一地使用相同的技术。我也不相信第一个函数正常工作,因为每个地方的查询语法都是错误的。

问题至少是你的SELECT语法不正确,最后有一个假的AND。您还使用名为time的列,这是一个mysql保留字。这可能也是一个问题,可以通过使用`column name`语法来缓解。

 $query =  "SELECT * 
            from historie_ordre 
            WHERE kode = $kode 
                AND time BETWEEN $from AND $to AND  
            order by time desc";

需要:

  $query =  "SELECT * 
             FROM historie_ordre
             WHERE kode = ? 
             AND `time` BETWEEN ? AND ? 
             ORDER BY `time` DESC";

<强> 更新

现在我们收到了您的更多信息,问题也可以追溯到这里:

$from = intval($_GET['from']);
$to = intval($_GET['to']);
$kode = intval($_GET['kode']);

问题是你的from和to需要是日期格式的字符串。你通过把它们变成整数来强迫它们成为零。所以你的查询再次无法运行。

$from = $_GET['from'];
$to = $_GET['to'];
$kode = intval($_GET['kode']);