0

Firstly, i'm sorry if this questions is mentioned before, but i don't find a good answer. I try to make a online quiz with images, but upload image don't work properly. After press the button to submit, questions is posted in my database, but image don't. In my database, i have one table with id column, question_id, question, type, image and name.

I don't understand exactly what happens...and i need your advice/indications.

I'm novice in php, so sorry for eventually big mistakes in my code.

Thank you in advance for help!

<?php

     if(isset($_POST['desc'])){
          if(!isset($_POST['iscorrect']) || $_POST['iscorrect'] == ""){
        echo "Sorry, important data to submit your question is missing. Please press back in your browser and try again and make sure you select a correct answer for the question.";
        exit();
    }
           if(!isset($_POST['type']) || $_POST['type'] == ""){
        echo "Sorry, there was an error parsing the form. Please press back in your browser and try again";
        exit();
    }
    require_once("scripts/connect_db.php");
    $question = $_POST['desc'];
    $answer1 = $_POST['answer1'];
    $answer2 = $_POST['answer2'];
    $answer3 = $_POST['answer3'];
    $answer4 = $_POST['answer4'];
    $type = $_POST['type'];
    $type = preg_replace('/[^a-z]/', "", $type);
    $isCorrect = preg_replace('/[^0-9a-z]/', "", $_POST['iscorrect']);
    $answer1 = strip_tags($answer1);
    $answer1 = mysqli_real_escape_string($connection,$answer1);
    $answer2 = strip_tags($answer2);
    $answer2 = mysqli_real_escape_string($connection,$answer2);
    $answer3 = strip_tags($answer3);
    $answer3 = mysqli_real_escape_string($connection,$answer3);
    $answer4 = strip_tags($answer4);
    $answer4 = mysqli_real_escape_string($connection,$answer4);
    $question = strip_tags($question);
    $question = mysqli_real_escape_string($connection,$question);

                    require("scripts/connect_db.php");
                    if(isset($_FILES['image'])){
                        echo $_FILES['image']['tmp_name'];
                        $image= base64_encode($image);

                            }
             if($image == TRUE){
                $result=mysqli_query($connection, "insert into questions (name,image) values ('$name','$image')") or die(mysqli_error($connection));
            }

    if($type == 'tf'){
    if((!$question) || (!$answer1) || (!$answer2) || (!$isCorrect)){
        echo "Sorry, All fields must be filled in to add a new question to the quiz. Please press back in your browser and try again.";
        exit();
        }
    }
    if($type == 'mc'){
    if((!$question) || (!$answer1) || (!$answer2) || (!$answer3) || (!$answer4) || (!$isCorrect)){
        echo "Sorry, All fields must be filled in to add a new question to the quiz. Please press back in your browser and try again.";
        exit();
        }
    }
    $sql = mysqli_query($connection,"INSERT INTO questions (question, type) VALUES ('$question', '$type')")or die(mysqli_error($connection));
        $lastId = mysqli_insert_id($connection);
        mysqli_query($connection,"UPDATE questions SET question_id='$lastId' WHERE id='$lastId' LIMIT 1")or die(mysqli_error($connection));
    //// Update answers based on which is correct //////////
    if($type == 'tf'){
        if($isCorrect == "answer1"){
        $sql2 = mysqli_query($connection,"INSERT INTO answers (question_id, answer, correct) VALUES ('$lastId', '$answer1', '1')")or die(mysqli_error($connection));
        mysqli_query($connection,"INSERT INTO answers (question_id, answer, correct) VALUES ('$lastId', '$answer2', '0')")or die(mysqli_error($connection));;
        $msg = 'Thanks, your question has been added';
      header('location: addQuestions.php?msg='.$msg.'');
    exit();
    }
    if($isCorrect == "answer2"){
        $sql2 = mysqli_query($connection,"INSERT INTO answers (question_id, answer, correct) VALUES ('$lastId', '$answer2', '1')")or die(mysqli_error($connection));
        mysqli_query($connection,"INSERT INTO answers (question_id, answer, correct) VALUES ('$lastId', '$answer1', '0')")or die(mysqli_error($connection));
        $msg = 'Thanks, your question has been added';
      header('location: addQuestions.php?msg='.$msg.'');
    exit();
        }   
    }
    if($type == 'mc'){
        if($isCorrect == "answer1"){
        $sql2 = mysqli_query($connection,"INSERT INTO answers (question_id, answer, correct) VALUES ('$lastId', '$answer1', '1')")or die (mysqli_error($connection));
        mysqli_query($connection,"INSERT INTO answers (question_id, answer, correct) VALUES ('$lastId', '$answer2', '0')")or die (mysqli_error($connection));
        mysqli_query($connection,"INSERT INTO answers (question_id, answer, correct) VALUES ('$lastId', '$answer3', '0')")or die (mysqli_error($connection));
        mysqli_query($connection,"INSERT INTO answers (question_id, answer, correct) VALUES ('$lastId', '$answer4', '0')")or die (mysqli_error($connection));
        $msg = 'Thanks, your question has been added';
      header('location: addQuestions.php?msg='.$msg.'');
    exit();
    }
    if($isCorrect == "answer2"){
        $sql2 = mysqli_query($connection,"INSERT INTO answers (question_id, answer, correct) VALUES ('$lastId', '$answer2', '1')")or die (mysqli_error($connection));
        mysqli_query($connection,"INSERT INTO answers (question_id, answer, correct) VALUES ('$lastId', '$answer1', '0')")or die(mysqli_error($connection));
        mysqli_query($connection,"INSERT INTO answers (question_id, answer, correct) VALUES ('$lastId', '$answer3', '0')")or die(mysqli_error($connection));
        mysqli_query($connection,"INSERT INTO answers (question_id, answer, correct) VALUES ('$lastId', '$answer4', '0')")or die(mysqli_error($connection));
        $msg = 'Thanks, your question has been added';
      header('location: addQuestions.php?msg='.$msg.'');
    exit();
    }
    if($isCorrect == "answer3"){
        $sql2 = mysqli_query($connection,"INSERT INTO answers (question_id, answer, correct) VALUES ('$lastId', '$answer3', '1')")or die(mysqli_error($connection));
        mysqli_query($connection,"INSERT INTO answers (question_id, answer, correct) VALUES ('$lastId', '$answer1', '0')")or die(mysqli_error($connection));
        mysqli_query($connection,"INSERT INTO answers (question_id, answer, correct) VALUES ('$lastId', '$answer2', '0')")or die(mysqli_error($connection));
        mysqli_query($connection,"INSERT INTO answers (question_id, answer, correct) VALUES ('$lastId', '$answer4', '0')")or die(mysqli_error($connection));
        $msg = 'Thanks, your question has been added';
      header('location: addQuestions.php?msg='.$msg.'');
    exit();
    }
    if($isCorrect == "answer4"){
        $sql2 = mysqli_query($connection,"INSERT INTO answers (question_id, answer, correct) VALUES ('$lastId', '$answer4', '1')")or die(mysqli_error($connection));
        mysqli_query($connection,"INSERT INTO answers (question_id, answer, correct) VALUES ('$lastId', '$answer1', '0')")or die(mysqli_error($connection));
        mysqli_query($connection,"INSERT INTO answers (question_id, answer, correct) VALUES ('$lastId', '$answer2', '0')")or die(mysqli_error($connection));
        mysqli_query($connection,"INSERT INTO answers (question_id, answer, correct) VALUES ('$lastId', '$answer3', '0')")or die(mysqli_error($connection));
        $msg = 'Thanks, your question has been added';
      header('location: addQuestions.php?msg='.$msg.'');
    exit();
        }
    }
}
?>
<?php 
$msg = "";
if(isset($_GET['msg'])){
    $msg = $_GET['msg'];
}
?>
<?php 
if(isset($_POST['reset']) && $_POST['reset'] != ""){
    $reset = preg_replace('/^[a-z]/', "", $_POST['reset']);
    require_once("scripts/connect_db.php");
    mysqli_query($connection,"TRUNCATE TABLE questions")or die(mysqli_error($connection));
    mysqli_query($connection,"TRUNCATE TABLE answers")or die(mysqli_error($connection));
    $sql1 = mysqli_query($connection,"SELECT id FROM questions LIMIT 1")or die(mysqli_error($connection));
    $sql2 = mysqli_query($connection,"SELECT id FROM answers LIMIT 1")or die(mysqli_error($connection));
    $numQuestions = mysqli_num_rows($sql1);
    $numAnswers = mysqli_num_rows($sql2);
    if($numQuestions > 0 || $numAnswers > 0){
        echo "Sorry, there was a problem reseting the quiz. Please try again later.";
        exit();
    }else{
        echo "Thanks! The quiz has now been reset back to 0 questions.";
        exit();
    }
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Create A Quiz</title>
<script>
function showDiv(el1,el2){
    document.getElementById(el1).style.display = 'block';
    document.getElementById(el2).style.display = 'none';
}
</script>
<script>
function resetQuiz(){
    var x = new XMLHttpRequest();
            var url = "addQuestions.php";
            var vars = 'reset=yes';
            x.open("POST", url, true);
            x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            x.onreadystatechange = function() {
        if(x.readyState == 4 && x.status == 200) {
            document.getElementById("resetBtn").innerHTML = x.responseText;

    }
}
x.send(vars);
document.getElementById("resetBtn").innerHTML = "processing...";

}
</script>
<style type="text/css">
.content{
    margin-top:48px;
    margin-left:auto;
    margin-right:auto;
    width:780px;
    border:#333 1px solid;
    border-radius:12px;
    -moz-border-radius:12px;
    padding:12px;
    display:none;
}
</style>
</head>

<body>
   <div style="width:700px;margin-left:auto;margin-right:auto;text-align:center;">
   <p style="color:#06F;"><?php echo $msg; ?></p>
    <h2>What type of question would you like to create?</h2>
    <button onClick="showDiv('tf', 'mc')">True/False</button>&nbsp;&nbsp;<button onClick="showDiv('mc', 'tf')">Multiple Choice</button>&nbsp;&nbsp;
    <span id="resetBtn"><button onclick="resetQuiz()">Reset quiz to zero</button></span>
   </div>
  <div class="content" id="tf">
    <h3>True or false</h3>
        <form action="addQuestions.php" name="addQuestion" method="post">
    <strong>Please type your new question here</strong>
        <br />
            <textarea id="tfDesc" name="desc" style="width:400px;height:95px;"></textarea>
          <br />
        <br />
        <strong>Please select whether true or false is the correct answer</strong>
        <br />
            <input type="text" id="answer1" name="answer1" value="True" readonly>&nbsp;
              <label style="cursor:pointer; color:#06F;">
            <input type="radio" name="iscorrect" value="answer1">Correct Answer?</label>
          <br />
        <br />
            <input type="text" id="answer2" name="answer2" value="False" readonly>&nbsp;
              <label style="cursor:pointer; color:#06F;">
              <input type="radio" name="iscorrect" value="answer2">Correct Answer?
            </label>
          <br />
        <br />
        <input type="hidden" value="tf" name="type">
        <input type="submit" value="Add To Quiz">
    </form>
 </div>
 <div class="content" id="mc">
    <h3>Multiple Choice</h3>
    <form action="addQuestions.php" name="addMcQuestion" method="post">
    <strong>Please type your new question here</strong>
        <br />
        <textarea id="mcdesc" name="desc" style="width:400px;height:95px;"></textarea>
        <br />
      <br />
    <strong>If you want to upload image, please upload here:</strong>
    <br />

        <br/>
            <input type="file" name="submit" />

    <br />
    <br />

    <strong>Please create the first answer for the question</strong>
        <br />
        <input type="text" id="mcanswer1" name="answer1">&nbsp;
          <label style="cursor:pointer; color:#06F;">
          <input type="radio" name="iscorrect" value="answer1">Correct Answer?
        </label>
      <br />
    <br />
    <strong>Please create the second answer for the question</strong>
    <br />
        <input type="text" id="mcanswer2" name="answer2">&nbsp;
          <label style="cursor:pointer; color:#06F;">
          <input type="radio" name="iscorrect" value="answer2">Correct Answer?
        </label>
      <br />
    <br />
    <strong>Please create the third answer for the question</strong>
    <br />
        <input type="text" id="mcanswer3" name="answer3">&nbsp;
          <label style="cursor:pointer; color:#06F;">
          <input type="radio" name="iscorrect" value="answer3">Correct Answer?
        </label>
      <br />
    <br />
    <strong>Please create the fourth answer for the question</strong>
    <br />
        <input type="text" id="mcanswer4" name="answer4">&nbsp;
          <label style="cursor:pointer; color:#06F;">
          <input type="radio" name="iscorrect" value="answer4">Correct Answer?
        </label>
      <br />
    <br />
    <input type="hidden" value="mc" name="type">
    <input type="submit" name="submit" value="Add To Quiz">
    </form>
 </div>
</body>
</html>
Diaconu Eduard
  • 161
  • 1
  • 3
  • 14
  • You need to use a `multipart` form enctype to upload images. ~~Also, have you checked the permissions for the images folder?~~ (Edit: looks like you're converting to Base64 rather than storing the image as a file, so the first part/answer by [@73bad...](http://stackoverflow.com/users/2999853/73badf2bb626675fdd519011cbb39e) should be enough.) – owenvoke Apr 21 '16 at 16:23
  • Here is a printscreen with my database structure: http://imagizer.imageshack.us/a/img923/5791/Xgi1ib.jpg – Diaconu Eduard Apr 21 '16 at 16:36

3 Answers3

0

Use this:

<form action="addQuestions.php" name="addQuestion" method="post" enctype="multipart/form-data">
.....................
.....................
</form>
Md Mahfuzur Rahman
  • 2,319
  • 2
  • 18
  • 28
  • Thank you for your prompt answer I changed, but... the image still dosen't uploaded. Mayabe it's possible wrong created my database. Here is a print screen: http://imageshack.com/a/img923/5791/Xgi1ib.jpg Thank you again! – Diaconu Eduard Apr 21 '16 at 16:34
0

From your code it looks like $image is unset. I can see you set the variable to $image= base64_encode($image); but it hasn't been set before that.

Please make sure that the $image variable is set as it looks like you're trying to do something like this:

$image = base64_encode(
        file_get_contents(
            $_FILES['image']['tmp_name']
        )
);

P.S. As mentioned before, the form must be using an enctype of multipart/form-data as shown in @73badf2...'s answer.

Edit:

I have tested this code locally and it works fine. (using a string instead of longblob.)

$connection = mysqli_connect('127.0.0.1', 'root', '', 'test');

if (isset($_FILES['image'])) {
    $name = $_FILES['image']['tmp_name'];
    $image = base64_encode(
        file_get_contents(
            $_FILES['image']['tmp_name']
        )
    );
    if (!empty($image)) {
        $result = mysqli_query($connection, "insert into questions (name,image) values ('$name','$image')");
    }
}

Have you set the permissions for the tmp folder?

Community
  • 1
  • 1
owenvoke
  • 228
  • 4
  • 16
  • Thank for your answer! I initiated variabile $image, but unfortunately, same result...image don't upload. P.S.: I change enctype of multipart/form-data. Thank you again! – Diaconu Eduard Apr 21 '16 at 17:48
  • Try using `if (!empty($image)) { $result = ... }` because `$image` won't be true, as it is not a boolean. – owenvoke Apr 21 '16 at 17:50
  • I modified, but...still same result. Thank for your interest about my problem, i don't know what do without your help. Look, i insert here a printscreen with my code and my database: http://imagizer.imageshack.us/a/img924/5435/SJMVys.jpg – Diaconu Eduard Apr 21 '16 at 18:08
  • @DiaconuEduard is there any reason for using a blob? A base64 encoded file becomes a string. I'd recommend using a `varchar` with a length of over 5000. I have tested this locally (will add it to my answer.) – owenvoke Apr 21 '16 at 18:44
  • I think the problem with my code is in another part, because i run this part of code (with upload) in another page and i can insert picture in my database... but i don't find where is the problem. – Diaconu Eduard Apr 21 '16 at 18:48
  • By the looks of it in your code you haven't set the variable `$name`. So the query may be failing. But, I'll take a full look at the rest of your code for you :) – owenvoke Apr 21 '16 at 18:50
  • 1
    I modified type of image in varchar, but the problem not resolved. I don't know exactly how to say thank you...I really appreciate your help ! – Diaconu Eduard Apr 21 '16 at 18:57
  • @PCgamer, "permissions for the tmp folder"-i think here is my problem. I have one script with connection at database, but i don't have idea how to set this permission. If I aren't too insistent, can you give me an idea? – Diaconu Eduard Apr 21 '16 at 19:32
  • Of course. You'll need to set the folder to `777`. To do this you can use FileZilla (right click the folder and "File Permissions..." from here enter 777 in the box and set it recursively). If using SSH or bash, it's just `chmod 777`. This can also be done in PHP using the [chmod()](http://php.net/manual/en/function.chmod.php) function. – owenvoke Apr 21 '16 at 19:34
  • Really, really...really thank you! I found this http://stackoverflow.com/questions/6433643/file-permissions-and-chmod-how-to-set-777-in-php-upon-file-creation , but i don't know exactly where could be placed. In code with "add questions" or in code with connection? And i have another question, if i can put picture in my database with same code using the part with upload in another page, it's necessary to set this permission? If i can uploaded picture, this permission is not set ? – Diaconu Eduard Apr 21 '16 at 20:08
0

I solved problem. :) She comes from:

<input type="file" name="submit" />

I replaced "submit", with "image" and now works fine.

Thanks for guidance!

Now i have another problem, images posted in database with another id... i researched why, but i don't find the answer. If have an idea, please tell me.

Have a nice day!

Diaconu Eduard
  • 161
  • 1
  • 3
  • 14