Hi Guys hope your all well,

I have found some code to create a quiz and this I have done, it was working a few weeks ago... but for some reason its now decied to stop working!

When I run the page on my localhost I'm getting the following eorror

Fatal error: Call to a member function fetch_assoc() on a non-object in C:\xampp\htdocs\quiz.php on line 8

This is the code so far

<?php
//Connect with mysql
$db = new mysqli("127.0.0.1", "root", "", "quiz");

//Perform the query to choose random questions
$query = $db->query("SELECT * FROM `table` ORDER BY RAND() LIMIT 20");

while ($row = $query->fetch_assoc()):
    $question = $row['question'];
    echo $question . "<br />";
endwhile;

//close result
$query->close();
//Close connection
$db->close();

session_start();
if (isset($_GET['question'])) {
    $question = preg_replace('/[^0-9]/', "", $_GET['question']);
    $next     = $question + 1;
    $prev     = $question - 1;
} // <--- I added this brace. You need to double-check it logically belongs here
if (!isset($_SESSION['qid_array']) && $question != 1) {
    $msg = "Sorry! No cheating.";
    header("location: start.php?msg=$msg");
    exit();
}
if (isset($_SESSION['qid_array']) && in_array($question, $_SESSION['qid_array'])) {
    $msg = "Sorry, Cheating is not allowed. You will now have to start over. Haha.";
    unset($_SESSION['answer_array']);
    unset($_SESSION['qid_array']);
    session_destroy();
    header("location: start.php?msg=$msg");
    exit();
}
if (isset($_SESSION['lastQuestion']) && $_SESSION['lastQuestion'] != $prev) {
    $msg = "Sorry, Cheating is not allowed. You will now have to start over. Haha.";
    unset($_SESSION['answer_array']);
    unset($_SESSION['qid_array']);
    session_destroy();
    header("location: start.php?msg=$msg");
    exit();
}
?>
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Quiz Page</title>

    <script type="text/javascript">
    function countDown(secs,elem) {
    var element = document.getElementById(elem);
    element.innerHTML = "You have "+secs+" seconds remaining.";
    if(secs < 1) {
    var xhr = new XMLHttpRequest();
    var url = "userAnswers.php";
    var vars = "radio=0"+"&qid="+<?php echo $question; ?>;
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function() {
    if(xhr.readyState == 4 && xhr.status == 200) {
    alert("You did not answer the question in the allotted time. It will be marked as incorrect.");
    clearTimeout(timer);
    }
    }
    xhr.send(vars);
    document.getElementById('counter_status').innerHTML = "";
    document.getElementById('btnSpan').innerHTML = '<h2>Times Up!</h2>';
    document.getElementById('btnSpan').innerHTML += '<a href="quiz.php?question=<?php echo $next; ?>">Click here now</a>';
    }
    secs--;
    var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000);
    }

    function getQuestion(){
    var hr = new XMLHttpRequest();
    hr.onreadystatechange = function(){
    if (hr.readyState==4 && hr.status==200){
    var response = hr.responseText.split("|");
    if(response[0] == "finished"){
    document.getElementById('status').innerHTML = response[1];
    }
    var nums = hr.responseText.split(",");
    document.getElementById('question').innerHTML = nums[0];
    document.getElementById('answers').innerHTML = nums[1];
    document.getElementById('answers').innerHTML += nums[2];
    }
    }
    hr.open("GET", "questions.php?question=" + <?php echo $question; ?>, true);
    hr.send();
    }
    function x() {
    var rads = document.getElementsByName("rads");
    for ( var i = 0; i < rads.length; i++ ) {
    if ( rads[i].checked ){
    var val = rads[i].value;
    return val;
    }
    }
    }
    function post_answer(){
    var p = new XMLHttpRequest();
    var id = document.getElementById('qid').value;
    var url = "userAnswers.php";
    var vars = "qid="+id+"&radio="+x();
    p.open("POST", url, true);
    p.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    p.onreadystatechange = function() {
    if(p.readyState == 4 && p.status == 200) {
    document.getElementById("status").innerHTML = '';
    alert("Thanks, Your answer was submitted"+ p.responseText);
    var url = 'quiz.php?question=<?php echo $next; 

    ?>';

    window.location = url;
    }
    }
    p.send(vars);
    document.getElementById("status").innerHTML = "processing...";
    }
    window.oncontextmenu = function(){
    return false;
    }
    </script>


    </head>

    <body onLoad="getQuestion()">
    <div id="status">
    <div id="counter_status"></div>
    <div id="question"></div>
    <div id="answers"></div>
    </div>


    </script>
    </body>
    </html> 

Any help would be great

Member Avatar for diafol

You "found" some code? Urgh. I'd send it back with a "broken in transit" sticker. All that raw js in the head makes me want to vom.

Fatal error: Call to a member function fetch_assoc() on a non-object in C:\xampp\htdocs\quiz.php on line 8

The $query doesn't exist as a object.

http://php.net/manual/en/mysqli.query.php

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.

I have updated the code and this is how it looks now

<?php
//Connect with mysql
$db = new mysqli("127.0.0.1", "root", "", "quiz");

//Perform the query to choose random questions
$query = $db->query("SELECT * FROM `table` ORDER BY RAND() LIMIT 20");
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!mysqli_query($link, "SET a=1")) {
    printf("Errormessage: %s\n", mysqli_error($link));
}

