PHP データベース MySQL (PDO) (正確がわからない)


メモ

データベースを接続して、データをアップロードする.
cmd:

cd /Applications/MAMP/Library/bin/
./mysql -u root -proot

コード:

すでにデータベースとテーブルを作成してから、データをアップロードするだけ

<!DOCTYPE html>

<head>
    <title>Count Fat</title>
    <h1> Count Fat</h1>
</head>
<hr />
<body>

<?php
    $id = $gender = $height = $weight = $bmi = "";

    function text_input($data){
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }
    function getSimpleValue($post_name, &$value){
        if(!empty($_POST[$post_name])){
            $value = text_input($_POST[$post_name]);
        }
        else{
            $value = "Null!";
        }
    }
    getSimpleValue("ID", $id);
    getSimpleValue("Height", $height);
    getSimpleValue("Weight", $weight);
    getSimpleValue("Gender", $gender);

?>

<form action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?>" method = "POST">
ID: <input type = "text" name = "ID"><br>
Height: <input type = "text" name = "Height">CM<br>
Weight: <input type = "text" name = "Weight">KG<br>
Gender: 
Female<input type = "radio" name = "Gender" value = "Female">
Male<input type = "radio" name = "Gender" value = "Male"><br>
<input type = "submit" value = "Submit"><br>
</form>
<hr />
<?php

    $bmif = function($w, $h){
        $h /= 100;
        return $w / ($h * $h);
    }; 
    $server = "localhost";
    $user = "root";
    $pw = "root";
    $dbname = "myDBPDO";
    $bmi = $bmif($weight, $height);


    try {
        $conn = new PDO("mysql:host = $server;dbname=$dbname", $user, $pw);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


        $gender = "\"".$gender."\"";

        $sql =<<<EOL
        INSERT INTO Diet
            (id, gender, height, weight, bmi)
        VALUES 
            ($id, $gender, $height, $weight, $bmi)
        EOL;
        $conn->exec($sql);
        echo "</ hr>". "Your data uploaded.";
    }
    catch(PDOException $e){
        echo $sql . "<br>" . $e->getMessage();
    }
    $conn = null;
    echo "ID:" . $id . "<br>";
    echo "Height:" . $height . "<br>";
    echo "Weight:" . $weight . "<br>";
    echo "Gender:" . $gender . "<br>";
    echo "BMI" . $bmi . "<br>";

?>

</body>

</html>