как передать данные сессии в формате fpdf - PullRequest
0 голосов
/ 07 февраля 2019

Я создаю веб-страницу электронного обучения , где администраторы веб-сайта могут создавать отчеты на основе данных пользователей.Я хочу создать базу отчетов о том, что администратор хочет иметь отчеты.Я попытался передать данные сеанса в fpdf так же, как и данные сеанса на другую страницу, но они не работают.

Нужно ли давать пример кода или нет?если это так, я отредактирую свой вопрос и вставлю в него свои коды.

Извините за мой английский, надеюсь, вы меня хорошо понимаете.

Я динамически генерирую свой отчет, поэтому использую егоданные сеанса для предложения WHERE в моем операторе SELECT.

<?php

require('../fpdf/fpdf.php');
require('includes/dbh.inc.php');
session_start();



class myPDF extends FPDF {
	function header() {
		$this->Image('../images/logo(dbs).png',10,6);
		$this->SetFont('Arial','B',14);
		$this->Cell(276,5,'User Report',0,0,'C');
		$this->Ln();
		$this->SetFont('Times', '',12);
		$this->Cell(276,10,'WAREHOUSE DEPARTMENT',0,0,'C');
		$this->Ln(20);

	}
	function footer() {
		$this->SetY(-15);
		$this->SetFont('Arial','',8);
		$this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
	}
	function headertable() {
		$this->SetFont('Times','B',12);
		$this->Cell(40,20,'WH#1 Finished',0,1,'C');
		$this->Cell(34,10,'Firstname',1,0,'C');
		$this->Cell(34,10,'Lastname',1,0,'C');
		$this->Cell(65,10,'Lesson Title',1,0,'C');
		$this->Cell(25,10,'Status',1,0,'C');
		$this->Cell(40,10,'Finished',1,0,'C');
		$this->Ln();

	}

