I'm making a test prep app. I store questions and answers in a DB, and when the user is taking the quiz, I instantiate the Question class defined in content.php
and call its getQuestions function to loop through and return data for the current question ID.
$question = new Question($questionID);
echo $question->getQuestions();
Which connects to the DB, runs the query for that question ID, and echos out a number of options as radio buttons:
while ($row = $imgpath->fetch_assoc()) {
$this->id = $row['question_id'];
echo '
<p>' . $row['question']. '</p><br/>
<br/><input type="radio" name="choice1" id="c1"> ' . $row['choice_1'] . ' , etc
The issue I'm having is, when the user selects a choice, and clicks the check Answer button, I'm getting breaking DB connection constants...
Use of undefined constant DB_HOST - assumed 'DB_HOST' in C:\wamp\www\...\php\dbconnect.php on line 2
The check answer button:
echo '<br/><br/><button id="checkAnswer" onclick="checkVal()">Check Answer</button>';
Which calls:
function checkVal() {
var chx = document.getElementsByTagName('input');
var userAnswer = null;
for (var i = 0; i < chx.length; i++) {
if (chx[i].type === 'radio' && chx[i].checked) {
userAnswer = chx[i].id;
}
}
$.get("./php/content.php", {_input : userAnswer, "_functionToRun" : "getAnswer"},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
Which returns:
$functionToRun = (isset($_GET['_functionToRun']) ? ($_GET['_functionToRun']) : 0);
if (isset($_GET['_functionToRun']) && !empty($_GET['_functionToRun'])) {
include 'dbconnect.php';
if ($functionToRun == "getAnswer") {
$qry =
"SELECT q.*
FROM questions q
WHERE question_id = $questionID";
$result = $mysqli->query($qry);
mysqli_close($mysqli);
$row = $result->fetch_assoc();
echo $row['answer'];
}
}
Question is: Why only on the ajax call are the dbconnection constants coming back undefined? Yet when I first load the page, the constants throw no errors?
dbconnect file: in root/php folder
, in same folder as content.php
$mysqli = new mysqli(DB_HOST, DB_UN, DB_PW, DB_NAME);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (Error code: " . $mysqli->connect_errno . ")... " . $mysqli->connect_error;
}
config.php: file in the root of website
if(!defined("DB_HOST")) define("DB_HOST", "stuff");
if(!defined("DB_UN")) define("DB_UN", "stuff");
if(!defined("DB_PW")) define("DB_PW", "stuff");
if(!defined("DB_NAME")) define("DB_NAME", "stuff");
config.php
is loaded from my index.php
file which determines which HTML to load:
include './config.php';
$action = isset($_GET['action']) ? $_GET['action'] : "";
switch($action) {
case 'practice':
require(TEMPLATE_PATH . "/practice.php");
break;
case 'about':
require(TEMPLATE_PATH . "/about.php");
break, etc...