15

I'm still new to PHP and MYSQL and I'm trying to learn both with modern coding techniques. All the stuff I find online seems to be outdated.

Can anybody suggest anything for me? I am also curious if the below code is outdated? If it is indeed outdated, can you suggest newer and safer methods?

<?php
    $connection = mysql_connect("localhost", "root", "");
    if (!$connection) {
        die("Oops, error happened: " . mysql_error());
    }
?>
Gottlieb Notschnabel
  • 9,408
  • 18
  • 74
  • 116
user1707535
  • 169
  • 1
  • 9

5 Answers5

11

Use PDO functions.

Database Connection Using PDO:

$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
Sumit Bijvani
  • 8,154
  • 17
  • 50
  • 82
3

safest ways to connect to a database with PHP

If you are looking for the safe methods you actually need to fire proof your queries from injections. MySQL extension is going to be deprecated soon, it does not means its not safe now, its just the case that community dropped further development for the extension.

You can try both PDO and mysqli for your database queries, both are good.

Your choice should depends upon your database selection -

PDO supports around 12 different drivers, while MySQLi supports MySQL only.

List of PDO drivers available

CUBRID (PDO)
MS SQL Server (PDO)
Firebird/Interbase (PDO)
IBM (PDO)
Informix (PDO)
MySQL (PDO)
MS SQL Server (PDO)
Oracle (PDO)
ODBC and DB2 (PDO)
PostgreSQL (PDO)
SQLite (PDO)
4D (PDO) 

Source - pdo-drivers-in-php

API support

PDO and MySQLi both offers object-oriented API, but MySQLi also offers a procedural API.

Community
  • 1
  • 1
swapnesh
  • 26,318
  • 22
  • 94
  • 126
2

Yes, your code is outdated. and mysql_connect, mysql_query etc will be deleted soon.

There are basically two options to use: (without installing 3rd party applications)

Take a look at http://php.net/manual/en/book.pdo.php

OR

use Mysqli http://php.net/manual/en/book.mysqli.php

bestprogrammerintheworld
  • 5,417
  • 7
  • 43
  • 72
2

When accessing a database in PHP, we now have two choices: MySQLi and PDO.

To choose which one you want to use take a look here!

And if you want to know why you shouldn't use mysql_* then take a look at this post!

Community
  • 1
  • 1
Daanvn
  • 1,254
  • 6
  • 27
  • 42
0

The first of all:

Yes, the line is outdated.

You can use instead mysqli_* functions which have very similar use as mysql_.

Secondly, if you know something about object-oriented programming, you can use PDO, as suggested in the other answers.

The last thing to mention is that never ever show error message to the user. He doesn't need to know that something went wrong, and he doesn't need to know WHAT went wrong. So never die() with error message.

Voitcus
  • 4,463
  • 4
  • 24
  • 40