一个类文件适用于其他类文件。它处理不当

时间:2016-01-03 09:05:20

标签: php mysql

这里是config.php

<?php 
define('DB_DSN','mysql:host=localhost;dbname=sales');
define('DB_USERNAME','root');
define('DB_PASSWORD','');
define("TBL_MEMBERS",'member');
define('TBL_PURCHASE','purchase');
define('TBL_SALES','sales');

?>

这是dataObject.class.php

<?php
require_once('config.php');
abstract class DataObject{
protected $data=array();

public function __construct($data){
    foreach($data as $key=>$value){
        if(array_key_exists($key, $this->data))
            $this->data[$key]=$value;
    }
}

public function getValue($field){
    if(array_key_exists($field, $this->data)){
        return $this->data[$field];
    }else{
        throw new Exception("Field is not found", 1);

    }
}

public function getValueEncoded($field){
    return htmlspecialchars($this->getValue($field));
}

protected function connect(){
    try {
        $conn=new PDO(DB_DSN,DB_USERNAME,DB_PASSWORD);
        $conn->setAttribute(PDO::ATTR_PERSISTENT,true);
        $conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    } catch (Exception $e) {
        throw new Exception("Connection failed", 1);

    }
    return $conn;
}

protected function disconnect($conn){
    $conn='';
}


} 


 ?>

这是我的customer.class.php文件

<?php 
require_once("DataObject.class.php");

class Customer extends DataObject{
protected $data=array(
    'id'=>'',
    'customerName'=>'',
    'totalPrice'=>'',
    'date'=>''
    );

public static function getCutomers($startRow,$numRows,$order){
    $conn=parent::connect();
    $sql="SELECT SQL_CALC_FOUND_ROWS*FROM ".TBL_SALES." ORDER BY $order LIMIT :startRow, :numRows";
    try {
        $st=$conn->prepare($sql);
        $st->bindValue(":startRow",$startRow,PDO::PARARM_INT);
        $st->bindValue(":numRows",$numRows,PDO::PARAM_INT);
        $st->execute();
        $purchases=array();
        foreach($st->fetchAll() as $row){
            $customers[]=new Customer($row);
        }
        $st=$conn->query("SELECT found_rows() AS totalRows");
        $row=$st->fetch();
        parent::disconnect($conn);
        return array($customers,$row['totalRows']);
    } catch (Exception $e) {
        parent::disconnect($conn);
        throw new Exception("Error Processing Query Request", 1);

    }
}

public static function getcustomer($id){
    $conn=parent::connect();
    $sql="SELECT*FROM ".TBL_SALES."WHERE id=:id";
    try {
        $st=$conn->prepare($sql);
        $st->bindValue("id",$id,PDO::PARAM_INT);
        $st->execute();
        $row=$st->fetch();
        parent::disconnect($conn);
        if($row) return new Customer($row);
    } catch (Exception $e) {
        parent::disconnect($conn);
        throw new Exception("Error Processing Query Request", 2);

    }
}

public function insert(){
    $conn=parent::connect();
    $sql="INSERT INTO ".TBL_SALES."(
        customerName,
        totalPrice,
        date)VALUES(
        :customerName,
        :totalPrice,
        :NOW()
        )";
    try {
        $st=$conn->prepare($sql);
        $st->bindValue(":customerName",$this->data["customerName"],PDO::PARAM_STR);
        $st->bindValue(":totalPrice",$this->data["totalPrice"],PDO::PARAM_INT);
        //$st->bindValue(":date",$this->data["date"],PDO::PARAM_STR);
        $st->execute();
        parent::disconnect($conn);
    } catch (Exception $e) {
        parent::disconnect($conn);
        throw new Exception("Error Processing Query Request", 9);

    }
}
}

 ?>

这是company.class.php文件:

      <?php 
     require_once("DataObject.class.php");

       class Company extends DataObject{
      protected $data=array(
    'id'=>'',
    'companyName'=>'',
    'purchase'=>'',
    'date'=>''
    );

public static function getCompanies($startRow,$numRows,$order){
    $conn=parent::connect();
    $sql="SELECT SQL_CALC_FOUND_ROWS*FROM ".TBL_PURCHASE." ORDER BY $order LIMIT :startRow, :numRows";
    try {
        $st=$conn->prepare($sql);
        $st->bindValue(":startRow",$startRow,PDO::PARARM_INT);
        $st->bindValue(":numRows",$numRows,PDO::PARAM_INT);
        $st->execute();
        $purchases=array();
        foreach($st->fetchAll() as $row){
            $companies[]=new Company($row);
        }
        $st=$conn->query("SELECT found_rows() AS totalRows");
        $row=$st->fetch();
        parent::disconnect($conn);
        return array($companies,$row['totalRows']);
    } catch (Exception $e) {
        parent::disconnect($conn);
        throw new Exception("Error Processing Query Request", 1);

    }
}

public static function getcompany($id){
    $conn=parent::connect();
    $sql="SELECT*FROM ".TBL_PURCHASE."WHERE id=:id";
    try {
        $st=$conn->prepare($sql);
        $st->bindValue("id",$id,PDO::PARAM_INT);
        $st->execute();
        $row=$st->fetch();
        parent::disconnect($conn);
        if($row) return new Company($row);
    } catch (Exception $e) {
        parent::disconnect($conn);
        throw new Exception("Error Processing Query Request", 2);

    }
}

public function insert(){
    $conn=parent::connect();
    $sql="INSERT INTO ".TBL_PURCHASE."(
        companyName,
        purchase,
        date)VALUES(
        :companyName,
        :purchase,
        NOW()
        )";
    try {
        $st=$conn->prepare($sql);
        $st->bindValue(":companyName",$this->data["companyName"],PDO::PARAM_STR);
        $st->bindValue(":purchase",$this->data["purchase"],PDO::PARAM_INT);
        $st->bindValue(":date",$this->data["date"],PDO::PARAM_STR);
        $st->execute();
        parent::disconnect($conn);
    } catch (Exception $e) {
        parent::disconnect($conn);
        throw new Exception("Error Processing Query Request", 3);

    }
}

 }

  ?>

