ReadQuestionsFromFile.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. $hostname = 'localhost';
  3. $username = 'narKampen';
  4. $pass = '9Bq.6[AcTc2ADwN-';
  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 (
  22. $answer == null ||
  23. $question == null ||
  24. $answer == '' ||
  25. $question == ''
  26. ) {
  27. echo 'Failed to get answer and/or question from ' .
  28. print_r($data, true) .
  29. "\r\n";
  30. die();
  31. }
  32. $sql = "SELECT id FROM questions WHERE question = '$question'";
  33. $result = $conn->query($sql);
  34. if ($result === false) {
  35. echo "Insert new question $question \r\n";
  36. } else {
  37. $questionId = $result->fetch_object()->id;
  38. }
  39. $result->free_result();
  40. if ($questionId == null) {
  41. $sql = "INSERT INTO questions (answer, question)
  42. VALUES ($answer, '$question')
  43. ON DUPLICATE KEY UPDATE
  44. answer = $answer,
  45. id = LAST_INSERT_ID(id)";
  46. $conn->query($sql);
  47. $questionId = $conn->insert_id;
  48. }
  49. if ($questionId == 0) {
  50. echo "Nothing insered or updated by sql: \r\n";
  51. echo $sql;
  52. die(); // Should not happen!
  53. }
  54. $sql = "SELECT id FROM category WHERE name = '$categoryName'";
  55. $result = $conn->query($sql);
  56. if ($result === false) {
  57. echo "Failed to get category, add New with name $categoryName";
  58. } else {
  59. $categoryId = $result->fetch_object()->id;
  60. }
  61. $result->free_result();
  62. if ($categoryId == null) {
  63. $sql = "INSERT INTO category (name, r,g,b,a) VALUES ($categoryName, 255,255,255,255)";
  64. $conn->query($sql);
  65. $categoryId = $conn->insert_id;
  66. }
  67. $sql = "INSERT INTO questionToCategory (questionId, categoryId) VALUES ($questionId, $categoryId)";
  68. $conn->query($sql);
  69. echo "inserted question $question into category $categoryName \r\n";
  70. }
  71. fclose($file);
  72. } else {
  73. echo 'Run with file as first argument';
  74. }