2016-06-14 88 views
1

我试图从MySQL读取与PHP和oop.How可以使用从propeties?如何在mysql中使用oop读取mysql数据?

这是从数据库中读取我的阶级和搜索功能:

<?php 
require_once('dbconfig.php'); 

class Film { 

public $name; 
public $year; 
public $country; 
public $director; 
private $conn; 

public function __construct() { 
    $database = new Database(); 
    $db = $database->dbConnection(); 
    $this->conn = $db; 
} 

public function runQuery($sql) { 
    $stmt = $this->conn->prepare($sql); 
    return $stmt; 
} 
public function search($name,$year,$country,$director) { 
    try { 
     $stmt = $this->conn->prepare("SELECT * FROM table where name='$name' or year='$year' or country='$country' or director='$director'"); 
     $stmt->execute(); 
     $num_rows = $stmt->rowCount(); 
     if ($num_rows > 0) { 

      echo "</br>".$num_rows."&nbsp; film is found. </br>"; 
      echo "</br><table><tr><th>Name</th><th>Year</th><th>Country</th><th>durationMinutes</th><th>Director</th></tr>"; 

      while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 

       echo "<tr><td>" . $row['name'] . "</td><td>" . $row['year'] . "</td><td>" . $row['country'] . "</td><td>" . $row['durationMinutes'] . "</td><td>" . $row['director'] . "</td></tr>"; 
      } 
      echo "</table>"; 
     } else { 
      echo "Nothing found !"; 
     } 
    } catch (PDOException $e) { 
     echo $e->getMessage(); 
    } 
} 
} 

我想搜索()是基于对象和属性上。

如何更改我的代码?

+0

你能给标题整容? – Drew

+0

我有一个电影列表,并希望用户可以按'名称'或'国家'或'年份'或...进行搜索。 –

回答

2

你的意思是你想调用那个函数吗? 只是把这个代码放在任何地方,例如在index.php中。

$film->search($name,$year,$country,$director); 

,但你必须初始类电影中的连接文件中像这样

session_start(); 
$host = "localhost"; 
$user = "root"; 
$pass = ""; 
$database="database"; 
try { 
$con = new PDO ("mysql:host={$host}; dbname={$database}", $user, $pass); 
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
//$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); 
} 
catch (PDOEXception $e) { 
echo $e->getMessage(); 
} 
include_once 'class_film.php'; 
$film= new Film($con); 
+0

搜索参数($ name,$ year,$ country,$ director)从客户端发布。我想从类属性中使用例如“public $ name”.. .example创建连接,我使用$ conn。一般我想使用面向对象。 –