ReadQuestionsFromFile.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 = intval($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 = "SELECT id FROM questions WHERE question = '$question'";
  26. $questionId = $conn->query($sql)->fetch_object()->id;
  27. if($questionId == null) {
  28. $sql = "INSERT INTO questions (answer, question)
  29. VALUES ($answer, '$question')
  30. ON DUPLICATE KEY UPDATE
  31. answer = $answer,
  32. id = LAST_INSERT_ID(id)";
  33. $conn->query($sql);
  34. $questionId = $conn->insert_id;
  35. }
  36. if ($questionId == 0) {
  37. echo "Nothing insered or updated by sql: \r\n";
  38. echo $sql;
  39. die(); // Should not happen!
  40. }
  41. $sql = "SELECT id FROM category WHERE name = '$categoryName'";
  42. $result = $conn->query($sql);
  43. $categoryId = -1;
  44. while ($row = $result->fetch_assoc()) {
  45. $categoryId = $row['id'];
  46. }
  47. if ($categoryId == -1) {
  48. $sql = "INSERT INTO category (name, r,g,b,a) VALUES ($categoryName, 255,255,255,255)";
  49. $conn->query($sql);
  50. $categoryId = $conn->insert_id;
  51. }
  52. $sql = "INSERT INTO questionToCategory (questionId, categoryId) VALUES ($questionId, $categoryId)";
  53. $conn->query($sql);
  54. echo "inserted question $question into category $categoryName \r\n";
  55. }
  56. fclose($file);
  57. } else {
  58. echo "Run with file as first argument";
  59. }