3

I am trying to run a MySQL PDO query. I am not sure why I am getting a fatal error. I have checked other posts, but their answers don't seem to solve mine.

The script is connecting to the database fine. The username and password are correct and I have removed them in the script below.

My output:

Connected to database
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[28000] [1045] Access denied for user 'nobody'@'localhost' (using password: NO)' in /home/a/public_html/d/inc/header.php:34 Stack trace: #0 /home/a/public_html/d/inc/header.php(34): PDO->__construct('mysql:host=;dbn...', NULL, NULL) #1 /home/a/public_html/d/inc/header.php(43): testdb_connect() #2 /home/a/public_html/d/article.php(3): include('/home/a/p...') #3 {main} thrown in /home/a/public_html/d/inc/header.php on line 34

My code:

<?php
    /*** MySQL  hostname ***/
    $hostname = 'localhost';
    /*** MySQL  username ***/
    $username = 'removed';
    /*** MySQL  password ***/
    $password = 'removed';
    try {
        function testdb_connect(){
            $dbh = new PDO("mysql:host=$hostname;dbname=removed", $username, $password);
            return ($dbh);
        }
            echo 'Connected to database';
        }
    catch(PDOException $e) {
        echo $e->getMessage();
    }

    $dbh = testdb_connect();

    $id = $_GET[id];
    echo 'dfsdfs ' . $id;
    var_dump($dbh);
    $sql = "SELECT * FROM 'radiologyArticles' WHERE 'id' = :id";
    $stmt = $dbh->prepare($sql);
    $stmt->bindParam(':id', $id);
    $stmt->execute();
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

?>

        <section>
            <header>
                <h2><?php echo $row['articleTitle']; ?></h2>
                <h3>A generic two column layout</h3>
            </header>
            <p>
                <?php echo $row['articleBody']; ?>
            </p>
        </section>

        <?php
    }
            // Close the PDO connection
            $link = null;
        ?>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
bobafart
  • 173
  • 2
  • 2
  • 11
  • But you aren't successfully connecting. The `echo 'Connected to database';` is called _before_ you call your connection `testdb_connect()`. – Michael Berkowski May 25 '14 at 13:00
  • 2
    Variable scope for your $username and $password values in the testdb_connect() function.... and don't put the try/catch around the function definition, put it around the call to the function – Mark Baker May 25 '14 at 13:00
  • 1
    `$username` and `$password` are not in scope for the function `testdb_connect()`. Either pass them as params to that function, or don't bother with the function and just call `new PDO(...)` directly. – Michael Berkowski May 25 '14 at 13:01
  • Mark Baker, where should I place the $username and $password then to prevent scoping issues? thanks – bobafart May 25 '14 at 13:02
  • @bobafart - pass them as arguments to the testdb_connect() function – Mark Baker May 25 '14 at 13:03
  • Michael, I need to create the function otherwise I will have a scoping problem with $dbh as I do not want to use a global $dbh. What is the correct way to structure this code? please and thank you? and the most code efficient way to structure it. this is my first time using PDO – bobafart May 25 '14 at 13:04
  • Learn to program at E_ALL error reporting level – Your Common Sense May 25 '14 at 13:09

1 Answers1

6
/*** MySQL hostname ***/
$hostname = 'localhost';
/*** MySQL username ***/
$username = 'removed';
/*** MySQL password ***/
$password = 'removed';

function testdb_connect ($hostname, $username, $password){
    $dbh = new PDO("mysql:host=$hostname;dbname=removed", $username, $password);
    return $dbh;
}

try {
    $dbh = testdb_connect ($hostname, $username, $password);
    echo 'Connected to database';
} catch(PDOException $e) {
    echo $e->getMessage();
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • I just did this Mark. Thank you for your help. Compared to the old MYSQL queries, the PDO way is so verbose. There must be a better way to structure code for PDO queries. Is this the way you expert coders structure simple PDO queries? – bobafart May 25 '14 at 13:08
  • Using Mark's above code eliminates the FATAL ERROR problem. Thank you Mark. However, now my ECHO output states return nothing. The query is valid as the mySQL table contains data within, the fields are not blank. Any idea why there is no output? – bobafart May 25 '14 at 13:09
  • Most would use a wrapper class for PDO, taking an OO approach... instantiate the class, passing in the connection details as arguments, and provide a getconnection() method; then the class can be injected into any other functions/methods wherever it's needed – Mark Baker May 25 '14 at 13:09
  • Can you point me to an example of a wrapper class? time to learn more.. thanks – bobafart May 25 '14 at 13:10
  • Furthermore, is there a method to error check the raw mySQL query with PDO? In the old method I could simply echo $sql and then cut and paste the output into mySQL to test the query to ensure it is accurate. Can't seem to do that with prepared statements, is there a way to do this? thanks – bobafart May 25 '14 at 13:11
  • http://codereview.stackexchange.com/questions/29362/very-simple-php-pdo-class – Mark Baker May 25 '14 at 13:11
  • There isn't unless you write one yourself, because prepared statements don't work in quite the same way... but working with bind variables is a lot simpler than injected values, because you don't need all the complexities of escaping – Mark Baker May 25 '14 at 13:13