0

I have this code:

<html>
<body>
<form method="post" action="">
Category:   <select name="category">
<option>Choose Category</option>
<?php 
include("connect.php");
$select="SELECT * FROM category";
$result=mysqli_query($link,$select) or die (mysqli_error($link));

    while($row=mysqli_fetch_array($result))
    {

    echo "<option value='$row[category]'>".$row['category'];

    }
?>
</select>

<br>
Subcategory:<select name="category">
<?php
include("connect.php");

$category=@$_POST['category'];

if($category=="Friuts")
{
    $select="SELECT * FROM subcategory WHERE $category='$category'";
    $result=mysqli_query($link,$select) or die (mysqli_error($link));

    while($row=mysqli_fetch_array($result))
    {

    echo "<option value='echo $row[subcategory]'>".$row['subcategory'];

    }
}


?>

</select>
<br>

<input type="submit" value="Open" name="submit">
</form>
</body>
</html>

I have two tables, table one name category and table two name subcategory, I want two when I choice one item option from table category get data from table subcategory in the select option appear in the image below:

This image is table category

This image is table subcategory

Talib
  • 25
  • 3
  • 9
  • 2
    Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use prepared statements with bound parameters, via either the [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php) drivers. [**This post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) has some good examples. – Alex Howansky Aug 26 '17 at 20:14
  • @AlexHowansky This is my code, how i can fix? – Talib Aug 26 '17 at 20:21
  • Maybe read the links I posted? – Alex Howansky Aug 26 '17 at 20:34
  • Thank you @AlexHowansky I read it and i will tray. – Talib Aug 26 '17 at 20:43

1 Answers1

1

To accomplice what you want you need to:

  1. Create a select box that shows the values from the main table, best is to use the category_id as value
  2. Check if the form has been submitted (thus if( isset( $_POST['category'] ) ) {}. Ifso, run a query on the subcategory table and check for cat_id = $_POST['category']
  3. show the results from the second query in a select box.

Or in short:

echo "<option value='$row[cat_id]'>".$row['category'];

$select='SELECT * FROM subcategory WHERE cat_id="' . mysqli_real_escape_string($link, $category ).'"';

NOT tested and PLEASE read the websites 'Alex Howansky' provided!

Jeffrey
  • 1,766
  • 2
  • 24
  • 44