Newbie713 Newbie713 - 7 days ago 9
PHP Question

Failing testing database connection in php

I've set up a database using MAMP.
When I try the following test, I only receive a blank page. Fairly new to this, and I've tried different suggestions found on the web with no luck.
Tried using both port and socket.

<?php
$user = 'root';
$password = 'root';
$db = 'test';
$host = 'localhost';
$port = 3306;
$socket = "/Applications/MAMP/tmp/mysql/mysql.sock";

$link = mysql_connect(
"$host:$socket",
$user,
$password
);
$db_selected = mysql_select_db(
$db,
$link
);

if (!$link){
echo "ERROR";
}
else {
echo "Success";
}
mysql_close($link);

?>

Answer

Would you like to try PDO ?!

<?php
    $dsn = "mysql:host=localhost;dbname=databasenamehere";
    $user = 'root';
    $pass = '';
    $option = array(
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
    );

    try {
        $connect = new PDO($dsn, $user, $pass,$option);
        $connect->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

    }
    catch (PDOException $r) {
        echo 'Failed' . $r->getMessage();
    }
Comments