/* close connection */
mysqli_close($link);
while ($row = $query->fetch_assoc()):
    $question = $row['question'];

    echo $question . "<br />";
endwhile;

//close result
$query->close();
//Close connection
$db->close();

session_start();
if (isset($_GET['question'])) {
    $question = preg_replace('/[^0-9]/', "", $_GET['question']);
    $next     = $question + 1;
    $prev     = $question - 1;
} // <--- I added this brace. You need to double-check it logically belongs here
if (!isset($_SESSION['qid_array']) && $question != 1) {
    $msg = "Sorry! No cheating.";
    header("location: start.php?msg=$msg");
    exit();
}
if (isset($_SESSION['qid_array']) && in_array($question, $_SESSION['qid_array'])) {
    $msg = "Sorry, Cheating is not allowed. You will now have to start over. Haha.";
    unset($_SESSION['answer_array']);
    unset($_SESSION['qid_array']);
    session_destroy();
    header("location: start.php?msg=$msg");
    exit();
}
if (isset($_SESSION['lastQuestion']) && $_SESSION['lastQuestion'] != $prev) {
    $msg = "Sorry, Cheating is not allowed. You will now have to start over. Haha.";
    unset($_SESSION['answer_array']);
    unset($_SESSION['qid_array']);
    session_destroy();
    header("location: start.php?msg=$msg");
    exit();
}
?>
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Quiz Page</title>

    <script type="text/javascript">
    function countDown(secs,elem) {
    var element = document.getElementById(elem);
    element.innerHTML = "You have "+secs+" seconds remaining.";
    if(secs < 1) {
    var xhr = new XMLHttpRequest();
    var url = "userAnswers.php";
    var vars = "radio=0"+"&qid="+<?php echo $question; ?>;
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function() {
    if(xhr.readyState == 4 && xhr.status == 200) {
    alert("You did not answer the question in the allotted time. It will be marked as incorrect.");
    clearTimeout(timer);
    }
    }
    xhr.send(vars);
    document.getElementById('counter_status').innerHTML = "";
    document.getElementById('btnSpan').innerHTML = '<h2>Times Up!</h2>';
    document.getElementById('btnSpan').innerHTML += '<a href="quiz.php?question=<?php echo $next; ?>">Click here now</a>';
    }
    secs--;
    var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000);
    }

    function getQuestion(){
    var hr = new XMLHttpRequest();
    hr.onreadystatechange = function(){
    if (hr.readyState==4 && hr.status==200){
    var response = hr.responseText.split("|");
    if(response[0] == "finished"){
    document.getElementById('status').innerHTML = response[1];
    }
    var nums = hr.responseText.split(",");
    document.getElementById('question').innerHTML = nums[0];
    document.getElementById('answers').innerHTML = nums[1];
    document.getElementById('answers').innerHTML += nums[2];
    }
    }
    hr.open("GET", "questions.php?question=" + <?php echo $question; ?>, true);
    hr.send();
    }
    function x() {
    var rads = document.getElementsByName("rads");
    for ( var i = 0; i < rads.length; i++ ) {
    if ( rads[i].checked ){
    var val = rads[i].value;
    return val;
    }
    }
    }
    function post_answer(){
    var p = new XMLHttpRequest();
    var id = document.getElementById('qid').value;
    var url = "userAnswers.php";
    var vars = "qid="+id+"&radio="+x();
    p.open("POST", url, true);
    p.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    p.onreadystatechange = function() {
    if(p.readyState == 4 && p.status == 200) {
    document.getElementById("status").innerHTML = '';
    alert("Thanks, Your answer was submitted"+ p.responseText);
    var url = 'quiz.php?question=<?php echo $next; 

    ?>';

    window.location = url;
    }
    }
    p.send(vars);
    document.getElementById("status").innerHTML = "processing...";
    }
    window.oncontextmenu = function(){
    return false;
    }
    </script>


    </head>

    <body onLoad="getQuestion()">
    <div id="status">
    <div id="counter_status"></div>
    <div id="question"></div>
    <div id="answers"></div>
    </div>


    </script>
    </body>
    </html> 

I'm now getting the following

Notice: Undefined variable: link in C:\xampp\htdocs\quiz.php on line 13

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\quiz.php on line 13

Notice: Undefined variable: link in C:\xampp\htdocs\quiz.php on line 14

Warning: mysqli_error() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\quiz.php on line 14
Errormessage:
Notice: Undefined variable: link in C:\xampp\htdocs\quiz.php on line 18

Warning: mysqli_close() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\quiz.php on line 18

Fatal error: Call to a member function fetch_assoc() on a non-object in C:\xampp\htdocs\quiz.php on line 19

Member Avatar for diafol

Notice: Undefined variable: link in C:\xampp\htdocs\quiz.php on line 13

Referring to:

if (!mysqli_query($link, "SET a=1"))

Well, can't you see that $link has not been initialized?

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\quiz.php on line 13

This is telling you that you need to supply the MySQLi object $db).

BUT

You've mixed up procedural and OO MySQLi. Choose one method or the other and stick to it.

I sure hope to God that the code you pasted above isn't actually like that in your editor or even on your hard drive. Please tell me that you actually indent.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.