我是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