	function headertable1() {
		$this->SetFont('Times','B',12);
		$this->Cell(40,20,'WH#1 Unfinished',0,1,'C');
		$this->Cell(34,10,'Firstname',1,0,'C');
		$this->Cell(34,10,'Lastname',1,0,'C');
		$this->Cell(65,10,'Lesson Title',1,0,'C');
		$this->Cell(25,10,'Status',1,0,'C');
		$this->Cell(40,10,'Finished',1,0,'C');
		$this->Ln();

	}
	function viewTable($conn) {
		$this->SetFont('Times', '',12);
		$stmt = $conn->query('SELECT DISTINCT firstname, lastname, lessontitle, status, finished FROM report 
				      WHERE lessontitle!="no lesson taken yet" AND user_type="user" AND whID="1" AND acnt_stats="active"
			              ORDER BY lessontitle DESC');
		while($data = $stmt->fetch_object()) {
			$this->Cell(34,10,$data->firstname,1,0,'L');
			$this->Cell(34,10,$data->lastname,1,0,'L');
			$this->Cell(65,10,$data->lessontitle,1,0,'L');
			$this->Cell(25,10,$data->status,1,0,'L');
			$this->Cell(40,10,$data->finished,1,0,'L');
			$this->Ln();
		}
	}

	function viewTable1($conn) {
		$this->SetFont('Times', '',12);
		$stmt = $conn->query('SELECT DISTINCT firstname, lastname, lessontitle, status, finished FROM report 
				      WHERE lessontitle="no lesson taken yet" AND user_type="user" AND whID="1" AND acnt_stats="active"
				      ORDER BY lessontitle DESC');

		while($data = $stmt->fetch_object()) {
			$this->Cell(34,10,$data->firstname,1,0,'L');
			$this->Cell(34,10,$data->lastname,1,0,'L');
			$this->Cell(65,10,$data->lessontitle,1,0,'L');
			$this->Cell(25,10,$data->status,1,0,'L');
			$this->Cell(40,10,$data->finished,1,0,'L');
			$this->Ln();
		}
	}
}


$pdf = new myPDF();
$pdf->AliasNbPages();
$pdf->AddPage('P','Letter',0);
$pdf->headertable();
$pdf->viewTable($conn);
$pdf->AddPage('P','Letter',0);
$pdf->headertable1();
$pdf->viewTable1($conn);
$pdf->Output();

Здесь я хочу получить данные сеанса:

if (!isset($submit)) {
    echo 'failed to update!';
 } else {   

    // for insert statement
    $acnt_status = $_SESSION['acnt_status'];
    $wh = $_SESSION["whID"];
    $user_type = $_SESSION['user']['user_type'];
    //update report data from database.
    $user = $_SESSION['user']['firstname'];
    $lname = $_SESSION['user']['lastname'];
    $dept = $_GET['dept'];
    $ica = $_SESSION['status2'];
    $lID = $_SESSION['title'];
    $stmt = mysqli_stmt_init($conn); 

    $result = $conn->query("SELECT * FROM report 
                            WHERE lessontitle = '$lID' AND status='registered' AND lastname='$lname' AND firstname='$user'");
    //check of there existing data in the database
    if ($result && mysqli_num_rows($result) > 0) {
        //if yes, update the data in database
        $query = "UPDATE report SET lessontitle='$lID', status='$ica', finished=NOW() 
                  WHERE lastname='$lname' AND firstname='$user' AND status='registered'";
        $result = mysqli_query($conn, $query);// use for executing multiple query a single query statement.
        echo'yes';
    } else {
        //check again if there's already data in database
        $result = $conn->query("SELECT * FROM report 
                                WHERE lessontitle = '$lID'
                                AND lastname='$lname' AND firstname='$user'");
        //check of there existing data in the database
        if ($result && mysqli_num_rows($result) > 0) {
            echo'there is';
        } else {
            //if no, insert new data in database
            mysqli_stmt_execute($stmt);
            $result = mysqli_stmt_get_result($stmt);

            $sql = "INSERT INTO report (firstname, lastname, lessontitle, status, department, acnt_stats, whID, user_type, finished)        VALUES (?,?,?,?,?,?,?,?,NOW())";
            if (!mysqli_stmt_prepare($stmt, $sql)) {
            echo "SQL statement failed";
            } else {
                mysqli_stmt_bind_param($stmt, "ssssssis", $user, $lname, $lID, $ica, $dept, $acnt_status, $wh, $user_type);
                mysqli_stmt_execute($stmt);
                echo 'no';
        }
    }
}

}

И это страница, на которой администраторыбудет генерировать отчеты:

<div class="listbody">
<div class="list" style="font-size:1.5vw;">
<?php
    if (!count($reportOpex)) {
        echo 'no record';
    } else {
?>
    <table>
        <thead>
            <tr>
                <th colspan="5" style=" background-color: #EF3842;" class="uReport">User Report</th>
            <tr>
                <th>Firstname</th>
                <th>LastName</th>
                <th>Lesson Title</th>
                <th>Status</th>
                <th>Date&Time finished</th>
            </tr>
        </thead>
        <tbody>
            <form action="GenReport.php" method="post">
            <?php
            foreach($reportOpex as $r) {
            ?>
            <tr>
                <td><?php echo escape($r->firstname)?></td>
                <td><?php echo escape($r->lastname); ?></td>
                <td><?php echo escape($r->lessontitle); ?></td>
                <td><?php echo escape($r->status); ?></td>
                <td><?php echo escape($r->finished); ?></td>

            </tr>

            <?php
            }
            ?>
        </tbody>
            <tr>
                <th colspan="5" style=" background-color: #6495ED"><button class="gReport"><b>Generate Report &#9658;</b></button></th>
            </tr>
            </form>
    </table>
<?php
}
?>

Я просто хочу получить whID, поэтому я могу использовать его в своем предложении WHERE в выражении SELECT.Спасибо!

1 Ответ

0 голосов
/ 07 февраля 2019

Я исправил свою проблему.Я поместил данные сеанса перед поиском require('../fpdf/fpdf.php');, в котором fpdf не хочет иметь переменную в диапазоне от require('../fpdf/fpdf.php'); до конца кода fpdf.

Вот что я сделал, чтобы решить мою проблему:

<?php
session_start();
$_SESSION['warehouseID'] = $_POST['warehouseID'];

require('../fpdf/fpdf.php');
require('includes/dbh.inc.php');




class myPDF extends FPDF {
	function header() {
		$this->Image('../images/logo(dbs).png',10,6);
		$this->SetFont('Arial','B',14);
		$this->Cell(276,5,'User Report',0,0,'C');
		$this->Ln();
		$this->SetFont('Times', '',12);
		$this->Cell(276,10,'WAREHOUSE DEPARTMENT',0,0,'C');
		$this->Ln(20);

	}
	function footer() {
		$this->SetY(-15);
		$this->SetFont('Arial','',8);
		$this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');
	}
	function headertable() {
		$this->SetFont('Times','B',12);
		$this->Cell(40,20,'WH#1 Finished',0,1,'C');
		$this->Cell(34,10,'Firstname',1,0,'C');
		$this->Cell(34,10,'Lastname',1,0,'C');
		$this->Cell(65,10,'Lesson Title',1,0,'C');
		$this->Cell(25,10,'Status',1,0,'C');
		$this->Cell(40,10,'Finished',1,0,'C');
		$this->Ln();

	}

	function headertable1() {
		$this->SetFont('Times','B',12);
		$this->Cell(40,20,'WH#1 Unfinished',0,1,'C');
		$this->Cell(34,10,'Firstname',1,0,'C');
		$this->Cell(34,10,'Lastname',1,0,'C');
		$this->Cell(65,10,'Lesson Title',1,0,'C');
		$this->Cell(25,10,'Status',1,0,'C');
		$this->Cell(40,10,'Finished',1,0,'C');
		$this->Ln();

	}
	function viewTable($conn) {
		$this->SetFont('Times', '',12);
		$stmt = $conn->query("SELECT DISTINCT firstname, lastname, lessontitle, status, finished FROM report 
							  WHERE lessontitle!='no lesson taken yet' AND user_type='user' AND whID='{$_SESSION['warehouseID']}' AND acnt_stats='active'
							  ORDER BY lessontitle DESC");
		while($data = $stmt->fetch_object()) {
			$this->Cell(34,10,$data->firstname,1,0,'L');
			$this->Cell(34,10,$data->lastname,1,0,'L');
			$this->Cell(65,10,$data->lessontitle,1,0,'L');
			$this->Cell(25,10,$data->status,1,0,'L');
			$this->Cell(40,10,$data->finished,1,0,'L');
			$this->Ln();
		}
	}

	function viewTable1($conn) {
		$this->SetFont('Times', '',12);
		$stmt = $conn->query("SELECT DISTINCT firstname, lastname, lessontitle, status, finished FROM report 
							  WHERE lessontitle='no lesson taken yet' AND user_type='user' AND whID='{$_SESSION['warehouseID']}' AND acnt_stats='active'
							  ORDER BY lessontitle DESC");

		while($data = $stmt->fetch_object()) {
			$this->Cell(34,10,$data->firstname,1,0,'L');
			$this->Cell(34,10,$data->lastname,1,0,'L');
			$this->Cell(65,10,$data->lessontitle,1,0,'L');
			$this->Cell(25,10,$data->status,1,0,'L');
			$this->Cell(40,10,$data->finished,1,0,'L');
			$this->Ln();
		}
	}
}


$pdf = new myPDF();
$pdf->AliasNbPages();
$pdf->AddPage('P','Letter',0);
$pdf->headertable();
$pdf->viewTable($conn);
$pdf->AddPage('P','Letter',0);
$pdf->headertable1();
$pdf->viewTable1($conn);
$pdf->Output();

Как вы можете видеть в верхней части кода, есть данные сеанса, которые у меня есть на предыдущей странице.И я использую whID='{$_SESSION['warehouseID']}' в операторе SELECT, чтобы fpdf считывал переменную из сеанса.Я перепробовал все, но это единственный способ (в моем случае) fpdf будет читать переменную сессии.Я надеюсь, что это будет полезно для начинающих программистов, как и я!

...