0

自動販売機システムを作成しております。
購入ページで商品を購入しようと思いましたが、最後の商品しか購入できないです。
下の画像エビデンスを見てもらったら分かるように
2つ別の商品を購入しても最後の商品しか購入できておりません。
画像の説明をここに入力
画像の説明をここに入力
画像の説明をここに入力
画像の説明をここに入力

functions.phpの中にあるnames_sql、prices_sql関数のforeach文の外にあるreturnが上手く作用してないように見えますが、どうやってreturnすれば上手く返せるかわからない状況です。
returnを行う場所を変えたりしてみましたが、foreach文の中にreturnを入れたら最初のデータしか返せませんでした。
お手数をおかけしますがご教授の程よろしくお願いいたします。
ソースコード
Model
functions.php

<?php
require_once('../../include/conf/const.php');

function get_db_connect() {
 
if (!$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWD, DB_NAME)) {
        die('error: ' . mysqli_connect_error());
    }
    mysqli_set_charset($link, DB_CHARACTER_SET);
    return $link;
}

function close_db_connect($link) {

    mysqli_close($link);
}

function insert_drink($link) {
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    return;
}
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['sql_kind'] === 'insert') {
        
        if (isset($_POST['new_name']) === TRUE) {
            
            $new_name = $_POST['new_name'];
        }
        
        if (isset($_POST['new_price']) === TRUE) {
        
            $new_price = $_POST['new_price'];
            
        }
        
        if (isset($_POST['new_stock']) === TRUE) {
            
            $new_stock = $_POST['new_stock'];
        }
        
        if (isset($_POST['new_status']) === TRUE) {
        if ((int) $_POST['new_status'] === 0 || (int) $_POST['new_status'] === 1) {
             
             $new_status = (int) $_POST['new_status'];
        }
            
        }
        
            $new_time = date('Y-m-d H:i:s');
            
            $sql = 'INSERT INTO drink_info_table(drink_name, price, stock, created_at, updated_at, status) VALUES(\''.$new_name.'\',\''.$new_price.'\',\''.$new_stock.'\',\''.$new_time.'\',\''.$new_time.'\',\''.$new_status.'\')';

            if ($result = mysqli_query($link, $sql) === TRUE) {

                $drink_id = mysqli_insert_id($link);
            } else {
                $err_msg[] = 'DBエラーが発生しました。';
                return $err_msg;
                
                
            }
                
            }
    }


        
function update_drink($link) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['sql_kind'] === 'update') {

        if (isset($_POST['update_stock']) === TRUE) {
                $update_stock = (int)($_POST['update_stock']);

                $update_time = date('Y-m-d H:i:s');

                $update_id = $_POST['drink_id'];

                $sql = 'UPDATE drink_info_table SET stock = ' . $update_stock . ', updated_at = \'' . $update_time . '\' WHERE drink_id = ' . $update_id;
                
                if ($result = mysqli_query($link, $sql) === TRUE) {
                } else {
                   $err_msg[] = 'DBエラーが発生しました。';
                   return $err_msg;
                }
                }
        }
}




function change_drink($link) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['sql_kind'] === 'change') {

        if (isset($_POST['change_status']) === TRUE) {
            if ((int) $_POST['change_status'] === 0 || (int) $_POST['change_status'] === 1) {
                $change_id = $_POST['drink_id'];
                $change_status = (int) $_POST['change_status'];

                $change_time = date('Y-m-d H:i:s');

                $sql = 'UPDATE drink_info_table SET status = ' . $change_status . ' WHERE drink_id = ' . $change_id;


                if ($result = mysqli_query($link, $sql) === TRUE) {
                    
                } else {
                    $err_msg[] = 'ステータスの変更に失敗しました';
                }
            } else {
                $err_msg[] = 'ステータスは公開か非公開を選択してください';
                return $err_msg;
            }
        }
    }
    
}



