2013-12-10 90 views
-1

我是PHP OOP的新手,所以我做了一個小遊戲,你必須猜測一個數字。現在我試圖在數據庫中添加一些分數,如果你沒有錯的話。PHP OOP(PDO)的問題

我已經嘗試了許多很多很多事情來讓它工作,但它沒有。此外,由於某些原因,我不瞭解我的$ db variabel。我一直在谷歌搜索幾個小時,但我找不到它。所以,請幫我出^^ 錯誤,我得到我贏:

Notice: Undefined variable: db in C:\xampp\htdocs\numbergame\class\game.php on line 14 

Fatal error: Call to a member function execute() on a non-object in C:\xampp\htdocs\numbergame\class\game.php on line 14 

db.php中:

<?php 
try { 
    $db = new PDO('mysql:host=localhost;dbname=numbergame', 'root', ''); 
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

} catch(PDOException $e) { 
    echo 'ERROR: ' . $e->getMessage(); 
} 
?> 

game.php:

<?php 
include('/DB.php'); 
class game { 

public $rand; 
public $num; 

public function __construct() { 
    $this->rand = mt_rand(1, 2); 

} 
public function addScore() { 
    $sql = "UPDATE user SET score = '1' WHERE name = 'Dieter'"; 
    $db->execute($sql); 
} 
public function guess() { 
    $this->num = $_POST["num"]; 
    if($this->num == $this->rand) { 
     echo "You won! With the number: ".$this->rand."<br />"; 
     echo "Added score with 1"; 
     $this->addScore(); 
    } else { 
     echo "You lose! The number was: 1"; 
} 
} 
public function check() { 
    if($_SERVER['REQUEST_METHOD'] == "POST") { 
    $this->guess(); 
    } else { 
     echo '<form action="index.php" method="POST">'; 
     echo 'Guess a number between 1-10 <br />'; 
     echo '<input type="text" name="num" ><br />'; 
     echo '<input type="submit" value="go!">'; 
     echo '</form>'; 
    } 
    } 



    } 

?> 

的index.php

<?php 
include("class/game.php"); 

$NumberGame = new game(); 
$NumberGame->check(); 
/* I made this to test if the DB works here. And it does. 
$select = "SELECT score FROM user"; 
$results = $db->query($select); 

foreach($results as $row) { 
    echo $row['score'].'<br>'; 
} 
*/ 
?> 
+4

什麼是你的錯誤? – kanenas

+0

'addScore()'中的'$ db'變量到底有多精確? –

+0

它是可變範圍。你在你的類中使用'$ db',但是它沒有在那裏定義,所以你使用了一個局部變量。 – andrewsi

回答

3

你沒有提到確切的p roblem是,但這是錯誤的:

public function addScore() { 
    $sql = "UPDATE user SET score = '1' WHERE name = 'Dieter'"; 
    $db->execute($sql); 
} 

$db沒有在你的方法的範圍界定,見variable scope

1

在OOP中,您無權訪問所有變量。所以你必須將你的$db var傳遞給對象。

protected $_db; 

public function __construct($db) { 
    $this->_db = $db; 
    ... 
} 

public function addScore() { 
    $sql = "UPDATE user SET score = '1' WHERE name = 'Dieter'"; 
    $this->_db->execute($sql); 
} 

它傳遞到目標:

include('/DB.php'); 

$NumberGame = new game($db); 
0

如果使用包括在一個類中,並在結束了這樣的事情:

$db = new DB(); 

class Car 
{ 

    public function getCars() 
    { 
     return $db->query("SELECT * FROM cars"); 
    } 
} 

方法getCars()$db變量根本不知道 - 它不在方法(類別)範圍內...

正確的做法(許多之一):

$db = new DB(); 

$car = new Car($db); 
print_r($car->getCars()); 

時,您有這樣的事情:

class Car 
{ 

    public function __construct(DB $db) 
    { 
     $this->db = $db; 
    } 

    public function getCars() 
    { 
     return $this->db->query("SELECT * FROM cars"); 
    } 
}