从具有相同列条目的数据库中获取数据?

时间:2015-07-21 09:34:34

标签: php mysql

有一个列为

的数据库
Username      Password     Chain Name
12345         12345        ASDFG
12345         12345        QWERT
12345         12345        ZXCVB

我将UsernamePassword作为用户的输入,并希望显示与此用户名和密码相关联的所有Chain Name

上传PHP。

<?php  
  include('includes/config.php');

  if(isset($_POST['userid'],$_POST['pid'])){    
    $userid = trim($_POST["userid"]);
    $pid = trim($_POST["pid"]);

    $sql = "SELECT * FROM tbl_store WHERE username = '$userid' ";

    $result = mysqli_query($conn,$sql);
    $rowcount=mysqli_num_rows($result);
    echo "$rowcount";

    $row = mysqli_fetch_array($result);

    echo "Store code".'<br/>';
    echo $row['Chain_Name'].'<br/>'.'<br/>';
  }
?>

请建议您需要做些什么来获取所有Chain Name

1 个答案:

答案 0 :(得分:1)

$sql = "SELECT * FROM tbl_store WHERE username = '$userid' AND password='$pid'";

    $result = mysqli_query($conn,$sql);
    $rowcount=mysqli_num_rows($result);
    echo "$rowcount";
    $chainName = array();
    //if($rowcount>0){
        while($row = mysqli_fetch_array($result)){

           echo "Store code".'<br/>';
         echo $row['Chain_Name'].'<br/>'.'<br/>'; 
         $chainName[] = $row['Chain_Name'];
      }
      print_r($chainName); this will have all chain names 

替代解决方案

 $sql = "SELECT GROUP_CONCAT("Chain_Name") as allChainName FROM tbl_store WHERE username = '$userid' AND password='$pid'";

$result = mysqli_query($conn,$sql);
        $rowcount=mysqli_num_rows($result);
        echo "$rowcount";
        $chainName = array();
$row = mysqli_fetch_array($result);
$chainName = explode(",",$row['allChainName']);
 print_r($chainName); // this will have all chain names