Avatar billede jan2001 Nybegynder
06. januar 2006 - 17:44 Der er 15 kommentarer og
1 løsning

PHP øv altså!

Jeg har har på det sidste været lidt nødtvungen til at benytte mig af PHP-scripts fordi der simpelthen er mange gode imellem.
Egentlig også ok, hvis bare jeg forstod det bedre.
Jeg har lige fundet et script, som jeg synes er meget brugbart, men mangler en lille feature, som blot er et ekstra tekstfelt i databasen. Jeg har forsøgt at tilføje dette felt i scriptet, men uden held.
Når scriptet køres vises bare en hvis side.
Hvorfor kan PHP ikke fortælle, hvad der er galt? Når jeg laver fejl i et ASP-script, får jeg altid en fejlmedellelse. ??
Det er ikke kun dette script, som giver mig en hvid side. Andre scripts jeg har hentet har også gjort det samme. Hvad sker der?
Avatar billede jaw Nybegynder
06. januar 2006 - 17:48 #1
Umiddelbart er den server du bruger så sat op til ikke at vise debug-meddelelser, hvilket virkelig kan være træls. Som standard viser PHP de fejl der er.

Muligvis, medmindre det er parse-error's som bliver valideret før et evt. output, så kan denne linie i toppen af filen måske hjælpe:
ini_set('error_reporting', E_ALL);

Hvis vi så snakker MySQL, så vil en tilføjelse af or die(mysql_error()); til et udtræk give hele fejlmeddelelsen fra MySQL-servere, altså f.eks.:
mysql_query("SELECT * FROM tabel") or die(mysql_error());
eller bare:
echo mysql_error();
efter udtrækket.

Ellers kan du jo prøve og paste dit script her, så kan vi måske i fællesskab finde frem til fejlen :)
Avatar billede jan2001 Nybegynder
06. januar 2006 - 18:22 #2
Har jeg så lige prøvet flere steder, men der sker intet.
scriptet består af flere filer, men de som jeg lige kan se har noget at gøre med det er nedenstående. Jeg forsøger at indsætte et input felt, hvor der kan skrives en sti til et billede. qimage hedder feltet.