这是purchase.php这与public.class.php工作正常,并将数据输入到mysql数据库

<?php

require_once("config.php");

require_once("company.class.php");


 if(isset($_POST["action"]) and $_POST["action"]=="add"){
 companyProcessForm();
} else{
companyForm(array(),array(),new Company(array()));
 }

  function companyForm($errorMessages,$missingFields,$company){

  if($errorMessages){
       foreach($errorMessages as $errorMessage){
          echo $errorMessage;
      }
    }else{

     ?>
  <form action="index.php" method="post" style="margin-bottom:50px;">
       <div style="width:30em;">
        <input type="hidden" name="action" value="add">
        <label for="companyName"<?php validateField("companyName",$missingFields)?>>Company Name*:</label>
    <input type="text" name="companyName" id="companyName" value="<?php echo $company->getValueEncoded('companyName')?>">
    </div>
    <div>
    <label for="purchase"<?php if($missingFields) echo 'class="error"'?>>Purchase(Taka)</label>
    <input type="text"name="purchase"id="purchase"value="">
</div>
<div style="clear:both;">
    <input type="submit" name="submitButton" id="submitButton" value="add">
</div>

</form>
<?php 
   }
  }
 function companyProcessForm(){
   $missingFields=array();
   $errorMessages=array();
   $company=new Company(array(
    "companyName"=>isset($_POST["companyName"])? preg_replace("/[^ \-\_a-zA-Z0-9]/", "", $_POST["companyName"]):"",
    "purchase"=>isset($_POST["purchase"])? preg_replace("/[^\.\ 0-9]/", "", $_POST["purchase"]):""
    // "date"=>mow()
    ));
if($missingFields){
    $errorMessages[]='<p class="error">Please fill up all fields highlighted below.<p>';
}
if($errorMessages){
    companyForm($errorMessages,$missingFields,$company);
    // header("Location: index.php");
}else{
    $company->insert();
    header("Location: index.php");
  }
  }
  ?>

这是index.php

<?php
 ob_start();
 require_once("common.inc.php");
 require_once("config.php");

 displayPageHeader("Purchase/Sales Report");

 include("purchase.php");

 displayPageFooter();

  ?>

这是sales.php

<?php

 require_once("config.php");
 require_once("customer.class.php");

 if(isset($_POST["action"]) and $_POST["action"]=="submit"){
  customerProcessForm();
  } else{
 customerForm(array(),array(),new Customer(array()));
  }

 function customerForm($errorMessages,$missingFields,$customer){

  if($errorMessages){
     foreach($errorMessages as $errorMessage){
         echo $errorMessage;
     }
  }else{
  ?>
<form action="index.php" method="post" style="margin-bottom:50px;">
    <div style="width:30em;">
    <div style="width:30em;">
    <input type="hidden" name="action" value="submit">
    <label for="customerName"<?php validateField("customerName",$missingFields)?>>Customer Name*:</label>
    <input type="text" name="customerName" id="customerName" value="<?php echo $customer->getValueEncoded('customerName')?>">
    </div>
    <div>
    <label for="totalPrice"<?php if($missingFields) echo 'class="error"'?>>Total Price(Taka)</label>
    <input type="text"name="totalPrice"id="totalPrice"value="">
</div>
<div style="clear:both;">
    <input type="submit" name="submitButton" id="submitButton" value="submit">
</div>

   </form>
   <?php } } 

  function customerrocessForm(){
$missingFields=array();
$errorMessages=array();
$customer=new Customer(array(
    "customerName"=>isset($_POST["customerName"])? preg_replace("/[^ \-\_a-zA-Z0-9]/", "", $_POST["customerName"]):"",
    "totalPrice"=>isset($_POST["totalPrice"])? preg_replace("/[^\.\ 0-9]/", "", $_POST["totalPrice"]):"",
    // "date"=>mow()
    ));
if($missingFields){
    $errorMessages[]='<p class="error">Please fill up all fields highlighted below.<p>';
}
if($errorMessages){
    customerForm($errorMessages,$missingFields,$customer);

}else{
    $customer->insert();
    header("Location: sales_report.php");
  }

 }

  ?>

这个slase_report.php当我输入数据时它重定向我index.php并没有输入到mysql表sales。另外它不能与customer.class.php一起显示company.class.php上的company.class.php未捕获异常插入函数

     <?php
       ob_start();
       require_once("common.inc.php");
       require_once("config.php");
       require_once('customer.class.php');

     displayPageHeader("Sales Report");
      include("sales.php");
      displayPageFooter();

       ?>

错误是:

  

[Sun Jan 03 12:15:52.564636 2016] [:error] [pid 4252] [client :: 1:60871] PHP致命错误:未捕获异常&#39;异常&#39;使用消息&#39;错误处理查询请求&#39;在/var/www/html/salesReport/company.class.php:71\nStack trace:\ n#0 /var/www/html/salesReport/purchase.php(57):Company-&gt; insert()\ n #1 /var/www/html/salesReport/purchase.php(10):companyProcessForm()\ n#2 /var/www/html/salesReport/index.php(8):include(&#39; / var / www / html / s ...&#39;)\ n#3 {main} \ n在第71行的/var/www/html/salesReport/company.class.php中引用,引用:http://localhost/salesReport/sales_report.php   `

 `

提前致谢

0 个答案:

没有答案