Database connection not working without any errors


#1

This is my first time working with 000webhost and databases. The problem I am having is with sending information to a table and getting info out of tables to be displayed on my page. As far I can tell the connection is working, however, when I go to post something, it doesn’t show up on phpmyadmin, and when I go to fetch something, nothing comes back. I am not getting any errors, and I appear to have the correct db name, user name, and password because if I change any of those a little bit I do get an error. I am just looking to see if anyone could point me in the right direction. Thanks.

Here is what I am using to connect:

    <?php
        $dsn = 'mysql:host=localhost;dbname=:mydatabasename';
    $username = 'myusername';
    $password = 'mypassword';

    try {
        $db = new PDO($dsn, $username, $password);
    } catch (PDOException $e) {
        $error_message = $e->getMessage();
        include('database_error.php');
        exit();
    }
?>

And here is where I am trying to use it:

    <?php
//get data from the form
$comment = filter_input(INPUT_POST, 'comments');
$comment = htmlspecialchars($comment);
$comment = nl2br($comment, false); 

// Validate inputs
if ($comment == null) {
    $error = "Invalid comment. Please try again.";
    include('error.php');
} 

else {
	//connect to the database
	require_once('database.php');

	//post new comment to the table
    $query = 'INSERT INTO comments
                 (comment)
              VALUES
                 (:comment)';
    $statement = $db->prepare($query);
	$statement->bindValue(':comment', $comment);
    $statement->execute();
    $statement->closeCursor();
}

//get all of the comments
$query = 'SELECT * FROM comments
                       ORDER BY time';
$statement = $db->prepare($query);
$statement->execute();
$comments = $statement->fetchAll();
$statement->closeCursor();

?>

#2

Also, here is the link to the page: https://ictn6825jdc.000webhostapp.com/index.php


#3

Are the user, password, and database name correct?
I mean did you remove them in the code you pasted here?


#4

Yes, they are correct in my files, I just removed them here.


#5

Php PDO exception is not enabled here, available at hostinger.


#6

I ended up creating a new account and the same file is working fine now. I am not sure what the problem was, but it is working now!


#7

Weird glad to hear you resolved it eventually on your own sorry about that!

Happy site building!