简体   繁体   中英

fetch a foreign key data from mysql database into select dropdownlist using php

I want to create a select dropdownlist which retrieves data from a table "teamtable" and displays it on a page where the user enters his choice and the corresponding ID for the choice is submitted in other database "user" where the column is a foreign key.

Tables and their contents-

teamtable -

idTeam(INT)(PK) - 1,2,3

teamName(VARCHAR) - Team-1, Team-2, Team-3

user -

team(INT)(FK)

 <html> <head> <script type="text/javascript"> function validateForm() { var f=document.forms["reg"]["team"].value; if ((f==null || f=="")) { alert("All Field must be filled out"); return false; } } </script> <form name="reg" action="user_exec.php" onsubmit="return validateForm()" method="post"> <table width="274" border="0" align="center" cellpadding="2" cellspacing="0"> <tr> <td colspan="2"> <div align="center"> <?php $remarks=$_GET['remarks']; if ($remarks==null and $remarks=="") { echo 'Register a new user'; } if ($remarks=='success') { echo 'Registration Success'; } ?> </div></td> </tr> <tr> <td><div align="right">Team:</div></td> <td> <?php $mysqli_hostname = "localhost"; $mysqli_user = "root"; $mysqli_password = "my_pass"; $mysqli_database = "my_db"; $prefix = ""; $bd = mysqli_connect($mysqli_hostname, $mysqli_user, $mysqli_password) or die("Could not connect database"); mysqli_select_db($mysqli_database, $bd) or die("Could not select database"); $sql = "SELECT idTeam,teamName FROM teamtable "; $result = mysqli_query($sql); echo "<select name='team'>"; while ($row=mysqli_fetch_array($result)) { echo "<option value='" . $row['idTeam'] ."'>" . $row['teamName'] ."</option>"; } echo "</select>"; ?> </td> </tr> <tr> <td><div align="right"></div></td> <td><input name="submit" type="submit" value="Submit" /></td> </tr> </table> </form> </head> </html> 

  <?php include('connection.php'); $sql = "SELECT idTeam, teamName FROM team"; $result = $conn->query($sql); echo "<select name='team'>"; if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "<option value='" . $row['idTeam'] ."'>" . $row['teamName'] ."</option>"; } echo "</select>"; } else { echo "0 results"; } $conn->close(); ?> 

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