2
\$\begingroup\$

Wrote this class it allows me to connect to database and display as many columns as I wish to. I can just give it desired parameters and I'm done. I've commented about the parameters that need it to be passed.

     include('connect.php');
   //include this file. This is our class

   $connection = new connection_to_db;
   //instantiate class

   $connection->make_connection("host_name", "user", "pass", "database_name");
   //1st param: your host name
   //2st param: your username
   //3rd param: your password
   //4th param: your database name

   $connection->run_test_query("shouts", "id", 2);
   //1st param: your table name.
   //2nd param: which column to show.
   //3rd param: how many results to display.

class connection_to_db{
     function make_connection($host, $user, $pass, $db){
       global $conn;
       try{
         $conn = new pdo("mysql: host=". $host . ";dbname=". $db, $user, $pass);         
       }catch(PDOException $error){
         echo $error->getMessage();
         die();
       }
     }

     function run_test_query($shouts, $column_to_show, $count){
       global $conn;
       $query = $conn->prepare("SELECT * FROM $shouts LIMIT $count");
       $query->execute();

       while($result = $query->fetch(PDO::FETCH_ASSOC) ){
         echo $result["$column_to_show"] . "</br>";
       }
     }
   }
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$
  • convention for PHP class names is PascalCase, so your class should be ConnectionToDb.
  • you are inconsistent with your indentation (2 vs 4 spaces).
  • select * is discouraged. Don't just select everything if you only need one column, select only that column.
  • limit is actually a vector for SQL injection. You should also clean table before using it in a query. Even if the data isn't user supplied right now, as this is a class, which is meant for reuse, you can never be sure how it will be used in the future.
  • Don't just echo unsanitized data from the database (because it might be user supplied), this can result in an XSS vulnerability.
  • </br> isn't valid HTML, use <br> or <br />
  • I don't see the benefit of having this as a class. I would just remove make_connection and add the connection as a parameter to run_test_query.
  • run_test_query isn't a very good name.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.