<?php

    // NueQuiz PRO - Lite
    // v 0.83b
    // Admin Script
    // Rev. History
    // v. 0.82 - stuff was broken
    // v. 0.83 - stuff was fixed

    session_start();
    define( 'CFG_LIB_PATH', 'nq_lib/' );
    define( 'CFG_STYLE_PATH', 'nq_style/' );

    header("Cache-control: private");

    require_once(CFG_LIB_PATH . "Database.class.php");
    require_once(CFG_LIB_PATH . "Question.class.php");
    require_once(CFG_LIB_PATH . "config.php");
    require_once(CFG_LIB_PATH . "QuizOperations.class.php");
    require_once(CFG_LIB_PATH . "dbImporter.php" );

    $timeStart = microtime(true);

    $db = new Database( CFG_DB_SERVER, CFG_DB_USERNAME, CFG_DB_PASSWORD, CFG_DB_NAME );    // Getting pass from db.
    $db->doQuery("SELECT config,value FROM nq_Config WHERE config='password'");
    $temp = $db->nextAssoc();
    $dbPass = $temp['value'];

    if(isset($_POST['action']))
        $a = $_POST['action'];
    elseif(isset($_GET['action']))
        $a = $_GET['action'];
    else
        $a = "Main";

    $status = "&nbsp;";
    $tab = 0;

    if($dbPass == $_SESSION['password'] || $dbPass == md5($_POST['password'])) {        // Checking Password
        $content = "";

        switch($a) {
            /*--------------------------------------------------*/
            case "Save Config":
                $qo = new QuizOperations();

                if(md5($_POST['oldpass']) == $qo->getPassword() && md5($_POST['newpass1']) == md5($_POST['newpass2'])) {
                    $qo->setPassword(md5($_POST['newpass1']));
                    $_SESSION['password'] = md5($_POST['newpass1']);
                    $status = "Configuration has been saved.";
                } else
                    if($_POST['oldpass'] != "" && $_POST['newpass1'] != "" && $_POST['newpass2'] != "")
                        $status = "Could not modify password. Passwords do not match.";
                    else
                        $status = "Configuration has been saved.";

                if($_POST['quizurl'] != "") {
                    $i = strlen($_POST['quizurl']) - 1;
                    $url = $_POST['quizurl'];
                    if($url{$i} == "/") {                                // Removing backslash from url.
                        $status .= " Backslash removed.";
                        $qo->setQuizURL(substr($_POST['quizurl'],0,$i));
                    } else
                        $qo->setQuizURL($_POST['quizurl']);
                }
                if($_POST['homeurl'] != "")
                    $qo->setHomeURL($_POST['homeurl']);
                if($_POST['homename'] != "")
                    $qo->setHomeName($_POST['homename']);

            // NO BREAK // Continue to display.

            /*--------------------------------------------------*/
            case "mConfig":
                $qo = new QuizOperations();

                $quizurl = $qo->getQuizURL();
                $homeurl = $qo->getHomeURL();
                $homename = $qo->getHomeName();

                $content .= "
                <tr><td class=\"head\" colspan=\"2\">General Configuration :.</td></tr>
                <tr><td class=\"right\" width=\"50%\">Old Password:</td><td class=\"left\" width=\"50%\"><input class=\"textBox medium\" name=\"oldpass\" type=\"password\"/></td></tr>
                <tr><td class=\"right\" width=\"50%\">New Password:</td><td class=\"left\" width=\"50%\"><input class=\"textBox medium\" name=\"newpass1\" type=\"password\"/></td></tr>
                <tr><td class=\"right\" width=\"50%\">Confirm New Password:</td><td class=\"left\" width=\"50%\"><input class=\"textBox medium\" name=\"newpass2\" type=\"password\"/></td></tr>
                <tr><td>&nbsp;</td><td>&nbsp;</td></tr>
                <tr><td class=\"right\" width=\"50%\">Homepage URL:</td><td class=\"left\" width=\"50%\"><input class=\"textBox\" name=\"homeurl\" type=\"text\" value=\"$homeurl\"/></td></tr>
                <tr><td class=\"right\" width=\"50%\">Home Name:</td><td class=\"left\" width=\"50%\"><input class=\"textBox\" name=\"homename\" type=\"text\" value=\"$homename\"/></td></tr>
                <tr><td class=\"right\" width=\"50%\">Quiz URL:</td><td class=\"left\" width=\"50%\"><input class=\"textBox\" name=\"quizurl\" type=\"text\" value=\"$quizurl\"/></td></tr>
                <tr><td>&nbsp;</td><td class=\"left\"><input class=\"button large\" name=\"action\" type=\"submit\" value=\"Save Config\" /></td></tr>
                ";

                $tab = 2;
                break;

            /*--------------------------------------------------*/
            case "Import Database":

                if( $_POST['filename'] )
                    if( !( $log = importFlatDB( $db, "import_db/" . $_POST['filename'] ) ))
                        $status = "Error: Import failed.";
                    else
                        $status = "Successful import.";

                    $content .= "
                        <tr><td class=\"head\" colspan=\"2\">Import Flat File Database :.</td></tr>
                        <tr><td colspan=\"2\">Note: The file must be in the import_db directory. This is used to import databases from the original perl version of NueQuiz.</td></tr>
                        <tr><td class=\"right\" width=\"50%\">Filename:</td><td class=\"left\" width=\"50%\"><input class=\"textBox medium\" name=\"filename\" type=\"text\"/></td></tr>
                        <tr><td>&nbsp;</td><td class=\"left\"><input class=\"button large\" name=\"action\" type=\"submit\" value=\"Import Database\" /></td></tr>
                        ";

                $tab = 2;
            break;
            /*--------------------------------------------------*/
            case "mStats":
                $content .= "<tr><td class=\"right\" width=\"100%\">Under Development.</td></tr>";
                $tab = 3;
                break;

            /*--------------------------------------------------*/
            case "mQuizzes":
                $content .= "<tr><td class=\"head\" colspan=\"2\">General Quiz Options :.</td></tr><tr><td width=\"50%\" class=\"right\">Import NueQuiz flat file database:</td><td><form action=\"admin.php?" . strip_tags(SID) . "\" method=\"POST\"><input class=\"button large\" name=\"action\" type=\"submit\" value=\"Import Database\" /></form></td></tr><tr><td width=\"50%\"class=\"right\">Create new quiz:</td><td><form action=\"admin.php?" . strip_tags (SID) . "\" method=\"POST\"><input class=\"button large\" name=\"action\" type=\"submit\" value=\"Add New Quiz\" /></form></td></tr></table>";

                $content .= "<table class=\"inner font left wide\"><tr><td class=\"head\" colspan=\"2\">Current Quizzes :.</td>";

                $db->doQuery("SELECT id,name FROM nq_Quizzes");
                if($db->resultNumRows() != 0)
                    while($temp = $db->nextAssoc()) {
                            $id = $temp['id'];
                            $name = $temp['name'];
                            $content .= "<tr><td class=\"right\" width=\"50%\">$name:</td><td class=\"left\" width=\"50%\"><form action=\"admin.php?" . strip_tags(SID) . "\" method=\"POST\"><input type=\"hidden\" name=\"quiz\" value=\"$id\" /><input class=\"button medium\" name=\"action\" type=\"submit\" value=\"Edit\" /><input class=\"button medium\" name=\"action\" type=\"submit\" value=\"Remove\" /></form></td></tr>";
                    }
                else
                    $content .= "<tr><td class=\"right\" width=\"100%\">No quizzes exist in the database.</td></tr>";

                $status = "Found " . $db->resultNumRows() . " quizzes.";
                $tab = 1;
                break;

            /*--------------------------------------------------*/
            case "Add New Quiz":
                $content .= "
                    <tr>
                        <td class=\"head sepa\" colspan=\"2\">New Quiz Configuration :.</td>
                    </tr>
                    <tr>
                        <td class=\"right\">Title:</td>
                        <td><input class=\"textBox\" type=\"text\" name=\"qName\" /></td>
                    </tr>
                    <tr>
                        <td class=\"right\">Description:</td>
                        <td><textarea name=\"intro\" rows=\"4\" cols=\"20\"></textarea></td>
                    </tr>
<tr>
                        <td class=\"right\">Image:</td>
                        <td><input class=\"textBox\" type=\"text\" name=\"qimage\" /></td>
                    </tr>
                    <tr>
                        <td class=\"right top\">Questions/Page:</td>
                        <td><input class=\"numBox\" name=\"qPerPage\" size=\"2\" type=\"text\" value=\"5\" /></td>
                    </tr>
                    <tr>
                        <td class=\"right\">Shuffle Choices:</td>
                        <td><input type=\"checkbox\" name=\"shuffleC\" /></td>
                    </tr>
                    <tr>
                        <td class=\"right\">Shuffle Questions:</td>
                        <td><input type=\"checkbox\" name=\"shuffleQ\" /></td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                        <td><form action=\"admin.php?" . strip_tags(SID) . "\" method=\"POST\"><input class=\"button medium font\" name=\"action\" type=\"submit\" value=\"Add Quiz\" /></td>
                    </tr>
                ";
                $tab = 1;
                break;

            /*--------------------------------------------------*/
            case "Add Quiz":
            $qo = new QuizOperations();

            if(get_magic_quotes_gpc())
                $qo->addQuiz( stripslashes($_POST['qName']), stripslashes($_POST['intro']), $_POST['qPerPage'], $_POST['shuffleC'], $_POST['shuffleQ'], $_POST['qimage']);
            else
                $qo->addQuiz( $_POST['qName'], $_POST['intro'], $_POST['qPerPage'], $_POST['shuffleC'], $_POST['shuffleQ'], $_POST['qimage']);

            saveMessage ("Message", "Quiz added successfully.");

            $url = "Location: admin.php?" . strip_tags(SID) . "&action=mQuizzes";
            header("$url");
            break;
            /*--------------------------------------------------*/
            case "Add Question":
                if (!isset ($_POST['add']) && !isset ($_POST['sub']))
                {
                    $id = $_POST['qId'];
                    $qo = new QuizOperations();

                    if(get_magic_quotes_gpc())
                        $qo->addQuestion( $_POST['qId'], stripslashes($_POST['question']), $_POST['choice'], $_POST['correct'], stripslashes($_POST['reason']));
                    else
                        $qo->addQuestion( $_POST['qId'], $_POST['question'], $_POST['choice'], $_POST['correct'], $_POST['reason']);

                    if (count ($_POST['choice']) > 1)
                        saveMessage ("Message", "New question added successfully.");
                    else
                        saveMessage ("Warning", "The newly added question has less than two choices. It has been added to the quiz, however questions with fewer than two choices are not displayed to users taking the quiz. You may add choices to this question by clicking the appropriate 'Edit' button below.");

                    $url = "Location: admin.php?" . strip_tags(SID) . "&action=Edit&quiz=" . $_POST['qId'];
                    header("$url");
                    break;
                    exit (0);
                }
                else
                {
                    addSubChoices ($_POST['choice'], $_POST['correct'], $_POST['add'], $_POST['sub']);
                }
                // fall through to "Add New Question" case

            case "Add New Question":

                if (!isset ($_POST['choice']))
                {
                    if (!is_numeric ($_POST['nChoices']) || $_POST['nChoices'] < 1)
                    {
                        $_POST['nChoices'] = 1;
                    }
                    else
                    {
                        settype ($_POST['nChoices'], "int");
                    }
                    $choiceArray = array_fill (1, $_POST['nChoices'], "");
                    $correctIndex = 1;
                }
                else
                {
                    $choiceArray = $_POST['choice'];
                    $correctIndex = $_POST['correct'];
                }
                $content = generateEditQuestionForm ($_POST['qId'], $_POST['question'], $_POST['reason'], $choiceArray, $correctIndex, "Adding New Question :.", "Add Question");

            break;

            /*--------------------------------------------------*/
            case "Add New Choices":    // no longer used
                $id = $_POST['qId'];
                $content = "<tr>
                            <td class=\"head\" colspan=\"2\">Adding More Choices :.</td>
                            </tr>";
                $num = $_POST['nChoices'];
                if($num < 1)
                    $num = 5;

                $content .= "<tr>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td></tr>";

                for($i = 1; $num != $i - 1; $i++) {
                        $content .= "<tr>
                            <td class=\"right\">Choice $i:</td>
                            <td><input class=\"textBox\" name=\"choices[$i]\" type=\"text\" /></td>
                            </tr>";
                }

                $content .= "
                        <tr>
                            <td>&nbsp;</td>
                            <td colspan=\"2\"><input type=\"hidden\" name=\"qId\" value=\"$id\" /><input class=\"button font\" name=\"action\" type=\"submit\" value=\"Add Choices\" /></td>
                        </tr>";

            break;

            /*--------------------------------------------------*/
            case "Add Choices":    // no longer used
                $id = $_POST['qId'];
                $qo = new QuizOperations();
                $qo->addChoices( $_POST['qId'], $_POST['choices'], NULL);

                $url = "Location: admin.php?" . strip_tags(SID) . "&action=mQuizzes";
                header("$url");
            break;

            /*--------------------------------------------------*/
            case "Save Settings":
            $qo = new QuizOperations();
            if($_POST['shuffleC'] == "on")
                $sC = 1;
            else
                $sC = 0;
            if($_POST['shuffleQ'] == "on")
                $sQ = 1;
            else
                $sQ = 0;

            if(get_magic_quotes_gpc())
                $qo->updateQuiz($_POST['qId'], stripslashes($_POST['qName']), stripslashes($_POST['intro']), $_POST['qPerPage'], $_POST['qimage'], $sC, $sQ);
            else
                $qo->updateQuiz($_POST['qId'], $_POST['qName'], $_POST['intro'], $_POST['qPerPage'], $_POST['qimage'], $sC, $sQ);

            saveMessage ("Message", "Quiz settings saved successfully.");

            $url = "Location: admin.php?" . strip_tags(SID) . "&action=Edit&quiz=" . $_POST['qId'];
            header("$url");
            break;

            /*--------------------------------------------------*/

            case "Save Question":
                if (!isset ($_POST['add']) && !isset ($_POST['sub']))
                {
                    $id = $_POST['qId'];
                    $qo = new QuizOperations();
                    $qo->removeAllChoices($_POST['qId']);
                    $qo->addChoices( $_POST['qId'], $_POST['choice'], $_POST['correct']);
                    if(get_magic_quotes_gpc())
                        $qo->updateQuestion( $_POST['qId'], stripslashes($_POST['question']), stripslashes($_POST['reason']), NULL );
                    else
                        $qo->updateQuestion( $_POST['qId'], $_POST['question'], $_POST['reason'], NULL );

                    $db->doQuery("SELECT quiz FROM nq_Questions where id='" . $_POST['qId'] . "'");
                    if($db->resultNumRows() > 0)
                    {
                        $tempQ = $db->nextAssoc();
                        $redirect = "&action=Edit&quiz=" . $tempQ['quiz'];
                    }
                    else
                    {
                        $redirect = "&action=mQuizzes";
                    }

                    if (count ($_POST['choice']) > 1)
                        saveMessage ("Message", "Question saved successfully.");
                    else
                        saveMessage ("Warning", "Question has been saved, but it has less than two choices. Questions with fewer than two choices are not displayed to users taking the quiz. You will have to add choices to this question before it will be displayed.");

                    $url = "Location: admin.php?" . strip_tags(SID) . $redirect;
                    header("$url");
                    break;
                    exit (0);
                }
                // Fall through

            /*--------------------------------------------------*/
            case "Edit":
                $qo = new QuizOperations();
                if(isset($_POST['quiz']) || isset ($_GET['quiz'])) {
                    if (isset ($_POST['quiz']))
                        $id = $_POST['quiz'];
                    else
                        $id = $_GET['quiz'];

                    $db->doQuery("SELECT * FROM nq_Quizzes WHERE id='$id'");
                    $quiz = $db->nextAssoc();
                    $title = $quiz['name'];
                    $intro = $quiz['intro'];
                    $perPage = $quiz['per_page'];
                    $sc = $quiz['shuffle_choices'];
                    $sq = $quiz['shuffle_questions'];
                                        $image = $quiz['qimage'];

                    $content .= "
                        <tr>
                            <td class=\"head sepa\" colspan=\"2\">Quiz Configuration :.</td>
                        </tr>
                        <tr>
                            <td class=\"right\">Title:</td>
                            <td><input class=\"textBox\" type=\"text\" name=\"qName\" value=\"$title\"/></td>
                        </tr>
                        <tr>
                            <td class=\"right\">Description:</td>
                            <td><textarea rows=\"4\" cols=\"20\" name=\"intro\">$intro</textarea></td>
                        </tr>
<tr>
                            <td class=\"right\">Image:</td>
                            <td><input class=\"textBox\" type=\"text\" name=\"qimage\" value=\"$image\"/></td>
                        </tr>
                        <tr>
                            <td class=\"right top\">Questions/Page:</td>
                            <td><input class=\"numBox\" name=\"qPerPage\" size=\"2\" type=\"text\" value=\"$perPage\" /></td>
                        </tr>
                        <tr>
                            <td class=\"right\">Shuffle Choices:</td>
                            <td><input type=\"checkbox\" name=\"shuffleC\"
                    ";

                    if($sc == 1) $content .= " checked";
                    $content .= " /></td>
                        </tr>
                        <tr>
                            <td class=\"right\">Shuffle Questions:</td>
                            <td><input type=\"checkbox\" name=\"shuffleQ\"
                    ";

                    $url = $qo->getQuizURL() . "?quiz=" . $id;

                    if($sq == 1) $content .= " checked";
                    $content .= " /></td>
                        </tr>
                        <tr>
                            <td>&nbsp;</td>
                            <td><input type=\"hidden\" name=\"qId\" value=\"$id\" /><input class=\"button large font\" name=\"action\" type=\"submit\" value=\"Save Settings\" /></form></td>
                        </tr>
                        <tr>
                            <td colspan=\"2\">&nbsp;</td>
                        </tr>
                        </table>

                        <table class=\"inner font left wide\">
                        <tr>
                            <td class=\"head sepa\">Quiz Access code :.</td>
                        </tr>
                        <tr><td>The following is a code snippet to access this quiz.</td></tr>
                        <tr><td><blockquote><br /><code>&lt;a href=\"$url\"&gt; $title &lt;/a&gt;</code><br /><br /></blockquote></td></tr>
                        </table>

                        <table class=\"inner font left wide\">
                        <tr>
                            <td class=\"head sepa\" colspan=\"2\">Add New Question :.</td>
                        </tr>
                        <tr><td class=\"right\">Choices:</td><td><form action=\"admin.php?" . strip_tags(SID) . "\" method=\"POST\"><input type=\"hidden\" name=\"qId\" value=\"$id\" /><input class=\"numBox\" name=\"nChoices\" size=\"2\" type=\"text\" value=\"5\" /><input class=\"button font\" name=\"action\" type=\"submit\" value=\"Add New Question\" /></form></td></tr>
                        </table>
                        <table class=\"inner font left wide\">
                        <tr>
                            <td class=\"head sepa\" colspan=\"2\">Current Quiz Questions :.</td>
                        </tr>
                    ";

                    $db->doQuery("SELECT * FROM nq_Questions where quiz='$id'");
                    if($db->resultNumRows() > 0) {
                        while($tempQ = $db->nextAssoc()) {            // For all question in quiz.
                            $id = $tempQ['id'];
                            if(strlen($tempQ['question']) > 50) {
                                $question =  substr($tempQ['question'], 0, 50);
                                $question .= "...";
                            } else
                                $question = $tempQ['question'];
                            $content .= "<tr><td>" . strip_tags ($question) . "</td><td><form action=\"admin.php?" . strip_tags(SID) . "\" method=\"POST\"><input type=\"hidden\" name=\"question\" value=\"$id\" /><input class=\"button font\" name=\"action\" type=\"submit\" value=\"Edit\" /><input class=\"button font\" name=\"action\" type=\"submit\" value=\"Remove\" /></form></td></tr>";
                        }
                        $status = "Found " . $db->resultNumRows() . " questions.";
                    } else
                        $content .= "<tr><td class=\"center\" colspan=\"2\">There have been no questions added to this quiz yet.</td></tr>";

                } else if(isset($_POST['question'])) {

                    if (isset ($_POST['add']) || isset ($_POST['sub']))
                    {
                        $id = $_POST['qId'];
                        $title = $_POST['question'];
                        $reason = $_POST['reason'];
                        $choiceArray = $_POST['choice'];
                        $correctIndex = $_POST['correct'];
                        addSubChoices ($choiceArray, $correctIndex, $_POST['add'], $_POST['sub']);
                    }
                    else
                    {
                        $id = $_POST['question'];
                        $db->doQuery("SELECT question,reason FROM nq_Questions WHERE id='$id'");
                        $question= $db->nextAssoc();
                        $title = $question['question'];
                        $reason = $question['reason'];

                        $db->doQuery("SELECT question,choice,answer FROM nq_Choices WHERE question='$id'");

                        $i = 1;
                        while($tempC = $db->nextAssoc())
                        {    // For all choices in the question.
                            $choiceArray[$i] = $tempC['choice'];
                            if ($tempC['answer'] == 1)
                                $correctIndex = $i;
                            $i++;
                        }
                    }

                    $content = generateEditQuestionForm ($id, $title, $reason, $choiceArray, $correctIndex, "Editing Question :.", "Save Question");

                } else {
                    $content .= "<tr><td class=\"head\">Warning:</td></tr><tr><td>It appears NueQuiz cannot find a specified item to edit. This may have been caused by a software error or melicious use of the application.</td></tr>";
                    $status = "Error: Cannot edit. Item id or item type not specified.";
                }
                $tab = 1;
                break;

            /*--------------------------------------------------*/
            case "Remove":
                if(isset($_POST['quiz'])) {
                    $id = $_POST['quiz'];
                    $content .= "<tr><td class=\"head\">Confirmation :.</td></tr><tr><td colspan=\"2\">Warning! This will remove all questions associated with this quiz.</td></tr></tr><tr><td>Are you sure you want to continue?</td><td><input type=\"hidden\" name=\"quiz\" value=\"$id\" /><input class=\"button small\" name=\"action\" type=\"submit\" value=\"Yes\" /><input class=\"button small\" name=\"action\" type=\"submit\" value=\"No\" /></td></tr>";
                } else if(isset($_POST['question'])) {
                    $id = $_POST['question'];
                    $content .= "<tr><td class=\"head\">Confirmation :.</td></tr><tr><td colspan=\"2\">Warning! This will remove all choices associated with this question.</td></tr></tr><tr><td>Are you sure you want to continue?</td><td><input type=\"hidden\" name=\"question\" value=\"$id\" /><input class=\"button small\" name=\"action\" type=\"submit\" value=\"Yes\" /><input class=\"button small\" name=\"action\" type=\"submit\" value=\"No\" /></td></tr>";
                } else { // Should never get here but just in case.
                    $content .= "<tr><td class=\"head\">Warning:</td></tr><tr><td>It appears NueQuiz cannot remove the specified item. This may have been caused by a software error or melicious use of the application. </td></tr>";
                    $status = "Error: Cannot remove. Item is not properly specified.";
                }
                $tab = 1;
                break;

            /*--------------------------------------------------*/
            case "Yes":
                $qo = new QuizOperations();
                if(isset($_POST['quiz'])) {
                    $qo->removeQuiz($_POST['quiz']);
                } else if(isset($_POST['question'])) {
                    $db->doQuery("SELECT quiz FROM nq_Questions where id='" . $_POST['question'] . "'");
                    if($db->resultNumRows() > 0)
                    {
                        $tempQ = $db->nextAssoc();
                        $redirect = "&action=Edit&quiz=" . $tempQ['quiz'];
                    }
                    else
                    {
                        $redirect = "&action=mQuizzes";
                    }
                    $qo->removeQuestion($_POST['question']);
                }
                saveMessage ("Message", "Delete operation successful.");
            case "No":

                if (isset ($_POST['question']))
                {
                    if (!isset ($redirect))
                    {
                        $db->doQuery("SELECT quiz FROM nq_Questions where id='" . $_POST['question'] . "'");
                        if($db->resultNumRows() > 0)
                        {
                            $tempQ = $db->nextAssoc();
                            $redirect = "&action=Edit&quiz=" . $tempQ['quiz'];
                        }
                        else
                        {
                            $redirect = "&action=mQuizzes";
                        }
                    }
                    $url = "Location: admin.php?" . strip_tags(SID) . $redirect;
                }
                else
                    $url = "Location: admin.php?" . strip_tags(SID) . "&action=mQuizzes";

                header("$url");
            break;

            /*--------------------------------------------------*/
            case "Login":

                $_SESSION['password'] = md5($_POST['password']);

            /*--------------------------------------------------*/
            case "Main":
                $welcomeMsg = "<br>Thank you for trying out NueQuiz Pro Lite beta release!<br><br>
                        Before we can release the final version, we want to make sure that
                        users have the opportunity to try out all the
                        features in order to make sure that any bugs present are found, helping
                        us greatly in being able to release a higher quality product.<br><br>
                        Please send any comments, suggestions and descriptions of any bugs you
                        may find to <a class='welcome' href='mailto:nqpro@nuedream.com'>nqpro@nuedream.com</a>.<br><br>
                        We hope you enjoy our new product. Don't forget to check the NueQuiz Pro
                        Homepage (<a class='welcome' href='www.nuedream.com/nuequizpro</a>" target="_blank">http://www.nuedream.com/nuequizpro'>www.nuedream.com/nuequizpro</a>)
                        regularly for new NueQuiz versions and other updates.<br><br>
                        - NueQuiz Pro Team -<br><br>";

                $content .= "<tr><td class=\"head\">Welcome to NueQuiz</td></tr><tr><td>$welcomeMsg</td></tr>";
                $status = "Login successful.";
                break;

            /*--------------------------------------------------*/
            case "mLogout":
                $_SESSION = array();
                session_destroy();
                header("Location: admin.php");
                break;

            /*--------------------------------------------------*/
            default:
                $content .= "<tr><td class=\"head\">Error:</td></tr><tr><td>Invalid action specified. You may have mistyped the URL. You may return to the <a href=\"admin.php?" . strip_tags (SID) . "\">admin script</a> and try again.</td></tr>";
                $status = "Error: Invalid action.";
                break;
        }

        displayHead($tab);
        $msgArray = getMessage ();
        if (is_array ($msgArray))
        {
            displayMessageBox ($msgArray['title'], $msgArray['message']);
        }
        echo("$content");
        displayFoot($status, round( (microtime(true) - $timeStart),8 ) );

    } else {

        if(isset($_POST['password']))                                                    // Incorrect Password.
            $status = "ERROR: Incorrect Password";

        ?>
            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

            <html>
            <head>
                <title><? echo CFG_PAGE_TITLE; ?></title>
                <link rel="stylesheet" type="text/css" href='<? echo CFG_STYLE_PATH; ?>style.css' />
            </head>

            <body>

                <table class="font">
                    <tr>
                        <th width="25%" class="head">&nbsp;</th>
                        <th width="25%" class="head">&nbsp;</th>
                        <th width="25%" class="head">&nbsp;</th>
                        <th width="25%" class="selected">Login</th>
                    </tr>
                    <tr>
                        <th colspan="4">
                            <?
                            echo "<form action=\"admin.php?" . strip_tags (SID) . "\" method=\"POST\">";
                            ?>
                                <input type="hidden" name="action" value="Login" />
                                <table class="inner font left login">
                                    <tr>
                                        <td class="head" colspan="2">Authentication</td>
                                    </tr>
                                    <tr>
                                        <td class="right">Password:</td>
                                        <td colspan="3"><label valign="center"><input class="textBox medium" name="password" type="password" /><input class="button medium" value="Login" type="submit" /></label></td>
                                    </tr>

        <?

        displayFoot($status, round( (microtime(true) - $timeStart),8 ) );
    }

