[英]How to echo a hyperlink in php
我正在从数据库中读取电子邮件。 而且我想将电子邮件作为超链接回显,但无法正常工作。
<?php
$un = $_POST['username'];
$pw = $_POST['password'];
// connect to the db
$user = 'proc';
$pswd = 'passwd';
$db = 'school';
$conn = mysql_connect('localhost', $user, $pswd);
mysql_select_db($db, $conn);
// run the query to search for the username and password the match
$query = "SELECT email AS text FROM contact";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
// this is where the actual verification happens
while ($row = mysql_fetch_assoc($result)) {
echo ("\n".$row['text']);
echo "<a href=.$row['text']>some text</a>";
}
?>
知道我的代码有什么问题吗?
您不能在所有情况下都将变量嵌入在双引号字符串中。 您可以执行以下操作 :
echo "<a href={$row['text']}>some text</a>";
要么
echo "<a href=".$row['text'].">some text</a>";
我个人比较喜欢第二种形式,因为从历史上看一眼就很容易看到通过编辑器的语法突出显示嵌入了一个变量(尽管今天,编辑器也可能会突出显示第一种形式)。
请注意, 您当前的代码还有其他问题: HTML属性值不带引号,并且没有正确转义嵌入HTML的值。 也可以用类似的方法解决
echo '<a href="'.htmlspecialchars($row['text']).'">some text</a>";
正确的正确格式也取决于您数据的编码。 有关详细信息,请参见htmlspecialchars
。
在您的echo语句中使用此命令:
echo "<a href=\"mailto:$row[text]\" >some text</a>";
根据代码片段,我想它在行上出错了:
echo "<a href=.$row['text']>some text</a>";
它应该是 :
echo "<a href=\"" . $row['text'] . "\">some text</a>";
另一种方式
echo "<a href='$row[text]'>some text</a>";
但是,我最喜欢的是先获取数据
<?php
include 'my_super_db_access_abstraction_class.php';
$data['rows'] = db::getAll("SELECT email AS text FROM contact");
tpl('template.php',$data);
?>
然后包含一个外观自然的HTML模板:
<ul?>
<?php foreach ($rows as $row): ?>
<li><a href="<?=$row['text']?>">some text</a></li>
<?php endforeach ?>
</ul>
使用此脚本:
$text = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})','<a href="mailto:\\1">\\1</a>', $row['text']);
echo $text;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.