Explorar o código

Lägga till frågor till databasen fungerar

Axel Nordh %!s(int64=3) %!d(string=hai) anos
pai
achega
c5af40d661
Modificáronse 1 ficheiros con 25 adicións e 5 borrados
  1. 25 5
      ReadQuestionsToDbFromCsvFile.php

+ 25 - 5
ReadQuestionsToDbFromCsvFile.php

@@ -10,7 +10,8 @@ if (!isset($argv[1]) || !str_contains($argv[1], '.csv')) {
     echo 'Needs to supply a .csv with questions and answers';
     die();
 } else {
-    $category = substr($argv[1],strripos($argv[1], '\\')+1,-4);
+    $file = $argv[1];
+    $category = substr($argv[1],strripos($argv[1], DIRECTORY_SEPARATOR)+1,-4);
     $category = str_replace("_", " ", $category);
 }
 
@@ -34,16 +35,35 @@ $result = $sth->fetchAll();
 if (count($result) > 0) {
     foreach ($result as $r) {
         echo "Category Id: " . $r['id'] . "\n";
+        $categoryId = $r['id'];
     }
+} else {
+// Insert new category??
+    echo "Category not found $category" . PHP_EOL;
+    die();  
 }
 
+$csv = fopen($file,'r');
+
+while (!feof($csv)) {
+    $csvArray[] = fgetcsv($csv,1000,',');
+}
 
+fclose($csv);
 
-$realHash = md5($_GET['name'] . $_GET['score'] . $secretKey);
-if ($realHash == $hash) {
-    $sth = $dbh->prepare('INSERT INTO scores VALUES (null, :name, :score)');
+foreach ($csvArray as $value) {
+    $data = ['question' => $value[1],
+            'answer' => $value[0]];
+    $sth = $dbh->prepare('INSERT INTO Questions (question, answer) VALUES (:question, :answer)');
     try {
-        $sth->execute($_GET);
+
+        $sth->execute($data);
+        $questionId = $dbh->lastInsertId();
+
+        $sth2 = $dbh->prepare('INSERT INTO QuestionToCategory (questionId, categoryId) VALUES (:questionId, :categoryId)');
+        $questionLinkData = ['questionId' => $questionId, 'categoryId' => $categoryId];
+        $sth2->execute($questionLinkData);
+
     } catch (Exception $e) {
         echo '<h1>An error has ocurred.</h1><pre>', $e->getMessage(), '</pre>';
     }