こんにちは。
PHPで、以下の通りチェックボックスの内容をDBに登録したいのですが、登録に失敗します。
MariaDB [fruit]> select * from fruit_tbl;
+----+--------+---------------+
| id | name | fruit1 |
+----+--------+---------------+
| 1 | test1 | apple, orange |
| 2 | test2 | |
+----+--------+---------------+
以下の箇所がおかしいことがわかるのですが、どう直せばよいのかわかりませんでした。
$fruit1 = $_REQUEST['fruit1'];
for($i=0; $i<sizeof($fruit1); $i++){
print "${fruit1[$i]}<br>";
}
//フォームで送られてきたデータでINSERT文を作成
$result = mysqli_query($con, "insert into fruit_tbl(name
, fruit1
) values('$name', '$fruit1[$i]')");
if (!$result) {
exit('データを登録できませんでした。');
}
ご教示いただけませんか。
宜しくお願い致します。
【mariaDBの作業】
mysql -u root -p
Enter password: ********
MariaDB [(none)]> create database fruit;
Query OK, 1 row affected (0.01 sec)
MariaDB [(none)]> show databases;
+--------------------+
| Database |
+--------------------+
| fruit |
+--------------------+
MariaDB [(none)]> use fruit;
Database changed
MariaDB [fruit]> create table fruit_tbl(
-> id int not null auto_increment,
-> name varchar(20),
-> fruit1 varchar(20),
-> primary key(id)
-> );
Query OK, 0 rows affected (0.23 sec)
MariaDB [fruit]> show tables;
+-----------------+
| Tables_in_fruit |
+-----------------+
| fruit_tbl |
+-----------------+
1 row in set (0.00 sec)
MariaDB [fruit]> insert into fruit_tbl(name, fruit1) values('test', '');
Query OK, 1 row affected (0.14 sec)
MariaDB [fruit]> select * from fruit_tbl;
+----+--------+---------------+
| id | name | fruit1 |
+----+--------+---------------+
| 1 | test | apple, orange |
| 2 | test | |
+----+--------+---------------+
MariaDB [fruit]>
【fruit.html】
<html> <body> <form action = "fruit.php" method="post"> 名前:<input type="text" name="name"><br /> くだもの: <input type="hidden" name="fruit1" value="Unchecked"> <input type="checkbox" name="fruit1[]" value="apple"> apple <input type="checkbox" name="fruit1[]" value="orange"> orange <input type="submit" name="exec" value="登録"> <input type="reset" value="リセット"> </form> </body> </html>【fruit.php】
<?php //データベースに接続 $con = mysqli_connect('127.0.0.1', 'root', 'password'); if (!$con) { exit('データベースに接続できませんでした。'); } //データベースを選択 $result = mysqli_select_db($con, 'fruit'); if (!$result) { exit('データベースを選択できませんでした。'); } $name = $_REQUEST['name']; print "$name<br>"; $fruit1 = $_REQUEST['fruit1']; for($i=0; $i<sizeof($fruit1); $i++){ print "${fruit1[$i]}<br>"; } //フォームで送られてきたデータでINSERT文を作成 $result = mysqli_query($con, "insert into fruit_tbl(`name`, `fruit1`) values('$name', '$fruit1[$i]')"); if (!$result) { exit('データを登録できませんでした。'); } //データベースから切断 $con = mysqli_close($con); if (!$con) { exit('データベースとの接続を閉じられませんでした。'); } ?>回答7件
あなたの回答
tips
プレビュー