【问题标题】:How to use the oop in reading from mysql in mysql?如何在mysql中使用oop从mysql中读取?
【发布时间】:2016-06-14 11:44:12
【问题描述】:

我正在尝试使用 php 和 oop 从 mysql 读取。如何使用 from propeties?

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

<?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();
    }
}
}

我希望 search() 是基于对象和属性的。

如何更改我的代码?

【问题讨论】:

  • 你能给标题改一下吗?
  • 我有一个电影列表,希望用户可以按“名称”或“国家”或“年份”或...进行搜索。

标签: php mysql oop


【解决方案1】:

您的意思是要调用该函数吗? 只需将此代码放在您想要放置的任何位置,例如 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);

【讨论】:

  • 搜索中的参数($name,$year,$country,$director) 是从客户端发布的。我想从类属性中使用,例如“public $name”..example 用于创建连接,我使用来自 $conn。通常我想使用面向对象。
猜你喜欢
  • 2017-05-16
  • 2011-09-16
  • 2023-03-18
  • 1970-01-01
  • 2015-03-25
  • 1970-01-01
  • 2020-10-31
  • 2016-11-16
  • 2013-09-06
相关资源
最近更新 更多