我是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>';
}
*/
?>
什麼是你的錯誤? – kanenas
'addScore()'中的'$ db'變量到底有多精確? –
它是可變範圍。你在你的類中使用'$ db',但是它沒有在那裏定義,所以你使用了一個局部變量。 – andrewsi