/*--------------------------------------------------*
* displayHead()
* - Displays header information.
*/

    function displayHead($selected) {

        ?>
            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

            <html>
            <head>
                <title><? echo CFG_PAGE_TITLE; ?></title>
                <link rel="stylesheet" type="text/css" href='<? echo CFG_STYLE_PATH; ?>style.css' />
            </head>

            <body>

                <table class="font">
                    <tr>
                        <th width="25%" <? if($selected != 1) echo("class=\"head\""); else echo("class=\"selected\"");?>><a href="admin.php?action=mQuizzes&<? echo strip_tags (SID); ?>">Quizzes</a></th>
                        <th width="25%" <? if($selected != 2) echo("class=\"head\""); else echo("class=\"selected\"");?>><a href="admin.php?action=mConfig&<? echo strip_tags (SID); ?>">Config</a></th>
                        <th width="25%" <? if($selected != 3) echo("class=\"head\""); else echo("class=\"selected\"");?>><a href="admin.php?action=mStats&<? echo strip_tags (SID); ?>">Stats</a></th>
                        <th width="25%" <? if($selected != 4) echo("class=\"head\""); else echo("class=\"selected\"");?>><a href="admin.php?action=mLogout&<? echo strip_tags (SID); ?>">Logout</a></th>
                    </tr>
                    <tr>
                        <th colspan="4"><?
                            echo "<form action=\"admin.php?" . strip_tags(SID) . "\" method=\"POST\">";
                                ?>
                                <table class="inner font left wide">
        <?
    }

