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 to get this quiz to work

    It sounds like your SQL query failed. For quick debugging, change this:

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

    to:

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

    This should exit the PHP script with an error message as to why the SQL query failed, and from there you can figure out how to fix it. Later, you could handle this more gracefully, e.g., check if $query is false, and if so, log the error message and print a human readable error message to the user instead of just terminating the script.

      Try this to give you a meaningful error you can work with:

      <?php
      //Connect with mysql
      $db = new mysqli("127.0.0.1", "root", "", "quiz");
      
      //Perform the query to choose random questions
      $query = "SELECT * FROM `table` ORDER BY RAND() LIMIT 20";
      $result = $db->query($query);
      if (!$result) {
          die(sprintf("Error: %s", $db->error));
      }
      while ($row = $result->fetch_assoc()):
          $question = $row['question'];
          echo $question . "<br />";
      endwhile;
      
      //close result
      $result->close();
      //Close connection
      $db->close();

        Oh, and I forgot to mention: you should not mix the normal syntax for control structures with the alternative syntax. Generally, the alternative syntax is more commonly used when using PHP as a template language.

          Can I ask what that means or maybe an example of that in the code laserlight? I'd like to learn a bit more about that but am not sure what to search for.

            laserlight;11046207 wrote:

            The PHP manual describes the Alternative syntax for control structures. You can see an example in the code that stokie-rich posted:

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

            Thanks for the explanation and link. I was not familiar with that syntax.

              hey thanks for all of the information guys, I have changed some code around and I'm now getting a more meaningful error now showing its as follows:

              Warning: require_once(classes/Cookie.php): failed to open stream: No such file or directory in C:\xampp\htdocs\core\init.php on line 24

              Fatal error: require_once(): Failed opening required 'classes/Cookie.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\core\init.php on line 24

                stokie-rich;11046211 wrote:

                hey thanks for all of the information guys, I have changed some code around and I'm now getting a more meaningful error now showing its as follows:

                Warning: require_once(classes/Cookie.php): failed to open stream: No such file or directory in C:\xampp\htdocs\core\init.php on line 24

                Fatal error: require_once(): Failed opening required 'classes/Cookie.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\core\init.php on line 24

                Oh this is the code at the moment:

                <?php
                //Connect with mysql
                $db = new mysqli("localhost", "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> 

                  What is your current code? This error message just means that you have the wrong path for require_once, or perhaps the file to be included really does not exist.

                  EDIT:
                  Okay, I see the code now. There does not appear to be any include or require, so it looks like you are not showing the relevant code. Also, note that the URL for a location header should be an absolute URL (this is documented in the PHP manual on the entry for [man]header/man).

                    laserlight;11046215 wrote:

                    What is your current code? This error message just means that you have the wrong path for require_once, or perhaps the file to be included really does not exist.

                    EDIT:
                    Okay, I see the code now. There does not appear to be any include or require, so it looks like you are not showing the relevant code. Also, note that the URL for a location header should be an absolute URL (this is documented in the PHP manual on the entry for [man]header/man).

                    This is the include file that its saying there is a problem:

                    <?php
                    session_start();
                    
                    // Create a global configuration
                    $GLOBALS['config'] = array(
                    	'mysql' => array(
                    		'host' 		=> 'localhost',
                    		'username' 	=> 'root',
                    		'password' 	=> '',
                    		'db' 		=> 'quiz'
                    	),
                    	'remember' => array(
                    		'cookie_name'	=> 'hash',
                    		'cookie_expiry' =>  604800
                    	),
                    	'session' => array(
                    		'session_name'	=> 'user',
                    		'token_name'	=> 'token'
                    	)
                    );
                    
                    // Autoload classes
                    function autoload($class) {
                    	require_once 'classes/' . $class . '.php';
                    }
                    spl_autoload_register('autoload');
                    
                    // Include functions
                    require_once 'functions/sanitize.php';
                    
                    // Check for users that have requested to be remembered
                    if(Cookie::exists(Config::get('remember/cookie_name'))) {
                    	$hash = Cookie::get(Config::get('remember/cookie_name'));
                    	$hashCheck = DB::getInstance()->get('users_session', array('hash', '=', $hash));
                    
                    if($hashCheck->count()) {
                    	$user = new User($hashCheck->first()->user_id);
                    	$user->login();
                    }
                    
                    }?>

                      I'm going to start the quiz all over again I'm going to sit down on sunday and go through the youtube videos again I have downloaded the code again so I'm going to see what happens I will let you know how I get on and hopefully you guys might be on hand if I need any help

                        laserlight;11046219 wrote:

                        Where is the Cookie class defined?

                        I've got to admit its been a few months since I looked at this quiz code so I'm going to watch all the videos again and make sure I understand it and get it this time!

                          laserlight;11046219 wrote:

                          Where is the Cookie class defined?

                          one would assume

                          stokie-rich;11046211 wrote:

                          hey thanks for all of the information guys, I have changed some code around and I'm now getting a more meaningful error now showing its as follows:

                          Warning: require_once(classes/Cookie.php): failed to open stream: No such file or directory in C:\xampp\htdocs\core\init.php on line 24

                          Fatal error: require_once(): Failed opening required 'classes/Cookie.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\core\init.php on line 24

                          Tells us Cookie class is defined in 'classes/Cookie.php' and is expected to be autoloaded

                          // Autoload classes 
                          function autoload($class) { 
                              require_once 'classes/' . $class . '.php'; 
                          } 
                          spl_autoload_register('autoload'); 
                          

                          Is probably the issue of file path or case...

                            Yes, I already mentioned this in post #10, that's why I asked where is the class defined, i.e., if it was defined elsewhere rather than not defined at all, the path could be corrected.

                              Write a Reply...