teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

2

コードを修正しました。foreachでCSVファイルの値を取得。

2019/12/03 12:31

投稿

amaturePy
amaturePy

スコア131

title CHANGED
File without changes
body CHANGED
@@ -30,15 +30,7 @@
30
30
  ```
31
31
  実行コード
32
32
 
33
- <?php
33
+ <?php
34
-
35
- try {
36
- $file = new SplFileObject('/tmp/winneyuser.csv');
37
- $file->setFlags(SplFileObject::READ_CSV);
38
- }catch (RuntimeException $e) {
39
- throw $e;
40
- }
41
-
42
34
  try{
43
35
  $pdo = new PDO(
44
36
  'mysql**********',
@@ -56,17 +48,23 @@
56
48
  }
57
49
  header('Content-Type: text/html; charset=utf-8');
58
50
 
51
+ $file = new SplFileObject('/tmp/winneyuser.csv');
52
+ $file->setFlags(SplFileObject::READ_CSV);
59
- $line_id -> $file[0];
53
+ $insert_array = [];
60
- $username -> $file[1];
61
-
62
- foreach($file as $files) {
54
+ foreach ($file as $line) {
55
+ $insert_array[] = [
56
+ 'line_id' => $line[0],
57
+ 'username' => $line[1],
58
+ ];
59
+ }
60
+
63
61
  $stmt = $pdo->prepare("INSERT INTO users (line_id, name) VALUES (:lineid, :username)");
64
-
65
- $stmt->bindValue(':line_id', $line_id, PDO::PARAM_STR);
62
+ $stmt->bindValue(':lineid', $line_id, PDO::PARAM_STR);
66
63
  $stmt->bindValue(':username', $username, PDO::PARAM_STR);
64
+
65
+ foreach($insert_array as $insert_data) {
67
66
  $stmt->execute();
68
-
67
+ }
69
68
  $pdo->commit();
70
- }
71
69
  ?>
72
70
  ```

1

質問内容を編集

2019/12/03 12:31

投稿

amaturePy
amaturePy

スコア131

title CHANGED
File without changes
body CHANGED
@@ -41,9 +41,9 @@
41
41
 
42
42
  try{
43
43
  $pdo = new PDO(
44
- 'mysql:host=database-1.cuiejdfzi0uf.ap-northeast-1.rds.amazonaws.com;dbname=hitobito_data;charset=utf8mb4',
44
+ 'mysql**********',
45
- 'admin',
45
+ '******',
46
- 'hitobitoOwner',
46
+ '********',
47
47
  [
48
48
  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
49
49
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,