我是PDO和PHP的新手,我想知道如何根据从我的表中提取的信息来定义变量。
我有以下内容:
$UID = $_GET['id'];
$sth = $conn->prepare("SELECT * FROM directory WHERE user_active != '' AND ID = '$UID'");
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo $row['First_Name'] . ' ' . $row['Surname'] . "\n";
echo '<img src="http://maps.google.com/maps/api/staticmap?center=' . $row["Location_Postcode_Last_Seen"] . '&zoom=1
4&size=200x200&maptype=roadmap&markers=color:ORANGE|label:A|' . $row["Location_Postcode_Last_Seen"] . '&sensor=true">';
echo $row["Nicknames"];
echo $row["Age"];
}
如果我尝试添加:
var $name = echo $row['First_Name'] . ' ' . $row['Surname'];
在我的while
循环中,代码无法向浏览器输出任何内容。
答案 0 :(得分:2)
分配变量就像这样完成,
$name = $row['First_Name'] . ' ' . $row['Surname']; //defining variable $name
并回显/显示它,应该像
一样echo $name; //this will display whatever is in $name
在问题中给出的while循环应该可以正常工作,只要这些键存在于结果集中,就会显示您尝试echo
的所有内容。
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo $row['First_Name'] . ' ' . $row['Surname'] . "\n";
echo '<img src="http://maps.google.com/maps/api/staticmap?center=' . $row["Location_Postcode_Last_Seen"] . '&zoom=1
4&size=200x200&maptype=roadmap&markers=color:ORANGE|label:A|' . $row["Location_Postcode_Last_Seen"] . '&sensor=true">';
echo $row["Nicknames"];
echo $row["Age"];
}
编辑:(根据评论)
//assign all that you want to display to a variable $map, the equality operator '=' is used for assigning the right-hand side value to the left-hand side variable.
$map = '<img src="maps.google.com/maps/api/staticmap?center=' . $row["Location_Postcode_Last_Seen"] . '&zoom=1 4&size=200x200&maptype=roadmap&markers=color:ORANGE|label:A|' . $row["Location_Postcode_Last_Seen"] . '&sensor=true">';
echo $map; //display $map
注意:只有在需要多次访问变量时才需要分配变量。
答案 1 :(得分:0)
var
是一个仅用于在类中声明变量的关键字。这可能是问题所在:
echo $row['First_Name'] . ' ' . $row['Surname'];
或
$name = $row['First_Name'] . ' ' . $row['Surname'];
echo $name;
此外,您使用的是红外线状态错误。它们的部分好处是自动引用您的参数。它应该看起来像下列之一:
// position placeholders
$sth = $conn->prepare("SELECT * FROM directory WHERE user_active != '' AND ID = ?");
$sth->execute(array($UID));
或
// names palceholders
$sth = $conn->prepare("SELECT * FROM directory WHERE user_active != '' AND ID = :uid");
$sth->execute(array(':uid' => $UID));