/*--------------------------------------------------*
* displayFoot()
* - Displays footer information.
*/

    function displayFoot($status, $time) {
        ?>
                            </table>
                        </form>
                    </th>
                </tr>
                <tr>
                    <th class="foot smallFnt left" colspan="2"><? echo $status ?></th>
                    <th class="foot smallFnt right" colspan="2"> Time: <? echo $time ?> sec.</th>
                </tr>
            </table>

        </body>
        </html>
        <?
    }

    function addSubChoices (&$choiceArray, &$correctIndex, $addArray, $subArray)
    {
        if (is_array ($addArray))
        {
            list ($key) = each ($addArray);
            array_splice ($choiceArray, $key, 0, "");
            if ($key < $correctIndex)
                $correctIndex++;
        }
        elseif (is_array ($subArray))
        {
            list ($key) = each ($subArray);
            array_splice ($choiceArray, $key - 1, 1);
            if ($key < $correctIndex)
                $correctIndex--;
            if ($correctIndex > count ($choiceArray))
                $correctIndex = count ($choiceArray);
        }
        else
        {
            return FALSE;
        }
        array_unshift ($choiceArray, "");
        unset ($choiceArray[0]);
        return TRUE;

    }

    function generateEditQuestionForm ($quizID, $question, $reason, $choiceArray, $correctIndex, $title, $action)
    {
        $numChoices = count ($choiceArray);
        // Must have at least one choice
        if ($numChoices < 1)
        {
            $choiceArray = Array ("");
            $numChoices = 1;
        }

        $content = "<tr>
                    <td class=\"head\" colspan=\"4\">$title</td>
                </tr>
                <tr>
                    <td class=\"right\">Question:</td>
                    <td colspan=\"3\"><textarea rows=\"2\" cols=\"20\" name=\"question\">" . stripslashes ($question) . "</textarea></td>
                </tr>";

        $content .= "<tr>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td class=\"left\">Correct</td>
            <td><input class=\"button font\" type=\"submit\" name=\"add[0]\" value=\"+\"/></td>
        </tr>";

        for($i = 1; $i <= $numChoices; $i++)
        {
                $content .= "<tr>
                    <td class=\"right\">Choice $i:</td>
                    <td><input class=\"textBox\" name=\"choice[$i]\" value=\"" . stripslashes ($choiceArray[$i]) . "\" type=\"text\" /></td>
                    <td class=\"left\"><input type=\"radio\" name=\"correct\" value=\"$i\" ";
                if ($i == $correctIndex)
                    $content .= " checked";

                $content .= " /></td><td class=\"left\"><input class=\"button font\" type=\"submit\" name=\"add[$i]\" value=\"+\"/>";

                if ($numChoices > 1)
                    $content .= "<input class=\"button font\" type=\"submit\" name=\"sub[$i]\" value=\"-\"/>";

                $content .= "</td></tr>";
        }

        $content .= "<tr>
                    <td class=\"right\">Answer Explanation:</td>
                    <td colspan=\"3\"><textarea rows=\"4\" cols=\"20\" name=\"reason\">" . stripslashes ($reason) . "</textarea></td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td colspan=\"3\"><input type=\"hidden\" name=\"qId\" value=\"$quizID\" /><input type=\"hidden\" name=\"action\" value=\"$action\" /><input class=\"button font\" type=\"submit\" value=\"$action\" /></td>
                </tr>";

        return $content;
    }

    function displayMessageBox ($title, $message)
    {
        ?>
                <tr>
                    <td class="head sepa"><?php echo $title; ?> :.</td>
                </tr>
                <tr>
                    <td colspan="2"><?php echo $message; ?></td>
                </tr>
            </table>
            <table class="inner font left wide">
        <?php
    }

    function saveMessage ($title, $message)
    {
        $msgArray = Array ('title' => $title, 'message' => $message, 'sent' => 1);
        $_SESSION['_msg'] = $msgArray;
    }

    function getMessage ()
    {
        $msgArray = $_SESSION['_msg'];
        if ($msgArray['sent'] == 1)
        {
            unset ($msgArray['sent']);
            $_SESSION['_msg'] = $msgArray;
            return;
        }
        unset ($_SESSION['_msg']);
        return $msgArray;
    }

        ?>


samt denne, som indeholder funktionerne:

<?php

require_once( "Database.class.php" );
require_once( "Error.class.php" );
require_once( "config.php" );

define('CFG_FIELD_HOME_NAME',"home_name");
define('CFG_FIELD_HOME_URL',"home_url");
define('CFG_FIELD_QUIZ_URL',"quiz_url");
define('CFG_FIELD_PASSWORD',"password");

class QuizOperations {
   
    var $db;
   
    function QuizOperations( )
    {
        $this->db = new Database( CFG_DB_SERVER, CFG_DB_USERNAME, CFG_DB_PASSWORD, CFG_DB_NAME );
    }
   
    /*--------------------------------------------------------------*
    | Adding Functions                                                |
    *--------------------------------------------------------------*
    | These functions are used to add quiz elements such as         |
    | quizzes, questions and choices.                                |
    *--------------------------------------------------------------*/
   
    function addQuiz( $quizName, $intro = "", $qPerPage = 1, $shuffleChoices = false, $shuffleQuestions = false, $qimage )
    {
        $this->db->autoErrEnable( ERR_LEVEL_FATAL );
       
        if( !$shuffleQuestions )
            $shuffleQuestions = 0;
        else $shuffleQuestions = 1;
        if( !$shuffleChoices )
            $shuffleChoices = 0;
        else $shuffleChoices = 1;
       
        if( !is_numeric( $qPerPage ) || intval( $qPerPage ) != $qPerPage )
            new Error( "NQ-AQZ-001", "Attempted to add quiz with '$qPerPage' questions per page: this is NOT an integer", ERR_LEVEL_FATAL, true );
       
        $quizName = mysql_escape_string( $quizName );
        $intro = mysql_escape_string( $intro );
       
        $query =  "INSERT INTO nq_Quizzes ( name, intro, per_page, shuffle_choices, shuffle_questions, q_image ) "
                . "VALUES ( '$quizName', '$intro', '$qPerPage', '$shuffleChoices', '$shuffleQuestions', '$qimage' )";
        echo mysql_error();
        $this->db->autoErrDisable( );
        if( !$this->db->doQuery( $query ) )
            return false;        // Could not insert quiz as requested
        $this->db->autoErrEnable( ERR_LEVEL_FATAL );
       
        return $this->db->lastInsertedIndex( );
    }
   
    function addQuestion( $quizID, $question, $choices = array(), $ansPosition = 1, $explanation = "" )
    {               
        $this->db->autoErrEnable( ERR_LEVEL_FATAL );
       
        if( !is_numeric( $quizID ) || intval( $quizID ) != $quizID )
            new Error( "NQ-AQN-001", "Attempted to add question to quiz number '$quizID', which is NOT an integer (or 0; invalid quiz id).", ERR_LEVEL_FATAL, true );
       
        $question = mysql_escape_string( $question );
        $explanation = mysql_escape_string( $explanation );
       
        $query =  "INSERT INTO nq_Questions ( question , reason , quiz ) "
                . "VALUES ( '$question', '$explanation', '$quizID' )";
       
        $this->db->autoErrDisable( );
       
        if( !$this->db->doQuery( $query ) )
            return false;        // Failed to insert question as requested
       
        $this->db->autoErrEnable( ERR_LEVEL_FATAL );
       
        $questionID = $this->db->lastInsertedIndex( );
       
        if( is_array( $choices ) )
            $this->addChoices( $questionID, $choices, $ansPosition );
           
        return $questionID;
    }
   
    function addChoices( $questionID, $choices, $ansPosition )
    {
        $i=1;
        foreach( $choices as $choice )
            $this->addChoice( $questionID, $choice, (($i++)==$ansPosition) );
    }
   
    function addChoice( $questionID, $choice, $isAnswer = 0, $position = NULL )
    {
        $this->db->autoErrEnable( ERR_LEVEL_FATAL );
       
        if(get_magic_quotes_gpc())
            $choice = stripslashes( $choice );
       
        if( !$choice )
            return;
       
        if( !is_numeric( $questionID ) || intval( $questionID ) != $questionID )
            new Error( "NQ-ACH-001", "Attempted to add choices to question number '$questionID', which is NOT an integer.", ERR_LEVEL_FATAL, true );
       
        $choice = mysql_escape_string( $choice );
       
        $posField = "";
        $posValue = "";
       
        if( is_numeric( $position ) && intval( $position ) == $position )
        {
            $posField = " position,";
            $posValue = " '$position',";
            $this->_shiftChoicesUp( $questionID, $position );
        }
       
        $query =  "INSERT INTO nq_Choices ( question, choice," . $posField . " answer ) "
                . "VALUES ( $questionID, '$choice'," . $posValue . " 0 )";
       
        $this->db->autoErrDisable( );
       
        if( !$this->db->doQuery( $query ) )
            return false;        // Failed to insert choice as requested
           
        $this->db->autoErrEnable( ERR_LEVEL_FATAL );
       
        if( $isAnswer )
            if( !$posField )    // Did check on $position argument succeed?
                if( $insertedPos = $this->db->lastInsertedIndex() )
                    $this->updateQuestionAns( $questionID, $insertedPos );
                else return false;    // Choice was not inserted
            else
                $this->updateQuestionAns( $questionID, $position );
                           
        if( !( $returnVal = $this->db->lastInsertedIndex() ) )
            $returnVal = true;
        return $returnVal;
    }
   
    /*--------------------------------------------------------------*
    | Updating Functions                                            |
    *--------------------------------------------------------------*
    | Used to change existing quiz elements such as quizzes,         |
    | questions and choices.
    *--------------------------------------------------------------*/
   
    function updateQuiz( $id, $newName, $newIntro = NULL, $qPerPage = NULL,  $newimage, $shuffleC = NULL, $shuffleQ = NULL, )
    {
        $query = "UPDATE nq_Quizzes SET";
       
        $bareLength = strlen( $query );
       
        if( is_string( $newName ) && strlen( $newName ) > 0 )
            $query .= " name='" . mysql_escape_string( $newName ) . "',";
if( is_string( $newimage ) && strlen( $newimage ) > 0 )
            $query .= " q_image='" . mysql_escape_string( $newimage ) . "',";
        if( is_string( $newIntro ) )
            $query .= " intro='" . mysql_escape_string( $newIntro ) . "',";
        if( is_numeric( $qPerPage ) && $qPerPage > 0 )
            $query .= " per_page=$qPerPage,";
        if( $shuffleC === false || $shuffleC === 0 || $shuffleC === "0" )
            $query .= " shuffle_choices=0,";
        else if( $shuffleC === true || $shuffleC === 1 || $shuffleC === "1" )
            $query .= " shuffle_choices=1,";
        if( $shuffleQ === false || $shuffleQ === 0 || $shuffleQ === "0" )
            $query .= " shuffle_questions=0,";
        else if( $shuffleQ === true || $shuffleQ === 1 || $shuffleQ === "1" )
            $query .= " shuffle_questions=1,";
       
        if( strlen( $query ) == $bareLength )
            return false;        // No fields were specified for update.
       
        $query = substr( $query, 0, -1 );    // Take off the last comma
       
        $query .= " WHERE id=$id LIMIT 1";
       
        $this->db->autoErrDisable( );
        if( !$this->db->doQuery( $query ) )
            return false;        // Quiz could not be updated as requested (query failed)
        $this->db->autoErrEnable( ERR_LEVEL_FATAL );
       
        return true;
    }
   
    /**
    * Since only one choice can be the answer in THIS quiz, this method
    * guarantees that when u update which choice is the answer, that is
    * the ONLY answer.
    */
    function updateQuestionAns( $questionID, $answerPos )
    {
        if( !is_numeric( $answerPos ) || intval( $answerPos ) != $answerPos )
            new Error( "NQ-UQA-001", "The answer position '$answerPos' is not a valid integer..", ERR_LEVEL_FATAL, true );
       
        $this->db->doQuery( "SELECT * FROM nq_Choices WHERE question=$questionID AND position=$answerPos" );
       
        if( $this->db->resultIsEmpty() )
            return false;    // No Choice exists at this answer position..
           
        $this->db->doQuery( "UPDATE nq_Choices SET answer=0 WHERE question=$questionID" );
        $this->db->doQuery( "UPDATE nq_Choices SET answer=1 WHERE question=$questionID AND position=$answerPos LIMIT 1" );
       
        return true;
    }
   
    function updateQuestion( $id, $newQuestion, $newReason = NULL, $newQuiz = NULL )
    {
        $query = "UPDATE nq_Questions SET";
       
        $bareLength = strlen( $query );
       
        if( is_string( $newQuestion ) && strlen( $newQuestion ) > 0 )
            $query .= " question='" . mysql_escape_string( $newQuestion ) . "',";
        if( is_string( $newReason ) )
            $query .= " reason='" . mysql_escape_string( $newReason ) . "',";
        if( is_numeric( $newQuiz ) && intval( $newQuiz ) > 0 )
            $query .= " quiz=$newQuiz,";
       
        if( strlen( $query ) == $bareLength )
            return false;        // No fields were specified for update.
       
        $query = substr( $query, 0, -1 );    // Take off the last comma
       
        $query .= " WHERE id=$id LIMIT 1";
       
        $this->db->autoErrDisable( );
        if( !$this->db->doQuery( $query ) )
            return false;        // Quiz could not be updated as requested (query failed)
        $this->db->autoErrEnable( ERR_LEVEL_FATAL );
       
        return true;
    }
   
    function updateChoice( $questionID, $position, $newChoice = NULL, $answer = NULL, $newPosition = NULL )
    {
        // If answer is to be changed, change it before updating choice
        if( $answer )
            if( !$this->updateQuestionAns( $questionID, $position ) )
                return false;        // Could not set answer
       
        $query = "UPDATE nq_Choices SET";
       
        $bareLength = strlen( $query );
       
        if( is_string( $newChoice ) && strlen( $newChoice ) > 0 )
            $query .= " choice='" . mysql_escape_string( $newChoice ) . "',";
        if( is_numeric( $newPosition ) && intval( $newPosition ) > 0 )
            $query .= " position=$newPosition,";
       
        if( strlen( $query ) == $bareLength )
        {
            if( !$answer )
                return false;        // No fields were specified for update.
            return true;
        }
       
        $query = substr( $query, 0, -1 );    // Take off the last comma
        $query .= " WHERE question=$questionID AND position=$position LIMIT 1";
       
        $this->db->autoErrDisable( );
        if( !$this->db->doQuery( $query ) )
            return false;        // Quiz could not be updated as requested (query failed)
        $this->db->autoErrEnable( ERR_LEVEL_FATAL );
       
        return true;
    }

    /*--------------------------------------------------------------*
    | Removing Functions                                            |
    *--------------------------------------------------------------*
    | Used to remove quiz elements such as quizzes, questions        |
    | and choices.                                                    |
    *--------------------------------------------------------------*/
   
    function removeQuiz( $quizId, $removeQuestions = true )
    {
        $query = "DELETE FROM nq_Quizzes WHERE id=$quizId LIMIT 1";
       
        $this->db->doQuery( $query );
       
        if( $removeQuestions )
            $this->removeAllQuestions( $quizId );
       
        return true;
    }
   
    function removeAllQuestions( $quizID )
    {
        $this->db->autoErrEnable( ERR_LEVEL_FATAL );
       
        $query = "SELECT id FROM nq_Questions WHERE quiz=$quizID";
        $this->db->doQuery( $query );
       
        $removedCount = 0;
       
        while( $id = $this->db->nextAssoc( ) )
        {
            $this->removeQuestion( $id['id'] );
            $removedCount++;
        }
       
        return $removedCount;
    }
   
    function removeQuestion( $questionId )
    {
        $query = "DELETE FROM nq_Questions WHERE id=$questionId LIMIT 1";
       
        $this->db->doQuery( $query );
       
        $this->removeAllChoices( $questionId );
       
        return true;
    }
   
    function removeChoice( $questionID, $position )
    {
        $query = "DELETE FROM nq_Choices WHERE question='$questionID' AND position='$position' LIMIT 1";
       
        $this->db->doQuery( $query );
       
        return $this->compactChoices( $questionID );
    }
   
    function removeAllChoices( $questionID )
    {
        $query = "DELETE FROM nq_Choices WHERE question=$questionID";
       
        $this->db->doQuery( $query );
       
        return $this->db->numAffectedRows( );
    }
   
    /*--------------------------------------------------------------*
    | Choice Ordering Functions                                    |
    *--------------------------------------------------------------*
    | Used to manipulate the order of choices for a question.        |
    *--------------------------------------------------------------*/
   
    function reorderChoices( $questionID, $newOrder )
    {
        $this->db->autoErrEnable( ERR_LEVEL_FATAL );
       
        $this->compactChoices( $questionID );
       
        echo "Compacting process completed..<br>";
       
        if( !is_array( $newOrder ) )
            return false;    // Argument is NOT an array!!
       
        $numChoices = $this->countChoices( $questionID );
       
        echo "Counted $numChoices choices in question $questionID..<br>";
       
        if( count( $newOrder ) != $numChoices )
            return false;    // New ordering size doesn't match the number of choices in this question!
       
        if( !$this->validateOrdering( $newOrder ) )
            return false;
       
        echo "New ordering accepted, and equal to number of choices..<br>";
       
        $this->_shiftChoicesUp( $questionID, 1, $numChoices );    // Push all choices' positions out of current range of positions
       
        $query = "SELECT choice, position, answer FROM nq_Choices WHERE question=$questionID ORDER BY position ASC";
       
        $this->db->doQuery( $query );
       
        for($i=0; $choice = $this->db->nextAssoc( ); $i++ )
            if( !$this->updateChoice( $questionID, $choice['position'], NULL, NULL, $newOrder[$i] ) )
                return false;
       
        return true;
    }
   
    function countChoices( $questionID )
    {
        $this->db->autoErrEnable( ERR_LEVEL_FATAL );
       
        $query = "SELECT * FROM nq_Choices WHERE question=$questionID";
        $this->db->doQuery( $query );
       
        return $this->db->resultNumRows( );
    }
   
    function compactChoices( $questionID )
    {
        $query = "SELECT * FROM nq_Choices WHERE question=$questionID ORDER BY position ASC";
       
        $this->db->doQuery( $query );
       
        for( $i=1; $choice = $this->db->nextAssoc( ); $i++ )
            if( !$this->updateChoice( $questionID, $choice['position'],NULL,NULL,$i ) )
                return false;
       
        return true;
    }
   
    function _shiftChoicesUp( $questionID, $startingAtPos = 1, $byAmount = 1 )
    {
        $query = "SELECT position FROM nq_Choices WHERE question='$questionID' AND position >= '$startingAtPos' ORDER BY position DESC";
       
        $this->db->doQuery( $query );
       
        while( $pos = $this->db->nextAssoc( ) )
            if( !$this->updateChoice( $questionID, $pos['position'], NULL, NULL, ( $pos['position']+$byAmount ) ) )
                return false;
       
        return true;
    }
   
    function validateOrdering( $ordering )
    {
        sort( $ordering );
        reset( $ordering );
       
        $i=1;
        foreach( $ordering as $index )
            if( $index != $i++ )
                return false;
       
        return true;
    }
   
    /*--------------------------------------------------------------*
    | Duplicating Functions                                        |
    *--------------------------------------------------------------*
    | Used to duplicate quiz elements such as quizzes, questions     |
    | and choices.                                                    |
    *--------------------------------------------------------------*/
   
    // NOTHING BEYOND THIS POINT HAS BEEN TESTED YET!!
   
    function duplicateQuiz( $id, $newName, $dupQuestions = true )
    {
        $query  = "INSERT INTO nq_Quizzes ( name, intro, per_page, shuffle_choices, shuffle_questions ) "
                . "SELECT '$newName', intro, per_page, shuffle_choices, shuffle_questions FROM nq_Quizzes WHERE id=$id LIMIT 1";
       
        $this->db->autoErrDisable( );
        if( !$this->db->doQuery( $query ) )
            return false;        // Quiz NOT copied successfully (Remember Name must be UNIQUE!)
        $this->db->autoErrEnable( ERR_LEVEL_FATAL );
       
        if( !( $newQuizID = $this->db->lastInsertedIndex( ) ) )
            return false;
       
        if( $dupQuestions )
            if( !duplicateAllQuestions( $id, $newQuizID ) )
                return false;
       
        return true;
    }
   
    function duplicateAllQuestions( $fromQuizID, $toQuizID = NULL )
    {
        if( !is_numeric( $toQuizID ) || $toQuizID < 1 )
            $toQuizID = $fromQuizID;
       
        $query = "SELECT id FROM nq_Questions WHERE quiz=$fromQuizID";
       
        $this->db->doQuery( $query );
       
        while( $question = $this->db->nextAssoc( ) )
            if( !$this->duplicateQuestion( $question['id'],$toQuizID ) )
                return false;
       
        return true;
    }
   
    function duplicateQuestion( $questionID, $toQuizID )
    {
        $query =  "INSERT INTO nq_Questions ( question, reason, quiz ) "
                . "SELECT question, reason, '$toQuizID' FROM nq_Questions WHERE id=$questionID LIMIT 1";
               
        $this->db->autoErrDisable( );
        if( !$this->db->doQuery( $query ) )
            return false;        // Choice was not transfered successfully..
        $this->db->autoErrEnable( ERR_LEVEL_FATAL );
       
        $newQID = false;
       
        if( $newQID = $this->db->lastInsertedIndex( ) )
            $this->duplicateAllChoices( $questionID, $newQID );
       
        return $newQID;
    }
   
    function duplicateAllChoices( $fromQuestion, $toQuestion )
    {
        if( $fromQuestion == $toQuestion || is_numeric( $fromQuestion ) || $fromQuestion < 1 )
            return false;
       
        $query =  "INSERT INTO nq_Choices ( question, choice, position, answer ) "
                . "SELECT '$toQuestion', choice, position, answer FROM nq_Choices WHERE question=$fromQuestion";
       
        $this->db->autoErrDisable( );
        if( !$this->db->doQuery( $query ) )
            return false;        // Choices were not transferred properly..
        $this->db->autoErrEnable( ERR_LEVEL_FATAL );
       
        return true;
    }
   
    /*--------------------------------------------------------------*
    | Global Config Functions                                        |
    *--------------------------------------------------------------*
    | Used to access and set specifig config values stored in the    |
    | NueQuiz database                                                |
    *--------------------------------------------------------------*/
   
    function getHomeName( )
    {
        $this->db->doQuery( "SELECT value FROM nq_Config WHERE config='".CFG_FIELD_HOME_NAME."' LIMIT 1" );
        $row = $this->db->nextAssoc( );
        return $row['value'];
    }
   
    function getHomeURL( )
    {
        $this->db->doQuery( "SELECT value FROM nq_Config WHERE config='".CFG_FIELD_HOME_URL."' LIMIT 1" );
        $row = $this->db->nextAssoc( );
        return $row['value'];
    }
   
    function getQuizURL( )
    {
        $this->db->doQuery( "SELECT value FROM nq_Config WHERE config='".CFG_FIELD_QUIZ_URL."' LIMIT 1" );
        $row = $this->db->nextAssoc( );
        return $row['value'];
    }
   
    function getPassword( )
    {
        $this->db->doQuery( "SELECT value FROM nq_Config WHERE config='".CFG_FIELD_PASSWORD."' LIMIT 1" );
        $row = $this->db->nextAssoc( );
        return $row['value'];
    }
   
    function setHomeName( $newValue )
    {
        $this->db->autoErrEnable( ERR_LEVEL_FATAL );
       
        if( !is_string( $newValue ) || strlen( $newValue ) == 0 || strlen( $newValue ) > 255 )
            return false;
       
        $this->db->doQuery( "DELETE FROM nq_Config WHERE config='".CFG_FIELD_HOME_NAME."' LIMIT 1" );
        $this->db->doQuery( "INSERT INTO nq_Config(config,value) VALUES('".CFG_FIELD_HOME_NAME."','$newValue')" );
        return true;
    }
   
    function setHomeURL( $newValue )
    {
        $this->db->autoErrEnable( ERR_LEVEL_FATAL );
       
        /*&& strlen( $newValue ) > 0 && strlen( $newValue ) <= 255*/
       
        if( !is_string( $newValue ) || strlen( $newValue ) == 0 || strlen( $newValue ) > 255 )
            return false;
       
        $this->db->doQuery( "DELETE FROM nq_Config WHERE config='".CFG_FIELD_HOME_URL."' LIMIT 1" );
        $this->db->doQuery( "INSERT INTO nq_Config(config,value) VALUES('".CFG_FIELD_HOME_URL."','$newValue')" );
        return true;
    }
   
    function setQuizURL( $newValue )
    {
        $this->db->autoErrEnable( ERR_LEVEL_FATAL );
       
        if( !is_string( $newValue ) || strlen( $newValue ) == 0 || strlen( $newValue ) > 255 )
            return false;
       
        $this->db->doQuery( "DELETE FROM nq_Config WHERE config='".CFG_FIELD_QUIZ_URL."' LIMIT 1" );
        $this->db->doQuery( "INSERT INTO nq_Config(config,value) VALUES('".CFG_FIELD_QUIZ_URL."','$newValue')" );
        return true;
    }
   
    function setPassword( $newValue )
    {
        $this->db->autoErrEnable( ERR_LEVEL_FATAL );
       
        if( !is_string( $newValue ) || strlen( $newValue ) > 255 )
            return false;
       
        $this->db->doQuery( "DELETE FROM nq_Config WHERE config='".CFG_FIELD_PASSWORD."' LIMIT 1" );
        $this->db->doQuery( "INSERT INTO nq_Config(config,value) VALUES('".CFG_FIELD_PASSWORD."','$newValue')" );
        return true;
    }
   
    function addStatistic( $quizID, $numQuestions, $numAnswered, $numCorrect )
    {
        if( !$numQuestions || !$numAnswered )
            return true;    // Do nothing in these cases.
       
        $query = "INSERT INTO nq_Stats( quiz,date,num_questions,num_answered,num_correct ) " .
                "VALUES( $quizID, CURDATE(), $numQuestions, $numAnswered, $numCorrect )";
       
        $this->db->doQuery( $query );
       
        if( $this->db->numAffectedRows() == 0 )
            return false;
       
        return true;
    }
}
?>
Avatar billede jaw Nybegynder
06. januar 2006 - 20:53 #3
Hold da op en fil !! Men jeg har rettet lidt, her er mine rettelser:

Linie 557: Homepage (<a class='welcome' href='www.nuedream.com/nuequizpro target='_blank'>www.nuedream.com/nuequizpro</a>" target="_blank">http://www.nuedream.com/nuequizpro'>www.nuedream.com/nuequizpro</a>)
Linie 951:
Avatar billede jaw Nybegynder
06. januar 2006 - 20:53 #4
Hov:

Linie 951: function updateQuiz( $id, $newName, $newIntro = NULL, $qPerPage = NULL,  $newimage, $shuffleC = NULL, $shuffleQ = NULL )
Avatar billede jan2001 Nybegynder
06. januar 2006 - 21:12 #5
Ha! et enkelt lille komma. Nå men jeg kan se i databasen at scriptet gemmer det indtastede i feltet. Men hvorfor ses det ikke i input feltet. De andre felter udfyldes af det der er i databasen?
Avatar billede jan2001 Nybegynder
06. januar 2006 - 21:16 #6
vent! tror jeg har fundet fejlen. kigger lige lidt mere på det.
Avatar billede jan2001 Nybegynder
06. januar 2006 - 21:50 #7
ok, på selve siden, som viser quizzen, skal jeg få det til at hente billedet eller bare det som er i databasen. Iøvrigt ligger billedet i en anden tabel end den med questions. Kan man hente fra fra flere tabeller i samtidigt i samme SQL-sætning?
Der bliver brugt følgende tre scripts til at vise quizzen:

page.class.php
<?php

/*
* Coding formatted for standard 4-space tabs.
*/
require_once( "Database.class.php" );
require_once( "Question.class.php" );
require_once( "Page.display.php" );
require_once( "config.php" );

class Page {
   
    var $quiz;
    var $pageNum;
    var $db;
    var $questions;
    var $qPerPage;
    var $shuffleQ;
    var $shuffleC;
   
    function Page( $quizID, $pageNum, $userAnswers )
    {
        $this->quiz = $quizID;
        $this->pageNum = $pageNum;
        $this->answers = $userAnswers;
        $this->questions = array( );
       
        $this->db = new Database( CFG_DB_SERVER, CFG_DB_USERNAME, CFG_DB_PASSWORD, CFG_DB_NAME );
       
        if( is_numeric( $this->quiz ) && intval( $this->quiz ) == $this->quiz && $this->quiz > 0 )
        {
            $this->_getQuizConfigs( );
            if( $this->qPerPage == 0 )
            {
                $this->db->doQuery( "SELECT COUNT(*) AS count FROM nq_Questions WHERE quiz=" . $this->quiz );
                $resRow = $this->db->nextAssoc( );
                $this->qPerPage = $resRow['count'];
            }
            $this->_fetchQuestions( );
        }
    }
   
    function display( )
    {
        $this->_generatePage( );
    }
   
    function _fetchQuestions( )
    {
        $query = "SELECT id,q.question, AS q, reason " .
                "FROM nq_Questions q, nq_Choices c " .
                "WHERE id=c.question AND quiz=" . $this->quiz . " " .
                "GROUP BY id,q.question,reason HAVING COUNT(c.position) > 1";
               
        if( $this->shuffleQ )
        {
            $numSessionID = preg_replace( "[\D]", "", session_id() );
            $randSeed = substr( $numSessionID, strlen($numSessionID)-6, 3 );
            $randSeed = $randSeed + ( substr( "$this->quiz", strlen( $this->quiz ) - 1 ) * 300 );
            $query = $query . " ORDER BY RAND(" . $randSeed * 10000000 . ")";
        }
        $this->db->doQuery( $query );
    }
   
    function _makeIntroPage( )
    {
        $query = "SELECT name,intro FROM nq_Quizzes WHERE id=" . $this->quiz . " LIMIT 1";
        $this->db->doQuery( $query );
       
        if( !( $quizInfo = $this->db->nextAssoc( ) ) )
        {
            $errText = "The quiz you are trying to access (ID " . $this->quiz . ") doesn't exist!<br><br>" .
                      "<a href=\"" . CFG_QUIZ_URL . "\">Choose a Valid Quiz</a><br>";
            new Error( "NQ-INT-001",$errText, ERR_LEVEL_MINOR, true );
        }
       
        showIntro( $quizInfo['name'], $quizInfo['intro'] );
    }
   
    function _makeSelectionPage( )
    {
        // Uncomment following to show ALL quizzes on selection page
        // (Not just ones that have valid questions)
        //$query = "SELECT id,name FROM Quizzes ORDER BY id ASC";
        $query = "CREATE TEMPORARY TABLE Temp
                  SELECT id AS qid,quiz
                  FROM nq_Questions q, nq_Choices c
                  WHERE id=c.question
                  GROUP BY id,quiz HAVING COUNT(c.position) > 1";
        $this->db->doQuery( $query );
       
        $query = "SELECT id,name
                  FROM nq_Quizzes,Temp
                  WHERE id=quiz
                  GROUP BY id,name";
        $this->db->doQuery( $query );
       
        $quizNames = array( );
        while( $quizName = $this->db->nextAssoc( ) )
            $quizNames[$quizName['id']] = $quizName['name'];
       
        showSelectionPage( $quizNames );
    }
   
    function _generatePage( )
    {
        if( !is_numeric( $this->quiz ) || intval( $this->quiz ) != $this->quiz )
            $this->_makeSelectionPage( );
       
        if( !$this->pageNum && $this->pageNum !== 0 )
        {
            $this->_makeIntroPage( );
            return;
        }
        if( $this->db->resultIsEmpty( ) )
        {
            $errText = "This quiz has no complete questions for you to answer.<br><br>" .
                      "<a href=\"" . CFG_QUIZ_URL . "\">Choose Another Quiz</a><br>";
            new Error( "NQ-GPG-001", $errText, ERR_LEVEL_MINOR, true );
        }
       
        $firstQ = $this->qPerPage * $this->pageNum;        // Calculate position of the first question on this page
       
        // Try to jump to first question of quiz
        // If fails, try to make results
        if( !$this->db->resultJump( $firstQ ) )    // Go to first question on this page:
        {
            while( $temp = $this->db->nextAssoc( ) )
                $this->questions[ $temp['id'] ] = new Question( $temp['id'], $temp['q'], $temp['reason'], $this->shuffleC );
            printResPage( $this->questions );
            //$this->_showResults( );
        }
        else
        {
            for( $i=0; ( $i < $this->qPerPage ) && ( $temp = $this->db->nextAssoc( ) ); $i++ )
                $this->questions[ $temp['id'] ] = new Question( $temp['id'], $temp['q'], $temp['reason'], $this->shuffleC );
            $totalPages = ceil( $this->db->resultNumRows() / $this->qPerPage );
            printQPage( $this->questions, $firstQ+1, $this->pageNum, $totalPages );
        }
    }
   
    function _getQuizConfigs( )
    {
        $this->db->doQuery( "SELECT per_page, shuffle_choices, shuffle_questions FROM nq_Quizzes WHERE id=" . $this->quiz );
        $temp = $this->db->nextAssoc();
        $this->qPerPage = $temp['per_page'];
        $this->shuffleC = $temp['shuffle_choices'];
        $this->shuffleQ = $temp['shuffle_questions'];
    }
}

?>

-----------------------------------------
question.class.php

<?php

/*
* Coding formatted for standard 4-space tabs.
*/

require_once( "Database.class.php" );
require_once( "config.php" );

class Question {
   
    var $qID;
    var $question;
    var $choices;
    var $reason;
   
    function Question( $id, $questionTxt, $reason, $randomizeChoices = false )
    {
        $this->qID = $id;
        $this->question = $questionTxt;
        $this->reason = $reason;
        $this->choices = new Database( CFG_DB_SERVER, CFG_DB_USERNAME, CFG_DB_PASSWORD, CFG_DB_NAME );
       
        $this->_fetchChoices( $randomizeChoices );
    }
   
    /**
    * Get the Next Choice as an Association Array
    *
    * The choice array includes 2 elements accessible by the keys "choice" and "position".
    * The "choice" is the text, the "position" is this choice's position as it was inserted
    * into the database.<br><br>
    * <b>NOTE:</b> If choices were randomized, each one still retains its original "position"
    * value, even if choices are displayed in a different order. So, "position" is essentially
    * a key for choices belonging to this question.
    */
    function nextChoice( )
    {
        return $this->choices->nextAssoc( );
    }
   
    function getReason( )
    {
        return $this->reason;
    }
   
    /**
    * Get the number of Choices
    */
    function getCount( )
    {
        return $this->choices->resultNumRows( );
    }
   
    /**
    * Reset choices to be able to iterate them again.
    */
    function resetChoices( )
    {
        $this->choices->resultJump( 0 );
    }
   
    /**
    * Get Question Text
    */
    function getQuestion( )
    {
        return $this->question;
    }
   
    /**
    * Get Question ID
    */
    function getQID( )
    {
        return $this->qID;
    }
   
    function getAnsPosition( )
    {
        $this->resetChoices( );
        for( $i=1; $choice = $this->nextChoice( ); $i++ )
            if( $choice['answer'] )
                return $i;
    }
   
    function getUserAnswer( )
    {
        return $_SESSION['answers'][$this->qID];
    }
   
    function getChoiceText( $position )
    {
        $this->choices->resultJump( $position-1 );
        $choice = $this->nextChoice( );
        $this->resetChoices( );
        return $choice['choice'];
    }
   
    /**
    * Fetch the Choices for the Specified Question From the Database
    */
    function _fetchChoices( $random )
    {
        $query = "SELECT choice,answer,position FROM nq_Choices WHERE question=". $this->qID;
       
        if( $random )
        {
            $num_session_id = preg_replace( "[\D]", "", session_id() );
            $rand_seed = substr( $num_session_id, strlen($num_session_id)-3 );
            $rand_seed = $rand_seed + ( substr( "$this->qID", strlen( $this->qID ) - 1 ) *300 );
            /*
              Using session ID as base of random seed to ensure that every usage of NueQuiz guarantees
              that for a given question, choices are ordered the same way no matter how many times a
              user views one question (ie. by using back/next feature). The seed has 500 possible combinations
              that are 10,000,000 apart (to ensure that they produce different choice combinations).
            */
            $query = $query . " ORDER BY RAND(" . $rand_seed * 10000000 . ")";
        }
        else
            $query = $query . " ORDER BY position";    // Otherwise just order by position (ascending).
       
        $this->choices->autoErrDisable( );
       
        if( !$this->choices->doQuery( $query ) )
            echo "<strong>ERROR: </strong>Could not fetch choices for question " . $this->qID . "!<br><br>";
       
        $this->choices->autoErrEnable( ERR_LEVEL_FATAL );
    }
}

?>
--------------------------------------------------
page.display.php

<?php

define( 'CFG_STYLE_PATH', 'nq_style/' );

require_once( "config.php" );

function _outputHTML( $text, $showAndExit, $center=true )
{
    $background = "#FFFFFF";
    $font_color = "#000000";

    $html_code ="<html>\n" .
                "<head>\n" .
                "<title>" . CFG_PAGE_TITLE . "</title>\n" .
                "<link rel=\"stylesheet\" href='" . CFG_STYLE_PATH . "quizStyle.css' type=\"text/css\">\n" .
                "</head>\n\n" .
                "<body background=\"$background\" text=\"$font_color\">\n";

    if ($center) $html_code .= "    <center>\n";

    $html_code .= $text;

    if ($center) $html_code .= "    </center>\n";

    $html_code .= "</body>\n</html>";

    echo $html_code;

    if( $showAndExit )
        exit();
}

function showSelectionPage( $quizNames )
{
    $html = "<table cellpadding=0 cellspacing=5 border=0 width=450><tr><td width=450 class='question'>\n" .
            "<br><strong class='quizname'>Quiz Selection</strong><br>\n" .
            "<hr width='450' align='left' color='gray' NOSHADE>\n" .
            "<small>Please select one of the following quizzes. " .
            "<font color='gray'> Please note that some quizzes " .
            "may not appear on this list; all the quizzes displayed here have at least " .
            "1 question that has at least 2 choices (questions with less than 2 choices are " .
            "not displayed in the quiz to which they belong).<br></font></small>\n" .
            "<ul type='square'>\n";
    while( list( $key,$value ) = each( $quizNames ) )
        $html .= "<li><a href='".CFG_QUIZ_URL."?quiz=$key'>$value</a></li>\n";

    if( count( $quizNames ) == 0 )
        $html .= "<blockquote>There are no valid quizzes to be taken at this time.</blockquote>\n";

    $html .= "</ul>\n";

    _outputHTML( $html, true );
}

function showIntro( $quizName, $intro )
{
    if( isset( $_GET['quiz'] ) ) {
        $quizNum = "quiz=" . $_GET['quiz'] . "&";
    }

    $html = "<table border=0 width=450><tr><td width=450 class='question'>\n";
    $html .= "<strong class='quizname'><br>$quizName<br></strong><hr>$intro<br>";
    $html .= "<form action=\"" . CFG_QUIZ_URL . "?" . $quizNum . "\" method=\"POST\">\n" .
            "<input type=\"Submit\" name=\"action\" value=\"" . NQ_BUT_START . "\">\n" .
            "</form>\n" .
            "</td></tr></table>\n";

    _outputHTML( $html, true );
}

