Skip to main content
edited tags; edited title
Link
200_success
  • 144.2k
  • 22
  • 188
  • 473

Can I call this OOP? How can I improve this line of code of PHP? Storing, fetching, and deleting battle simulation results

Source Link

Can I call this OOP? How can I improve this line of code of PHP?

my connection code:

    <?php
try {
    $pdo = new PDO("mysql:host=localhost;dbname=game;
    charset=utf8", "root");
}
catch(PDOException $e){
    echo $e->getMessage();
}
?>

my class code:

    <?php
include './database/config.php';

class DB {
    public function dataWarrior($battle,$name,$type){
        global $pdo;
        try {
            $stmt = $pdo->prepare("SELECT battle_id,warrior_name,warrior_type,health,attack,defense,speed,evade
            FROM battle WHERE battle_id = :battle AND warrior_name = :name AND warrior_type = :type LIMIT 1");
            
            $stmt->execute(array(":battle"=>$battle, ":name"=>$name, ":type"=>$type));
            
            return $stmt;
        }
        catch(PDOException $e){
            echo $e->getMessage();
        }
    }
    public function checkBattleID($battle){
        global $pdo;
        try {
            $stmt = $pdo->prepare("SELECT battle_id FROM battle WHERE battle_id=:battle LIMIT 1");
            
            $stmt->execute(array(":battle"=>$battle));
            
            if($stmt->rowCount()>0){
                return false;
            }
            else {
                return true;
            }
        }
        catch(PDOException $e){
            echo $e->getMessage();
        }
    }
    public function createBattle($warrior){
        global $pdo;
        try {
            $stmt = $pdo->prepare('INSERT INTO battle(battle_id,warrior_name,warrior_type,
            health,attack,defense,speed,evade) VALUES(:battle,:name,:type,:health,:attack,:defense,:speed,:evade)');
            
            $stmt->execute(array(':battle'=>$warrior['battle'], ':name'=>$warrior['name'], 
            ':type'=>$warrior['type'], ':health'=>$warrior['health'], ':attack'=>$warrior['attack'],
            ':defense'=>$warrior['defense'], ':speed'=>$warrior['speed'], ':evade'=>$warrior['evade']));            
        }
        catch(PDOException $e){
            echo $e->getMessage();  
        }   
    }
    public function deleteBattle($battle){
        global $pdo;
        try {
            $stmt = $pdo->prepare('DELETE FROM battle WHERE battle_id = :battle');
            $stmt->execute(array(':battle'=>$battle));
        }
        catch(PDOException $e){
            echo $e->getMessage();  
        }
    }
}
?>