Mysqli为特定值获取assoc循环

时间:2015-09-03 11:43:16

标签: php mysql fetch

我有下表呼叫爱好:

name,  hobby1,  hobby2,  hobby3,   hobby4

Jenny, Skiing,  Bowling, Swimming, Dancing
Jane,  Skiing,  Jogging, Eating,   Dancing
Bonny, Skiing,  Bowling, Swimming, Dancing
Alice, Running, Bowling, Swimming, Drinking
Amber, Running, Bowling, Eating,   Dancing

我可以使用fetch_assoc函数来获取拥有hobby1的人的名字:

$sql = "SELECT name, hobby1 FROM hobbies";
$result = mysqli_query($con, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo "Name: " . $row['name'].", ".$row['hobby1']. "<br>";
    }
} else {
    echo "0 results";
}

答案:

Name: Jenny, Skiing
Name: Jane, Skiing
Name: Bonny, Skiing
Name: Alice, Running
Name: Amber, Running

如何修改代码只列出喜欢滑雪的人?

2 个答案:

答案 0 :(得分:3)

您可以将where子句设为

SELECT name, hobby1 FROM hobbies where hobby1 = 'Skiing'

答案 1 :(得分:2)

如果您要求使用Skiing获取hobby1,那么这是您需要的查询

$sql = "SELECT name, hobby1 FROM hobbies WHERE hobby1 = 'Skiing'";