function printQPage( $questions, $firstQNum, $pageNum, $totalPages )
{
    if( isset( $_GET['quiz'] ) ) {
        $quizNum = "quiz=" . $_GET['quiz'];
    }

    $html_code = "<form action=\"" . CFG_QUIZ_URL . "?" . $quizNum . "&" . strip_tags (SID) . "\" method=\"POST\">\n" .
            //"<table cellpadding=0 cellspacing=0 border=0 width=450><tr><td align=\"center\">\n" .
            "<table cellpadding=0 cellspacing=5 border=0><tr><td width=450 align='left'><br>\n";

    $qNum = $firstQNum;
    $answerList = $_SESSION['answers'];

    foreach( $questions as $question )
    {
        $html_code .= _printQ( $question, $qNum++, $answerList ) . "<br><br>\n\n";
    }

    if( $pageNum > 0 )
        $html_code .= "<input class='nav' type=\"Submit\" name=\"action\" value=\"" . NQ_BUT_PREV . "\">\n";

    if( $pageNum < $totalPages-1 )
        $html_code .= "<input class='nav' type=\"Submit\" name=\"action\" value=\"" . NQ_BUT_NEXT . "\">\n";

    if( $pageNum == $totalPages-1 )
        $html_code .= "<input class='nav' type=\"Submit\" name=\"action\" value=\"" . NQ_BUT_DONE . "\">\n";

    $html_code .= "<input type=\"Hidden\" name=\"page\" value=\"$pageNum\">\n" .
            "</form>\n";
    /* //Uncomment this to have a "restart button" throughout the whole quiz..
    $html_code .= "<form action=\"" . CFG_QUIZ_URL . "?" . $quizNum . "\" method=\"POST\">\n" .
            "<input type=\"Submit\" name=\"action\" value=\"" . NQ_BUT_RESTART . "\">\n" .
            "</form>";
    */
    $html_code .= "</td></tr>\n</table>\n";

    _outputHTML( $html_code, true );
}

function _printQ( $question, $qNum, $answerList )
{
    $html_code = "<table cellpadding=0 cellspacing=0 border=0 width=450>\n" .
            "<tr><td class=\"question\" colspan=3 width=450><b>$qNum. " . $question->getQuestion() . "</b></td></tr>\n";

    $position = 1;

    $checked = "";
    $qID = $question->getQID( );

    for( $i=1; $choice = $question->nextChoice( ); $i++ )
    {
        $checked = "";
        if( $answerList[ $qID ] == $i )
            $checked = "checked";
        $html_code .= "<tr>\n" .
                "\t<td valign=\"top\" nowrap class='question'>&nbsp;<input type=\"Radio\" name=\"answers[$qID]\" value=\"$i\" $checked>&nbsp;</td>\n" .
                "\t<td valign=\"top\" valign='middle' nowrap class='question'>" . _getCharPos( $position++ ) . ".&nbsp;</td>\n" .
                "\t<td width=\"90%\" valign=\"top\" align=\"left\" class='question'>" . $choice['choice'] . "</td>\n" .
                "</tr>\n";
    }

    return $html_code . "</table>\n";
}

function printResPage( $questions )
{
    if( isset( $_GET['quiz'] ) ) {
        $quizNum = "quiz=" . $_GET['quiz'] . "&";
    }

    $questionCount = count( $questions );

    $html_code = "<table cellpadding=0 cellspacing=0 border=0 width=450><tr><td align=\"center\">\n" .
            "<table cellpadding=0 cellspacing=5 border=0><tr><td class='results'>\n" .
            "<strong>Quiz Results</strong><br><hr width=\"450\" align=\"left\" color=\"gray\" NOSHADE><br>\n";
            //"<small>\n";
    $qNum = 1;
    $answerList = $_SESSION['answers'];
    $numCorrect = 0;
    $numAnswered = 0;

    foreach( $questions as $question )
        $html_code .= _printResQ( $question, $qNum++, $answerList, $numCorrect, $numAnswered, $questionCount ) . "<br>\n\n";

    $html_code .= "<hr width='450' align='left' color='gray' NOSHADE>\n";

    $scoring = "<table cellpadding=0 cellspacing=5 border=0 width=450>\n
                <tr><td colspan=2 width=450 class='question'>\n
                Your Score is <b>$numCorrect/$questionCount</b> or <b>" . _getPercent($numCorrect,$questionCount) . "%</b> of questions answered correctly.<br>\n
                </td></tr>";

    if( $numAnswered != $questionCount && $numAnswered > 0 )
        $scoring .= "<tr><td colspan=2 class='results'><font color='gray'>\n
                    (You scored <b>$numCorrect/$numAnswered</b> or <b>" . _getPercent($numCorrect,$numAnswered) . "%</b> counting only the questions that were answered)<br>\n
                    </td></tr>\n";

    $scoring .="<tr><td colspan=2>\n<hr width='450' align='left' color='gray' NOSHADE><br>\n</td></tr>\n
                <tr><td><form action='" . CFG_QUIZ_URL . "?" . $quizNum . "' method='POST'>\n
                <input type='Submit' name='action' value='" . NQ_BUT_RESTART . "'>\n
                </form></td>\n
                <td><form action='" . CFG_HOME_URL . "' method='GET'>\n
                <input type='Submit' value='Return to " . CFG_HOME_NAME . "'>\n
                </form></td></tr>\n
                </table>\n";

    $html_code .= "</small>\n</td></tr></table>\n</td></tr></table>\n";
    $html_code .= $scoring;
    $op = new QuizOperations( );
    $op->addStatistic( $_GET['quiz'], $questionCount, $numAnswered, $numCorrect );

    session_unset( );
    session_destroy( );

    _outputHTML( $html_code, true );
}

function _printResQ( $question, $qNum, $answerList, &$numCorrect, &$numAnswered, &$questionCount )
{
    $html_code = "<b>$qNum. " . $question->getQuestion( ) . "</b><br>\n";
    $qID = $question->getQID( );

    if( !$question->getUserAnswer( ) )
        $html_code .= "This question was not answered..<br><br>";
    else
    {
        $numAnswered++;

        $html_code .= "You answered: " . _getCharPos( $question->getUserAnswer() ) . " (<font color='gray'>" . $question->getChoiceText( $question->getUserAnswer() ) . "</font>)";
        $rightAns = $question->getAnsPosition( );

        if( !$rightAns )
        {
            $questionCount--;
            $numAnswered--;
            $html_code .= " <br><i><font color='gray'>However, no choice is the right answer, so this question will be omitted from your score.</font></i>";
        }
        else if( $rightAns == $question->getUserAnswer() )
        {
            $numCorrect++;
            $html_code .= " <b><font color='#0ACE38'>Correct!</font></b>";
        }
        else
            $html_code .= " <b><font color='red'>Incorrect!</font></b><br>\nCorrect answer is: " . _getCharPos( $rightAns ) . " (<font color='gray'>" . $question->getChoiceText( $rightAns ) . "</font>)" . "<br><br>\n";

        $html_code .= "<blockquote>" . $question->getReason( ) . "</blockquote>\n";
    }

    return $html_code;
}

function _getCharPos( $index )
{
    if( $index > 26 )
        return "Z" . ($index-26);    // This allows Z1, Z2, Z3,..
    $letters = array( '0','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' );
    return $letters[$index];
}

function _getPercent( $score, $outOf )
{
    if( $outOf <= 0 )
        return 0;
    return round( ($score/$outOf)*100, 1 );
}
?>
Avatar billede jaw Nybegynder
06. januar 2006 - 21:56 #8
Nu synes jeg du begynder at stille ret mange krav for 30 point? Det er jo et helt andet spørgsmål, er det ikke? Men ja, du kan joine 2 tabeller, hvis f.eks. der er et id på quizzen og et id på billedet i de 2 tabeller der er ens.
Avatar billede jan2001 Nybegynder
06. januar 2006 - 22:02 #9
jeg gætter selv på at det er i denne funktion, at der skal indsættes en stump kode for at vise billedet, men på en eller anden måde skal det hentes fra databasen og puttes ind i funktionen. Hvordan?
Avatar billede jan2001 Nybegynder
06. januar 2006 - 22:04 #10
Jeg kan godt oprette en ny tråd med flere point til dig for hjælpen.
Avatar billede jan2001 Nybegynder
06. januar 2006 - 22:09 #11
id lader til at være ens i begge tabeller.
Avatar billede jaw Nybegynder
06. januar 2006 - 22:41 #12
Du kan finde den forespørgsel der henter quizzen, samt navne på tabel og felter med billede.
Avatar billede jan2001 Nybegynder
07. januar 2006 - 00:03 #13
det kunne være denne:
function _fetchQuestions( )
    {
        $query = "SELECT id,q.question, AS q, reason " .
                "FROM nq_Questions q, nq_Choices c " .
                "WHERE id=c.question AND quiz=" . $this->quiz . " " .
                "GROUP BY id,q.question,reason HAVING COUNT(c.position) > 1";
               
        if( $this->shuffleQ )
        {
            $numSessionID = preg_replace( "[\D]", "", session_id() );
            $randSeed = substr( $numSessionID, strlen($numSessionID)-6, 3 );
            $randSeed = $randSeed + ( substr( "$this->quiz", strlen( $this->quiz ) - 1 ) * 300 );
            $query = $query . " ORDER BY RAND(" . $randSeed * 10000000 . ")";
        }
        $this->db->doQuery( $query );
    }

Men tingene går igennem flere funktioner og ender i funktionen
function _printQ( $question, $qNum, $answerList )

Det er nærmest umuligt for mig at se mig ud af dette problem.
Avatar billede jaw Nybegynder
07. januar 2006 - 00:14 #14
Det kunne godt være den måske. Du har dog ikke skrevet hvad den anden tabel og felter hedder, så du må selv rette og prøve:

        $query = "SELECT q.id,q.question, AS q, reason, billedetabel.billedefelt " .
                "FROM nq_Questions q, nq_Choices c, billedetabel " .
                "WHERE id=c.question AND quiz=" . $this->quiz . " AND billedetabel.idfelt = q.id " .
                "GROUP BY id,q.question,reason HAVING COUNT(c.position) > 1";

Håber det virker...
Avatar billede jan2001 Nybegynder
07. januar 2006 - 01:07 #15
Jeg vil kigge mere på det og se om jeg kan se mig ud af de mange funktioner.
Det vil nok tage mig et stykke tid.
Men mange tak for din hjælp.
Husk at lægge et svar.

PS: hvad betyder fx. $this->noget = nogetandet;
Avatar billede jaw Nybegynder
07. januar 2006 - 02:54 #16
Selv tak :)

Det betyder, at den variabel i klassen bliver tildelt en værdi.
Avatar billede Ny bruger Nybegynder

Din løsning...

Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.

Loading billede Opret Preview
Kategori
Vi tilbyder markedets bedste kurser inden for webudvikling

Log ind eller opret profil

Hov!

For at kunne deltage på Computerworld Eksperten skal du være logget ind.

Det er heldigvis nemt at oprette en bruger: Det tager to minutter og du kan vælge at bruge enten e-mail, Facebook eller Google som login.

Du kan også logge ind via nedenstående tjenester