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