Jump to content

Recommended Posts

Hello everyone - I have picked dup a book on php and SQL and have been quaking through it. I have come across a problem with a foreach statement that I can not resolve.

Any help and advice is greatly appreciated!

 

<?php

    try {
        $pdo = new PDO('mysql:host=localhost;dbname=ijdb; charset=utf8', 
            'ijdbuser', 'mypassword');
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = 'SELECT `joketext` FROM `joke`';
        $result = $pdo->query($sql);
        while ($row = $result->fetch()) {
            $jokes[] = $row['joketext'];
        }
    } 
    catch (PDOException $e) {
        $output = 'Unable to connect to the database server: ' .
        $e->getMessage() . ' in ' .
        $e->getFile() . ':' . $e->getLine();
    }
include  __DIR__ . '/../templates/jokes.html.php';

and the other file

 

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>List of jokes</title>
    </head>
    <body>
        <?php if (isset($error)): ?>
        <p>
            <?php echo $error; ?>
        </p>
        <?php else: ?>
        <?php foreach($jokes as $joke ): ?>
        <blockquote>
            <p>
            <?php echo htmlspecialchars($joke, ENT_QUOTES, 'UTF-8') ?>
            </p>
        </blockquote>
        <?php endforeach; ?>
        <?php endif; ?>
    </body>
</html>

 

Link to comment
https://forums.phpfreaks.com/topic/311725-trying-to-learn/
Share on other sites

Personally I wouldn't start off learning PDO by doing try-catch statements as in my opinion will cause more confusion than it is worth. Simply have error reporting turned on to catch the errors.

I personally don't like writing foreach statements that way, I would write it something like the following:

<?php

foreach ($result as $text) {

  echo '<blockquote>'; 

    echo '<p>' . htmlspecialchars($text['joketext']) . '</p>'; 

  echo '</blockquote>';

}

?>

as for the pdo I would do something like the following:

$db_options = array(
            /* important! use actual prepared statements (default: emulate prepared statements) */
            PDO::ATTR_EMULATE_PREPARES => false
            /* throw exceptions on errors (default: stay silent) */
            , PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
            /* fetch associative arrays (default: mixed arrays)    */
            , PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        );

$pdo = new PDO('mysql:host=' . DATABASE_HOST . ';dbname=' . DATABASE_NAME . ';charset=utf8', DATABASE_USERNAME, DATABASE_PASSWORD, $db_options);

$stmt = $pdo->query('SELECT joketext FROM joke');
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);

I haven't tested the above out, so I don't know how correct it is.

I would look at this link -> https://phpdelusions.net/pdo as it explains it pretty good in my opinion and I still refer to it from time to time myself. 

Edited by Strider64
  • Great Answer 1
Link to comment
https://forums.phpfreaks.com/topic/311725-trying-to-learn/#findComment-1582478
Share on other sites

for the $jokes variable to not exist, either the query failed due to an error or there are no (matching) rows in the database table.

for the first case, most database statement errors are fatal problems, either due to programming mistakes or the database server not running, and there's no point in code on the page continuing to run at all. therefore, you would want your error handling to display the actual error information when you are learning, developing, and debugging query(ies) and to log the actual error information when on a live/public web server. to do this, simply let php catch the exception, where it will use its error related settings to control what happens with the actual error information (database statement errors will 'automatically' get displayed/logged the same as php errors.) you would then remove any existing database statement error handing, so that you don't need to keep track of if you are actually displaying/logging the output from it.

the exception to this rule are execution errors for inserting/updating user submitted data and a duplicate or out of range error can occur. in this case, you would want your error handling to catch the exception, test if the error number is for something your code can handle, then setup and output a message telling the user what was wrong with the data that they submitted. for all other error numbers, just re-throw the exception and let php handle it, as described above.

short-version: only use a try/catch block for database statement errors when a visitor on a site (not you as the programmer/developer) can do something about correcting the error.

for the second case, your code producing the output should test if there is data to display, and either output a message stating there is not, or use the data to produce the output.

Edited by mac_gyver
Link to comment
https://forums.phpfreaks.com/topic/311725-trying-to-learn/#findComment-1582484
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.