我是PHP OOP的新手所以我在其中制作了一个小游戏,您必须猜测一个数字。现在我正试图在数据库中添加一些分数,如果你做对了。
我尝试了许多很多东西才能让它发挥作用,但事实并非如此。此外,由于某些我不理解的原因,它没有重新调整我的$ db变量。我一直在谷歌搜索几个小时,但我找不到它。所以请帮帮我^^ 我赢的时候得到的错误:
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>';
}
*/
?>
答案 0 :(得分:3)
你没有提到确切的问题是什么,但这是错误的:
public function addScore() {
$sql = "UPDATE user SET score = '1' WHERE name = 'Dieter'";
$db->execute($sql);
}
$db
未在您的方法范围内定义,请参阅variable scope。
答案 1 :(得分: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);
答案 2 :(得分:0)
如果你在一个类中使用include并且最终有这样的东西:
$db = new DB();
class Car
{
public function getCars()
{
return $db->query("SELECT * FROM cars");
}
}
方法$db
中的getCars()
变量根本不知道 - 它不在方法(类)范围内...
正确的方法(许多之一):
$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");
}
}