0

I am trying to put URL parameter to sql query in PHP class. I don't know how to do it and when i searching about this i found i cant do it with static variable and also found it can do it with PDO. but i don't have any idea how to do it. please help me to develop below code

class Constants{
    //DATABASE CREDENTIALS
    static $DB_SERVER="localhost";
    static $DB_NAME="digital_reader";
    static $USERNAME="root";
    static $PASSWORD="Wacoal?2023";


    static $SQL_SELECT_ALL="SELECT * FROM science where id={url parameter}";
    //i want to put url parameter to this select statment $id=$_GET['id'];
    
}


class Scientists{
    /**
     * 1. CONNECT TO DATABASE.
     * 2. RETURN CONNECTION OBJECT
     * 3. IF NO CONNECTION THEN RETURN NULL.
     */
    public function connect()
    {
        $con=new mysqli(Constants::$DB_SERVER,Constants::$USERNAME,Constants::$PASSWORD,
        Constants::$DB_NAME);
        if($con->connect_error) {
            return null;
        }else{
            return $con;
        }
    }

 
   public function select()
    {
        $con=$this->connect();
        if($con != null)
        {
            $result=$con->query(Constants::$SQL_SELECT_ALL);
            if($result->num_rows > 0)
            {
                $scientists = array();
                while($row=$result->fetch_array())
                {
                    array_push($scientists, array("id"=>$row['id'],"name"=>$row['name'],
                    "description"=>$row['description'],"galaxy"=>$row['galaxy'],"star"=>$row['star'],
                    "dob"=>$row['dob'],"died"=>$row['died']));
                }
                print(json_encode(array("code" => 1,"message"=>"Success", "result"=>$scientists)));
            }else{
                print(json_encode(array("code" => 0, "message"=>"Data Not Found")));
            }
            $con->close();

        }else{
            print(json_encode(array('code' =>3,
            'message' => 'ERROR: PHP WAS UNABLE TO CONNECT TO MYSQL DUE TO NULL CONNECTION.')));
        }
    }

I tried to do this in pdo by watching and learning but i have no idea

  • Welcome to Stack Overflow, see [How can I prevent SQL injection in PHP?](https://stackoverflow.com/q/60174/2257664). – A.L Jul 26 '23 at 10:38
  • 2
    You can do it with MySQLi as well, see: [PHP MySQL Prepared Statements](https://www.w3schools.com/php/php_mysql_prepared_statements.asp) – KIKO Software Jul 26 '23 at 10:38
  • 1
    Please don't create [multiple accounts](https://stackoverflow.com/q/76765105/231316). As to your code, did you try what I showed you in the comments? I partly feel like OOP is getting in your way, and I'd personally recommend skipping that for now. It provides zero value or performance at this stage. – Chris Haas Jul 26 '23 at 13:13

0 Answers0