How do I get the selected ID of the second dropbox based on the first dropbox in PHP with a refresh?

I am building an editor for a blog. Each post will be categorised.

When the user clicks on a post title from the first dropdown menu and presses Ga (go in dutch), then the second category dropbox will have the selected category associated with it, and display all the other categories in the same dropbox.

Having all the categories in the second dropbox will allow the user to change the category of article. I am able to get both dropbox populated, but not getting the selection part working. Can anyone help?

        <?php
          if (isset($_POST['Ga'])) {
        	$db = new mysqli("dbhost", "username", "password", "dbname"); //set your database handler
            $query = "SELECT c.catid , a.titel , c.cat FROM artikelen a JOIN Categorie c ON c.catid = a.catid  where  c.catid = a.catid";
            $result = $db->query($query);
        		  
            while ($row = $result->fetch_assoc()) {
        		
              if ($row ['a.catid'] = ['c.catid']) {
                $selected = ($row['catid'] == $result);
                echo "<option value=\"".$row["catid"]."\" ".($selected ? " selected=\"selected\"":"").">".$row["cat"]."</option>";    	
              }
            }
          }
        ?>
        	
        <?php 	
          $link = mysqli_connect("dbhost", "username", "password", "dbname");
          $db = new mysqli("dbhost", "username", "password", "dbname");//set your database handler
          $query = "SELECT c.catid , a.titel , c.cat FROM artikelen a JOIN Categorie c ON c.catid = a.catid";
          $result = $db->query($query);
        
          echo "<form action='test.php' method='post' enctype='multipart/form-data'>";
        ?>			
        	
        <select id='subcatsSelect'>
        		
        <?php
          // $query = "SELECT catid, cat FROM Categorie";
          $result = $db->query($query);
        
          while ($row = $result->fetch_assoc()) {
            // $subcats[$row['catid']][] = array("catid" => $row['catid'], "val" => $row['cat']);  
            echo "<option value='catid'> {$row['titel']}</option>";
          }
        		
        ?>
        
        </select>
        	
        <select id='categoriesSelect'>
        
          <?php     
            $result = $db->query($query);
            while ($row = $result->fetch_assoc()) {
        	  $resultofcar = ("<option value='{$row ['catid']}'> {$row['cat']}</option>");
              echo $resultofcar;
            }
          ?>

        </select>

        <input id='Ga' type='submit'  value='Ga'name='Ga' />

The most immediate problem is that form fields must have a name=ā€™ā€¦ā€™ attribute so that the data from that field will be submitted. Your two <select > fields do not have name attributes.

Next, the posted code is generally disorganized and undefined in what it is trying to do. The code for a page should be laid out in this general order -

  1. initialization - require/produce things your page needs for it to work
  2. post method form processing - perform an action based on the submitted form data
  3. get method business logic - get/produce data needed to display the page
  4. html document/template - use the output from the above sections to produce the web page

You also need to define what the work-flow/steps are. Then, define what data is needed to produce the output for step and what data will be submitted from each step. You can then go about designing, writing, testing, and debugging the code needed, one step at a time.

See the following example code for reference -

<?php

// initialization - require/produce things your page needs for it to work
// since a database connection is needed for all operations on this page, make ONE connection here
// you should put the database connection code in a .php file and require it when needed
// you should also use exceptions for database errors and in most cases let php catch and handle the exception, where it will use its error related settings to control what happens with the actual error information

// this example code uses the PDO extension, since it is much simpler and more consistent than the mysqli extension
require 'pdo_connection.php'; 

$post = []; // an array to hold a trimmed working copy of the form data
$errors = []; // an array to hold validation error messages

// post method form processing - perform an action based on the submitted form data
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
	// trim and validate all input data here, storing errors in an array using the form field name as the array index
	$post = array_map('trim',$_POST);
	
	if($post['category_id'] == '')
	{
		$errors['category_id'] = 'You must select a category.';
	}
	
	if($post['article_id'] == '')
	{
		$errors['article_id'] = 'An article has not been selected.'; // this error would indicate a programming mistake or someone feeding their own data to the script
	}
	
	// if no errors, use the submitted form data
	if(empty($errors))
	{
		// build, prepare, and execute an UPDATE query to change the category id in the selected article
		$sql = "UPDATE artikelen SET catid = ? WHERE id = ?";
		$stmt = $pdo->prepare($sql);
		$stmt->execute([$post['category_id'],$post['article_id']]);
	}
	
	// if no errors, success
	if(empty($errors))
	{
		// redirect to the exact same url of this page to cause a get request - PRG Post, Redirect, Get.
		header("Refresh:0");
		exit;
	}
}

// get method business logic - get/produce data needed to display the page

// retrieve all article data (id and title) for producing the 1st select/option menu
$sql = "SELECT id, title FROM artikelen ORDER BY title";
$stmt = $pdo->query($sql);
// separate the database specific code from the presentation code by fetching all the data from a query into an appropriately named variable, then test/use that variable in the html document
$article_data = $stmt->fetchAll();

// condition get input(s)
$article_id = $_GET['article_id'] ?? 0;

// retrieve the selected article data (catid)
if($article_id)
{
	$sql = "SELECT catid FROM artikelen WHERE id = ?";
	$stmt = $pdo->prepare($sql);
	$stmt->execute([$article_id]);
	$article_category = $stmt->fetchColumn();
	
	// retrieve all category data (catid, cat) for producing the 2nd select/option menu
	$sql = "SELECT catid, cat FROM Categorie ORDER BY cat";
	$stmt = $pdo->query($sql);
	$category_data = $stmt->fetchAll();
}

// html document/template - use the output from the above sections to produce the web page
?>

<?php
// output the article selection form
echo "<form>
	<select name='article_id'>
	<option value=''>Select an Article</option>";
foreach($article_data as $row)
{
	$sel = $article_id == $row['id'] ? ' selected' : '';
	echo "<option value='{$row['id']}'$sel>{$row['title']}</option>\n";
}
echo "</select>
	<input type='submit'>
	</form>";
?>

<?php
// output any errors
if(!empty($errors))
{
	echo implode('<br>',$errors);
}
?>

<?php
// output the category edit form
if($article_id)
{
	echo "<form method='post'>
		<input type='hidden' name='article_id' value='$article_id'>
		<select name='category_id'>
		<option value=''>Select a Category</option>";
	foreach($category_data as $row)
	{
		$sel = $article_category == $row['catid'] ? ' selected' : '';
		echo "<option value='{$row['catid']}'$sel>{$row['cat']}</option>\n";
	}
	echo "</select>
		<input type='submit' value='Ga'>
		</form>";
}

Thank you for your help. Iā€™m new to php. Is PDO better then MySQLi?

It generally takes fewer statements to accomplish a task, you can treat the result from a prepared and non-prepared query the same (the mysqli extension has a completely different interface/set of statements), and there are no driver/server specific gotchas that result in non-portable code (mysqli_stmt_get_result(), which would allow you treat the result from both types of queries the same, and mysqli_fetch_all() are dependent on the mysqlnd driver being used, which you cannot guarantee unless you manage your own server.)

An added benefit is that the same php statements are used regardless of the database type (the actual sql syntax may need to be changed), so, once you learn to use the PDO extension, you can use it with about 12 different database types, instead of learning a completely different php extension for each different database type.

Sponsor our Newsletter | Privacy Policy | Terms of Service