ReadQuestionsFromFile.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. $hostname = 'localhost';
  3. $username = 'narKampen';
  4. $pass = 'IfRLzj2HJBXA9eei';
  5. $database = 'narKampen';
  6. $conn = new mysqli($hostname, $username, $pass, $database);
  7. if (!$conn) {
  8. die("Connection Failed. ". mysqli_connect_error());
  9. }
  10. mysqli_set_charset($conn,'utf8');
  11. // Check if file is CSV
  12. // get Filename, remove ending, this is the category name
  13. // get file contents
  14. if (file_exists($argv[1]) {
  15. $file = fopen($argv[1], "r");
  16. $fileinfo = pathinfo($argv[1]);
  17. $categoryName = str_replace("_"," ", $fileinfo['filename']);
  18. while ($data = fgetcsv($file, 1000, ",") !== false) {
  19. $answer = $data[0];
  20. $question = $data[1];
  21. if ($answer == null || $question == null || $answer = "" || $question == "") {
  22. echo "Failed to get answer and/or question from " . print_r($data,true) . "\r\n";
  23. die();
  24. }
  25. $sql = "INSERT INTO questions (answer, question)
  26. VALUES ($answer, '$question')
  27. ON DUPLICATE KEY UPDATE SET
  28. answer = $answer,
  29. id = LAST_INSERT_ID(id)";
  30. $conn->querry($sql);
  31. $questionId = $conn->insert_id;
  32. if ($questionId == 0) {
  33. echo "Nothing insered or updated by sql: \r\n";
  34. echo $sql;
  35. die(); // Should not happen!
  36. }
  37. $sql = "SELECT id FROM category WHERE name = '$categoryName'";
  38. $result = $conn->querry($sql);
  39. $categoryId = -1;
  40. while ($row = $result->fetch_assoc()) {
  41. $categoryId = $row['id'];
  42. }
  43. if ($categoryId == -1) {
  44. $sql = "INSERT INTO category (name, r,g,b,a) VALUES ($categoryName, 255,255,255,255)";
  45. $conn->querry($sql);
  46. $categoryId = $conn->insert_id;
  47. }
  48. $sql = "INSERT INTO questionToCategory (questionId, categoryId) VALUES ($questionId, $categoryId)";
  49. $conn->querry($sql);
  50. echo "inserted question $question into category $categoryName \r\n";
  51. }
  52. fclose($file);
  53. } else {
  54. echo "Run with file as first argument";
  55. }