简体   繁体   中英

Selection option in php

I am working on a PHP quiz game and at the moment i am struggling a bit mixing php and html together as i have more previous experience in html. I have the following select option for quiz selection:

<select style="width: 300px" name="quizes" size="10">
  <option onClick="window.location = 'quiz1.php'" >Quiz 1</option>
  <option>Quiz 2</option>
  <option>Quiz 3</option>
  <option>Quiz 4</option>
  <option>Quiz 5</option>
</select>

I was told that this can be made with php code so that the new quizes are added onto it when created. Can somebody help me out with this, i dont quite understand how this would work.

I am not using database for my quizes, each quiz is/will be on one page, with the questions stored in array and the processing of the questions is on the same page.

Try this, added fire event in <select>

<select style="width: 300px" name="quizes" size="10" onChange="window.location = 'quiz1.php?val='+this.value;">
  <option value='Quiz 1'>Quiz 1</option>
  <option value='Quiz 2'>Quiz 2</option>
  <option  value='Quiz 3' >Quiz 3</option>
  <option  value='Quiz 4'>Quiz 4</option>
  <option  value='Quiz 5'>Quiz 5</option>
</select>

Try this. It presumes that the page where the selection is made, is in the same directory as your quiz php pages.

<?php
$dir    = getcwd();
$files = scandir($dir);

foreach($files as $file)
{
    if (strpos($file,'quiz') !== false)
    {
        $fileName = ucfirst(str_replace('.php', '', $file));
        $quizPages[] = array('name'=>$fileName,'file'=>$file);
    } 
}
?>

<select style="width: 300px" name="quizes" size="10">
<?php
foreach($quizPages as $quiz)
{
    echo '<option name="' . $quiz["name"] . '" onClick="window.location = \'' . $quiz["file"] . '\'" >' . $quiz["name"] . '</option>';
}
?>
</select>

Update for comment.

This is likely due to the fact you have a file called Quizes in that directory also, which having the word quiz in its being caught in the foreach loop. What I would suggest is to change this line

if (strpos($file,'quiz') !== false)

To this

if (strpos($file,'quiz') !== false && strpos($file,'quizes') === false)

Further update. If you want to have a custom name for the quiz I would suggest you use the following naming convention quiz_desired_name.php. So for example If I have a quiz called what animal are you. Then the filename should be quiz_what_animal_are_you.php therefore separating words with underscores.

Then just replace this line

$fileName = ucfirst(str_replace('.php', '', $file));

with this

$fileName = ucfirst(str_replace(array('.php','quiz_','_'), array('','',' '), $file));

if you want to use html tags inside php,add an

eg:

 echo"<select>";

before every html tag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM