hello, how can I display a data (ex. course) in a drop-down list whenever I add a data? thanks!

Dani AI

Generated

Short summary and a cleaner approach

wants topics tied to a selected course; showed a working page-reload solution. That works, but it relies on the old mysql_* API and forces full-page navigation. A clearer, more robust pattern is:

  • Store courses and topics with integer IDs (use the topic row’s course_id as a foreign key).
  • Populate the course <select> with option values set to course IDs.
  • Load topics for the chosen course via an AJAX call that returns JSON.
  • Insert new topics with the chosen course_id and update the topic <select> client-side so the new topic appears immediately.

Minimal schema (example)

CREATE TABLE courses (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(150) NOT NULL UNIQUE
);

CREATE TABLE topics (
  id INT AUTO_INCREMENT PRIMARY KEY,
  course_id INT NOT NULL,
  title VARCHAR(255) NOT NULL,
  FOREIGN KEY (course_id) REFERENCES courses(id) ON DELETE CASCADE
);

Server endpoint (example: return JSON for a course)

<?php
// get_topics.php?course_id=123
header('Content-Type: application/json; charset=utf-8');
if (empty($_GET['course_id'])) { echo json_encode([]); exit; }
$pdo = new PDO('mysql:host=localhost;dbname=...;charset=utf8mb4','user','pass',[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
$stmt = $pdo->prepare('SELECT id,title FROM topics WHERE course_id = ? ORDER BY title');
$stmt->execute([(int)$_GET['course_id']]);
echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));

Client-side: fetch and populate the topic dropdown

document.getElementById('course').addEventListener('change', function(){
  const id = this.value, topic = document.getElementById('topic');
  topic.innerHTML = '<option>Loading...</option>';
  fetch('get_topics.php?course_id=' + encodeURIComponent(id))
    .then(r => r.json())
    .then(list => {
      topic.innerHTML = list.length ? '' : '<option value="">No topics</option>';
      list.forEach(t => {
        const o = document.createElement('option'); o.value = t.id; o.textContent = t.title; topic.appendChild(o);
      });
    })
    .catch(()=> topic.innerHTML = '<option value="">Error</option>');
});

Practical tips

  • Use IDs, not names, as option values so names can change without breaking relationships.
  • Always use prepared statements (PDO/mysqli) to avoid SQL injection and because mysql_* was removed in newer PHP versions (PHP PDO manual).
  • Escape any values rendered into HTML with htmlspecialchars.
  • After inserting a topic server-side, return the new row as JSON and append it to the topic <select> so users don’t need a full reload.
  • Index topics.course_id for performance on larger tables.

Recommended Answers

All 5 Replies

hello, how can I display a data (ex. course) in a drop-down list whenever I add a data? thanks!

hi...

from database? or any other way?

can u explain be detail?

from data base, u can get this way.....

$course="aaaaa"; //example...
<select name="course" title="course" value="<?php echo $course; ?>" >
<option value="">Select course</option>
<?php
while($row=mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['course']; ?>"><?php echo $row['course']; ?></option>
<?php
}
?>
</select>

thanks..

how can i "connect" test1 to test 2? example, i already have an id for the test1. i want to connect test2's id to test1... i dont know how to implement it in PHP... XD

thanks..

how can i "connect" test1 to test 2? example, i already have an id for the test1. i want to connect test2's id to test1... i dont know how to implement it in PHP... XD

Hi...

here what is test1 and test2 ?
explain plz?

ok sorry. lets say test1 == course. test2 == topic. I want to add a course in the database and display it to a drop-down menu(done). After selecting the desired course, we will now add a topic to that course. so from there, if we want to view a course, the topic added to that course will display.

im creating a test bank btw. :)

ok sorry. lets say test1 == course. test2 == topic. I want to add a course in the database and display it to a drop-down menu(done). After selecting the desired course, we will now add a topic to that course. so from there, if we want to view a course, the topic added to that course will display.

im creating a test bank btw. :)

HI..
first i want to know ..this is right? plz check...

1)display courses in first select box..
2) afeter selecting the course u need to display topics related to that course in second select box..

if the above procedure is right try to using this one...


in this select box display all courses frm database..

<select name="course" id="course" onchange="switchProduct();">
<?php
		include("config.php");
		$row=mysql_query("select distinct course from courses  ")or die(mysql_error());
		
?>
        <?php if(!$cu==""){ ?>
 <option value="<?php echo $cu ; ?>"><?php echo $cu;?></option><?php }else { ?> 
<option value="Select One">Select One</option><?php } ?>
<?php 
		while($res=mysql_fetch_array($row))
		{
		$course1=$res['course'];
		if($cu!=$course){
?>
          <option value="index.php?cu=<?php echo $course1 ; ?>&topic=<?php echo $topic; ?>"><?php echo $course1;?></option>
<?php }}
?>
            </select>

after by using onchange event u can display topics.....
here is the code...

<script language="javascript">
	 function switchProduct()
	 {
	 if(window.document.form1.course.options.selectedIndex!=0)
	 
	 window.location=window.document.form1.course.options[window.document.form1.course.options.selectedIndex].value
	 }
	  
	 
	  </script>

here is second selectbox code.....

$cours= $_GET['course'];
<select name="topic" id="topic">
     
<?php
$course
if($course==""){?>
<option value="Select One">Select Course</option>
<?php }else  { ?> 
 <option value="<?php echo $topic;?>"><?php echo $topic;?></option>
<?php }
		while($res=mysql_fetch_array($row1))
		{
		$topic1=$res['topic']; 
		if($topic==$topic1){}else{
?>
          <option value="<?php echo $topic1;?>"><?php echo $topic1;?></option>
<?php }}
?>
        </select>

If u confuse plz excuse....just ask if u want any doubts....

Be a part of the DaniWeb community

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