function do_sql($link) {
    $sql = 'SELECT drink_info_table.drink_id, drink_info_table.drink_name, drink_info_table.price, drink_info_table.stock, drink_info_table.status
    FROM drink_info_table';
    $data = [];
    if ($result = mysqli_query($link, $sql)) {
        while ($row = mysqli_fetch_array($result)) {
            $data[] = $row;
        }
    } else {
        $err_msg[] = 'データの抽出に失敗しました';
    }
    return $data;
}

function names_sql($link) {
    $sql = 'SELECT drink_info_table.drink_id, drink_info_table.drink_name, drink_info_table.status
    FROM drink_info_table WHERE status = 1';
    $data = [];
    if ($result = mysqli_query($link, $sql)) {
        while ($row = mysqli_fetch_array($result)) {
            $data[] = $row;
        }
    } else {
        $err_msg[] = 'データの抽出に失敗しました';
    }
     foreach ($data as $info) {
               $drink_name = $info['drink_name'];
     }
    return $drink_name;
}

function prices_sql($link) {
    $sql = 'SELECT drink_info_table.drink_id, drink_info_table.price, drink_info_table.status
    FROM drink_info_table WHERE status = 1';
    $data = [];
    if ($result = mysqli_query($link, $sql)) {
        while ($row = mysqli_fetch_array($result)) {
            $data[] = $row;
        }
    } else {
        $err_msg[] = 'データの抽出に失敗しました';
    }
     foreach ($data as $info) {
                $price = (int) $info['price'];
                $money = $_POST['money'];
                $return = $money - $price;
     }
     return $return;
}

function does_sql($link) {
    $sql = 'SELECT drink_info_table.drink_id, drink_info_table.drink_name, drink_info_table.price, drink_info_table.stock, drink_info_table.status
    FROM drink_info_table WHERE status = 1';
    $data = [];
    if ($result = mysqli_query($link, $sql)) {
        while ($row = mysqli_fetch_array($result)) {
            $data[] = $row;
        }
    } else {
        $err_msg[] = 'データの抽出に失敗しました';
    }
    return $data;
}

function complete_check_insert($link) {
    $complete_msg[] = '追加登録完了!';
    return $complete_msg;
}

function complete_check_update($link) {
    $complete_msg[] = '在庫数更新完了!';
    return $complete_msg;
}

function complete_check_change($link) {
    $complete_msg[] = 'ステータス変更完了!';
    return $complete_msg;
}

function validation_check($link) {
   $err_msg = [];
   if (!isset($_POST['new_name']) || (isset($_POST['new_name']) && $_POST['new_name'] === ""))  {
     $err_msg[] = '商品名を入力してください。';
    }
    
    if (!isset($_POST['new_price']) || (isset($_POST['new_price']) && $_POST['new_price'] === "")) {
     $err_msg[] = '値段を入力してください';
    } else if(preg_match('/^[0-9]+$/',($_POST['new_price'])) !== 1) {
     $err_msg[] = '値段は0以上の半角整数を入力してください';
    }
    
    if (!isset($_POST['new_stock']) || (isset($_POST['new_stock']) && $_POST['new_stock'] === "")) {
     $err_msg[] = '在庫を入力してください';
    } else if(preg_match('/^[0-9]+$/',($_POST['new_stock'])) !== 1) {
     $err_msg[] = '在庫は0以上の半角整数を入力してください';
    }
    
    if (!empty($_POST["new_status"])) {
    if ((int) $_POST['new_status'] === 2) {
     $err_msg[] = 'ステータスは公開か非公開を選択してください'; 
    }
    }
return $err_msg;
}

function validation_check2($link) {
    if (!empty($_POST["update_stock"])) {
    if (preg_match('/^[0-9]+$/',($_POST['update_stock'])) !== 1){ 
     $err_msg = [];
     $err_msg[] = '0以上の半角整数を入力してください';
     return $err_msg;
    }

}
}

View
index2.php

<!DOCTYPE html>
<html lang="ja">

<head>
    <meta charset="UTF-8">
    <title>自動販売機</title>
</head>

<body>


    <h1>自動販売機</h1>

    <form class="form" method="post" action="result.php">

        <div>
            金額 <input type="text" name="money" />
            <?php
             if (!empty($money)) {
            $money = (int) $_POST['money']; 
            $money =  prices_sql($link);
            var_dump($money);
            return $money;
             }
            ?>
        </div>
        <div class="parent">
             <?php 
             if (!empty($data)) {
               foreach ((array)$data as $product) {
             
             ?>
                <? php print htmlspecialchars($product,ENT_QUOTES,'UTF-8'); ?>
                <div class="product">
                    <div class="product_name">
                        <p class="margin"><?php {
                        print $product['drink_name']; 
                        }
                       ?></p>
                    </div>

                    <div class="product_price">
                        <p class="margin"><?php {
                        print $product['price'];
                         }
                        ?>円</p>
                    </div>

                    <div class="product_buy">
                        <?php {
                        print $product['stock']; 
                        }
                        ?>
                        <?php if ((int) $product['stock'] === 0) { ?>
                            <div class="sold_out"><?php print '売り切れ'; ?></div>
                        <?php } else { ?>
                         <input type="radio" name="drink_id" value="<?php print $product['drink_id']; ?>" />
                        <?php } ?>
                        <?php } ?>
                        <?php } ?>
                    </div>
                </div>
        </div>
        

        <div id="submit">
            <input type="submit" value="■□■□購入■□■□" />
        </div>

    </form>
</body>

</html>

result2.php

<!DOCTYPE html>
<html lang="ja">

<head>
    <meta charset="UTF-8">
    <title>自動販売機結果</title>
</head>

<body>

    <h1>自動販売機結果</h1>

    <?php foreach ($err_msg as $err) { ?>
        <p><?php print $err; ?></p>
    <?php } ?>

    <?php if (count($err_msg) === 0) { ?>

        <div class="result">
            <?php ?>
            <?php if (!empty($drink_name)) {
            ?>
            <p><?php print 'がしゃん!【' .$drink_name . '】が買えました!'; ?></p>
            
            <?php ?>
            <?php if (!empty($return)) {
            ?>
            <p><?php print 'おつりは【' .$return . '円】です!'; ?></p>
            <?php } ?>
            <?php } ?>
        </div>

    <?php } ?>
    <a href='../../mvc/index.php'>戻る</a>

    </form>
</body>

</html>

Controller
index.php

<?php
require_once('../../include/model/functions.php');
require_once('../../include/conf/const.php');
$link = get_db_connect();
$data = does_sql($link);
require_once('../../include/view/index2.php');

close_db_connect($link);

result.php

<?php
require_once('../../include/model/functions.php');
require_once('../../include/conf/const.php');
$link = get_db_connect();
$drink_name = names_sql($link);
$return = prices_sql($link);
require_once('../../include/view/result2.php');

close_db_connect($link);

その他
const.php

<?php
$err_msg = [];
$complete_msg = [];
$data = [];

define('DB_HOST',   ''); // データベースのホスト名又はIPアドレス
define('DB_USER',   '');  // MySQLのユーザ名
define('DB_PASSWD', '');    // MySQLのパスワード
define('DB_NAME',   '');    // データベース名

define('HTML_CHARACTER_SET', 'UTF-8');  // HTML文字エンコーディング
define('DB_CHARACTER_SET',   'UTF8');   // DB文字エンコーディング

date_default_timezone_set('Asia/Tokyo');
9
  • フォームで渡している drink_id が使われていませんね。
    – metropolis
    2021年9月21日 6:54
  • drink_idで識別する必要があるんですか? 2021年9月22日 2:06
  • はい、SQL(select statement)の where 句で指定する必要があります。
    – metropolis
    2021年9月22日 2:09
  • drink_id = drink_info_table.drink_id←これではうまくいきませんか? 2021年9月22日 2:18
  • where で絞らないと全てのレコードを抽出してしまいます。そして foreach で上書きしているので最後の商品のデータが戻るという結果になっています。
    – metropolis
    2021年9月22日 2:22

0

この質問に回答するには、ログインする必要があります。

のタグが付いた他の質問を参照する。