在php MYSQLi上使用选项选择

时间:2018-08-06 06:12:47

标签: php mysqli

请帮助我,如何使用选项选择以使用MYSQLi显示数据库中的数据。

  

_________________ ______________
  |所有| / | | SEARCH | |
  |墨西哥(Mexico) _____________
  |法国||
  | _______________   

例如,当通过选择“ 墨西哥”点击搜索时。将显示数据库中墨西哥的数据。

1 个答案:

答案 0 :(得分:0)

<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="SELECT * FROM table_name";

if ($result=mysqli_query($con,$sql))
  {
  // Fetch one and one row
echo ' <select onclick="getData(this.value)" name="names">';
  while ($row=mysqli_fetch_row($result))
    {

      echo '<option value="'.$row['id'].'" >'.$row["name"].'</option>';  

    }
echo '</select>';
  // Free result set
  mysqli_free_result($result);
}

mysqli_close($con);
?>

<script>
function getData(id){
$.ajax({
     type: "POST",
     url: 'test.php?id='+id,
     data: "json",
     success: function(response){
         alert(response);
     }
});
}

</script>

test.php代码:

    <?php
    $con=mysqli_connect("localhost","my_user","my_password","my_db");
    // Check connection
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }

  $id=$_GET["id"];
    $sql="SELECT * FROM table_name WHERE id='$id'";

    if ($result=mysqli_query($con,$sql))
      {

      $row=mysqli_fetch_row($result)
    echo json_encode($row);
    }

    mysqli_close($con);
    ?>