我对使用 PHP 编程非常陌生,并且正在开发一个有趣的小游戏来帮助自己学习。我从其他人那里得到了一些关于从数据库中提取角色统计信息的代码帮助,但在让它工作时遇到了麻烦。当我现在尝试运行它时,我只是得到“服务器错误”。数据库信息很好,我以前有一个从数据库中提取的工作函数,但想通过一个类函数来通用化它。这是我到目前为止所拥有的。
数据库类:
<?php
class db_class
{
//db connection portion
protected $mysqli;
private $db_host = 'XXXXXXX';
private $db_user = 'Filler';
private $db_password = 'Filler';
protected $db_name = 'Filler';
//db connection portion
public function __construct($db_host = null, $db_user = null, $db_password = null, $db_name = null) {
if (!empty($db_host)) {
$this->db_host = $db_host;
}
// validate other parameters similarly
//database connection object
$mysqli = new mysqli($this->db_host, $this->db_user, $this->db_password, $this->db_name);
if ($mysqli->connect_error) {
throw new Exception('Connect Error: ' . $mysqli->connect_errno . ', ' . $mysqli->connect_error);
} else {
$this->mysqli = $mysqli;
}
}
public function getPlayerStats($id) {
if (empty($id)) {
throw new Exception ('An empty value was passed for id');
}
// verify this is integer-like value
$id = (string) $id;
$pattern = '/^\d+$/';
if (!preg_match($pattern, $id) !== 1) {
throw new Exception ('A non-integer value was passed for id');
}
$id = (int) $id;
$query = "SELECT id, name, strength, defense, level, health, type, experience FROM characters WHERE id = :id";
$stmt = $this->mysqli->prepare($query);
$stmt->bind_param('i', $id);
$result = $stmt->execute();
if (false === $result) {
throw new Exception('Query error: ' . $stmt->error);
} else {
$obj = new stdClass();
$stmt->bind_result($obj->id, $obj->name, $obj->strength, $obj->defense, $obj->level, $obj, health, $obj->type, $obj->experience);
$stmt->fetch();
$stmt->close();
return $obj;
}
}
}
?>
DB类函数调用:
<?php
include "db_class.php";
echo "made it out here1";
$classobject = new db_class();
echo "made it out here2";
$results = $classobject->getPlayerStats('1');
print_r($results);
echo "made it out here3";
$id = "id: " . $results['id'];
$name = "name: " . $results['charname'];
$strength = "strength: " . $results['strength'];
$defense = "defense: " . $results['defense'];
$health = "health: " . $results['health'];
$level = "level: " . $results['level'];
$type = "type: " . $results['type'];
$experience = "experience: " . $results['experience'];
echo "<br/>";
echo "made it out here4";
?>
调试此代码很困难,因为我习惯于在编译器中的 VBA 之类的东西中添加断线并运行编码错误,因此任何调试技巧都会非常有帮助。我在这里做错了什么?提前致谢!