ReadQuestionsFromFile.php 2.2 KB

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