How can I connect to a MySQL database from a PHP script ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

How can I connect to a MySQL database from a PHP script ?

14th Oct 2018, 10:58 AM
Tinashe Genius Ndawe
Tinashe Genius Ndawe - avatar
4 Answers
+ 11
Using mysqli: $connection = mysqli_connect(localhost, username, password, database_name); Now you can use $connection everytime you want to manipulate SQL.
15th Oct 2018, 11:21 PM
ᴰᴼᴹᴵᴺᴼ
ᴰᴼᴹᴵᴺᴼ - avatar
14th Oct 2018, 11:27 AM
Ulisses Cruz
Ulisses Cruz - avatar
+ 1
Use PDO: $host = 'localhost'; $db = 'test'; $user = 'root'; $pass = 'yourpassword'; $charset = 'utf8mb4'; $dsn = "mysql:host=$host;dbname=$db;charset=$charset"; $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ]; try { $pdo = new PDO($dsn, $user, $pass, $options); } catch (\PDOException $e) { throw new \PDOException($e->getMessage(), (int)$e->getCode()); } More info: https://phpdelusions.net/pdo
19th Oct 2018, 4:56 AM
Sithu Kyaw
+ 1
Using mysqli: $connection = mysqli_connect(localhost, username, password, database_name); Now you can use $connection everytime you want to manipulate SQL. (copied Domino’s answer for corrections) if you want to include this connection in all pages its advisable to have it in one page and use php includes to import it into any page or if you have a universal header you can include it their, always have a function page just incase you wanna edit, you edit in only one oage rather that all pages.
19th Oct 2018, 7:26 PM
FEXZI
FEXZI - avatar