我创建了一个要求用户添加的表单: first_name,last_name,location,status
一段时间后,我收到了5个输入。 mysql表名为users,表数据如下:
id first_name location status
== ========== ======== ========
1 Chris UK Married
2 Anton Spain Single
3 Jacob UK Single
4 Mike Greece Married
5 George UK Married
另外我通过POST方式接收输入的方式。所以:
$firstname=$_POST['FIRST_NAME']; // First Name: <input type="text" name="FIRST_NAME">
$location=$_POST['LOCATION']; // Location: <input type="text" name="LOCATION">
$status=$_POST['STATUS']; // Status: <input type="text" name="STATUS">
我创建了一个查询来选择来自英国的所有已婚用户:
$query = "SELECT * FROM users WHERE location='UK' AND status='Married'";
$result = mysqli_query($dbc,$query); //$dbc is the connection to my database
$row = mysqli_fetch_array($results, MYSQLI_BOTH);
换句话说:
id first_name location status
== ========== ======== ========
1 Chris UK Married
5 George UK Married
问题:
1)$ row数组是否如下所示:
$row= array(
array(1 Chris UK Married),
array(5 George UK Married)
);
2)如何在实施过滤后回显数据库的内容WHERE location ='UK'AND status ='Married'?
我需要它是这样的:
Hello Chris! You are from UK and you are married!
Hello George! You are from UK and you are married!
我知道我必须使用foreach循环(echo数组),但我已经尝试了它并且它不起作用。我试过的一些东西是我在php.net中找到的东西:
使用list()
解压缩嵌套数组(PHP 5> = 5.5.0)
PHP 5.5增加了迭代数组数组的能力,并通过提供list()作为值将嵌套数组解压缩为循环变量。
例如:
<?php
$array = [
[1, 2],
[3, 4],
];
foreach ($array as list($a, $b)) {
// $a contains the first element of the nested array,
// and $b contains the second element.
echo "A: $a; B: $b\n";
}
?>
当我使用上述内容时,我收到以下错误:
Parse error: syntax error, unexpected T_LIST in C:\wamp\www....
有什么建议吗?
据我了解,我不得不将ID与其他数据联系起来..
提前致谢。
答案 0 :(得分:3)
您可以使用以下内容:
$query = "SELECT * FROM users WHERE location='UK' AND status='Married'";
$result = mysqli_query($dbc,$query);
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
printf("Hello %s! You are from %s and you are %s!\n", $row['first_name'], $row['location'],$row['status']);
}
答案 1 :(得分:1)
mysqli_fetch_array
返回一行。你需要循环来获取所有行。您可以从行中获取值并将其放在以下字符串中:
while($row = mysqli_fetch_array($results, MYSQLI_BOTH)){
echo "Hi ".$row['first_name'] . " You are from ".$row['location']." and you are ".$row['status']."!";
}
答案 2 :(得分:0)
问题2:您可以在sql查询中添加格式我猜:
"SELECT OUTPUT = "Hello" + name + "! You are from UK and you are married!" FROM users WHERE location='UK' AND status='Married'";