0

I have seen some ways to connect to the MySQL DB with PHP, but don't know why the one is better than the other, or safer or anything. Same thing goes with inserting or fetching data to/from the database.

This is some examples of MYSQL connection with PHP:

DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', 'password');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'test');

$db = @mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die('Could not connect to database. '.mysqli_connect_error());

OR

class kobling extends mysqli {
public function __construct(
    $host = "127.0.0.1",
    $base = "test",
    $user = "root",
    $pw = "password",
    $port = "3306") {
    parent::__construct($host,$user,$pw,$base,$port);
}
}

if (!($db = new kobling())) {
die("Kunne ikke koble til databasen.");
}

Any suggestions or solutions?

tryAndroid
  • 95
  • 1
  • 11
  • Both of them are pretty much the same. Style difference – frz3993 Apr 27 '17 at 18:27
  • Just preference honestly.. – clearshot66 Apr 27 '17 at 18:28
  • 2
    If you're starting from scratch, your best bet is probably to use [PDO](http://php.net/manual/en/book.pdo.php), as it is portable across different databases. – Alex Howansky Apr 27 '17 at 18:28
  • Okay thanks, thought the one would be more secure or something. – tryAndroid Apr 27 '17 at 18:29
  • Why do some use include(db.php) and some other use require_once(db.php)? @AlexHowansky – tryAndroid Apr 27 '17 at 18:29
  • 1
    I would avoid the first one, mainly because of the way it doesn't handle errors. ([See this Q&A.](http://stackoverflow.com/questions/22662488/how-to-get-mysqli-error-in-different-environments)) And, for what it's worth, I agree with Alex about PDO. – Don't Panic Apr 27 '17 at 18:31
  • Depends on how db.php is programmed. `include()` **always** includes the file, whereas `require_once()` (or `include_once()`) **only** includes the file if it hasn't already been included. So if your db.php defines any constants or functions, you'll get an error if you `include()` it twice. If it's just two lines of code that set up the connection (like `$db = new mysqli(...);`), it's fine to `include()` it multiple times if necessary. – rickdenhaan Apr 27 '17 at 18:32
  • I would avoid the second one as well, because hardcoding the connection parameters into your class isn't a great idea. It's better to include them from a config file. – Don't Panic Apr 27 '17 at 18:32
  • Try to avoid using any form of `include()` or `require()` and instead investigate how autoloaders work, and build your files and class names according to PSR-4 guidelines. – Alex Howansky Apr 27 '17 at 18:35
  • @Don'tPanic Okay, could you show an example of the way to do, since they both should be avoided? Thanks. I'm new to the way to connect, I just copy paste and use it for every project. – tryAndroid Apr 27 '17 at 18:35

0 Answers0