2016-07-28 33 views
0

我想顯示數據庫和csv文件中的數據。我*若i顯示從數據庫和CSV兩種,但在CSV功能數據的PHP中使用哎呀m該是以下錯誤:我如何使用oops在php中顯示csv文件

syntax error, unexpected '$f' (T_VARIABLE), expecting function (T_FUNCTION) in D:\xampp\htdocs\factory\4.php on line 71

代碼:

<?php 
 
interface IDatabase { 
 
    function connect(); 
 
\t function readCSV(); 
 
} 
 

 

 
class Db implements IDatabase 
 
{ 
 
    private $connection; 
 
    private static $instance; 
 

 
    private function __construct() 
 
    { 
 
     $host = "localhost"; 
 
     $user = "root"; 
 
     $pass = ""; 
 
     $name = "cart"; 
 

 
     $this->connection = new mysqli($host, $user, $pass, $name); 
 
    
 
    if(mysqli_connect_error()) { 
 
\t \t \t trigger_error("Failed to conencto to MySQL: " . mysqli_connect_error(), 
 
\t \t \t \t E_USER_ERROR); 
 
\t \t } 
 

 
    } 
 

 
    public function connect() 
 
    { 
 
     if (self::$instance == null) { \t \t \t 
 
      self::$instance = new Db(); 
 
     } 
 

 
     return self::$instance; 
 
    } 
 

 
    public function query($sql) 
 
    { 
 
     $result = $this->connection->query($sql); 
 
     $records = array(); 
 
     while ($row = $result->fetch_assoc()) { 
 
      $records[] = $row; 
 
     } 
 
     return $records; 
 
    } 
 
} 
 

 

 
$db1 = Db::connect(); 
 

 

 

 

 

 
$query = $db1->query("SELECT * FROM user_info"); 
 
foreach($query as $row=>$val) 
 
{ echo '<tr>'; 
 
       echo '<td>'.$val['id'].'</td>'; 
 
       echo '<td>'.$val['username'].'</td>'; 
 
       echo '<td>'.$val['email'].'</td>'; 
 
\t \t \t \t echo '<td>'.$val['password'].'</td>'; 
 
\t \t \t \t echo '</tr>'; 
 
} \t \t \t \t 
 

 
class csv implements IDatabase{ 
 
public function readCSV($f){fclose($f);} 
 

 

 

 
$f = fopen("http://localhost/csv/cr.csv", "r"); 
 
while (($line = fgetcsv($f)) !== false) { 
 
     echo "<tr>"; 
 
\t \t $data = count($line); 
 
     foreach ($line as $cell) { 
 
       echo "<td>" . htmlspecialchars($cell) . "</td>"; 
 
     } 
 
     echo "</tr>\n"; 
 
} 
 

 
?>

回答

1

就像它說的那樣,有一個語法錯誤。在一個類中,你不能通過調用一個函數來指定一個成員變量。此外,你不能直接在課堂上開始一段時間的陳述,這是一種方法的工作。

下面是更多的東西一樣,你需要

class Csv { 
    private $_file; 

    public function __construct($path) { 
      $this->_file = fopen($path, "r"); 
    } 

    public function closeCsv() 
    { 
      fclose($this->_file); 
    } 

    public function readCsv() { 
     // I strongly recommend not echoing out here. This should just return the content 
     return fgetcsv($this->_file) 
    } 
} 

什麼,然後你會使用它像

<?php 
    $csv = new Csv("/path/to/file.csv"); 
    while (($line = $csv->readCsv()) !== false) { 
     //Do what you wanna do 
    } 

    //When done, close it 
    $csv->closeCsv() 

的代碼測試未啓用的,但我會想你明白了吧。如果沒有,結帳更多關於OOP,例如在這裏http://code.tutsplus.com/tutorials/object-oriented-php-for-beginners--net-12762