0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

初心者がPHPの開発で注意すること

Posted at

個人的に役に立った記事をまとめメモ
各記事の執筆者様本当にありがとうございます…!

開発の前に読むとはかどる記事

by @mpyw

by @7968

#注意することポイント(初心者)

ビューとロジックは分けて実装する

間違い↓

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Example</title>
    </head>
    <body>
        <ul>
<?php

try {

    $pdo = new PDO('mysql: ... ', 'root', 'password', [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    ]);
    $stmt = $pdo->query('SELECT * FROM users');
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        echo '<li>' . htmlspecialchars($row['name']) . '</li>';
    }

} catch (PDOException $e) {

    exit($e->getMessage());    

}

?>
        </ul>
    </body>
</html>

正しい↓

<?php

try {

    $pdo = new PDO('mysql: ... ', 'root', 'password', [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    ]);
    $rows = $pdo->query('SELECT * FROM users')->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {

    exit($e->getMessage());    

}

function h($str)
{
    return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
}

?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Example</title>
    </head>
    <body>
        <ul>
<?php foreach ($rows as $row): ?>
            <li><?=h($row)?></li>
<?php endforeach; ?>
        </ul>
    </body>
</html>

$_POST['id'] などの外部入力からきた変数が定義されているか確認

変数が 未定義でない かつ NULLでない かつ 配列でないか チェック

if (!isset($_POST['email']) || !is_string($_POST['email']) || $_POST['email'] === '') {
    $errors[] = 'Eメールアドレスが入力されていません';
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?