我正在尝试从div中的php脚本中回显变量,但我没有得到任何结果。这是我的代码:
<?php
session_start();
session_name();
$con = mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("bloggers", $con) or die(mysql_error());
$data = "Select * from accountprofile where Username = '" . $_SESSION['Sess_user'] . "' and Password = '" . $_SESSION['Sess_pass'] . "'";
$result = mysql_query($data);
while($row = mysql_fetch_array($result)) {
$row['Fname'];
$row['Username'];
$row['Password'];
}
mysql_close($con);
?>
这里是我的div,我想显示变量$ row ['Fname'];
<div class="title" style="font-size: 36px;">
<?php echo $row['Fname']; ?>
</div>
抱歉,我是html和php的新手。请帮助谢谢。
答案 0 :(得分:2)
你很亲密。以下是您的代码简化和更正:
<?php
session_start();
session_name();
$con = mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("bloggers", $con) or die(mysql_error());
$data = "Select * from accountprofile where Username = '" . $_SESSION['Sess_user'] . "' and Password = '" . $_SESSION['Sess_pass'] . "'";
$result = mysql_query($data);
$row = mysql_fetch_assoc($result); // You're only getting one row, no need to loop.
mysql_close($con);
?>
<div class="title" style="font-size: 36px;">
<?php echo $row['Fname']; ?>
</div>
<强> FYI 强>:
Please, don't use mysql_*
functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDO或MySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial。
答案 1 :(得分:2)
变量$ row只是循环范围。你在里面创建这个变量,它只存在于那里。
答案 2 :(得分:0)
@ user2047260记得要显示的变量必须在while循环中,下面是代码试试吧
<?php
session_start();
session_name();
$con = mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("bloggers", $con) or die(mysql_error());
$data = "Select * from accountprofile where Username = '" . $_SESSION['Sess_user'] . "' and Password = '" . $_SESSION['Sess_pass'] . "'";
$result = mysql_query($data);
while($row = mysql_fetch_array($result)) {
$fname = $row['Fname'];
$username = $row['Username'];
$password =$row['Password'];
?>
<div class="title" style="font-size: 36px;">
<?php echo $fname;
mysql_close($con);
}
?>
</div>
enter code here
答案 3 :(得分:-1)
如果您在echo语句中回显变量,则可以执行以下操作:
echo "foo " . $bar . "!";
这称为连接字符串。
如果您希望以后再使用它,可以在while循环中使用以下内容将所有结果放入数组中
while($row = mysql_fetch_array($result)) {
$useLaterOn[] = $row;
}
希望这有助于:)