我的代码现在所做的是回显来自MySQL的链接,其中movie_id等于GET id。我想要添加的内容是让它回显像#34;没有链接喜欢的消息"如果没有链接,其中movie_id = id
<?php
// set the _GET id
if(isset($_GET["id"])){
$id = preg_replace('#[^a-z0-9]#i', '', $_GET['id']);
} else {
header("location: /");
exit();
}
// display data
$query = "SELECT * FROM links WHERE movie_id='$id'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo "<a href=\"".$row['url']."\" target=\"_blank\">link</a>";
}
?>
答案 0 :(得分:2)
只需在while循环之前添加一个检查。
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result)) {
echo "<a href=\"".$row['url']."\" target=\"_blank\">link</a>";
}
}else{
echo "No records were found.";
}
如果可能,请使用PDO扩展进行数据库查询。 http://php.net/pdo
答案 1 :(得分:0)
使用 empty()
if(empty($result))
{
echo 'your link here';
}
else
{
while($row = mysql_fetch_array($result)) {
echo "<a href=\"".$row['url']."\" target=\"_blank\">link</a>";
}
}
或者您也可以使用
if( mysql_num_rows($result) === 0 ){
echo 'no link ';
}
else{
while($row = mysql_fetch_array($result)) {
echo "<a href=\"".$row['url']."\" target=\"_blank\">link</a>";
}
}
答案 2 :(得分:0)
尝试使用不推荐使用的PDO.MYSQL。试试这样:
$result = mysql_query("SELECT * FROM links WHERE movie_id='$id'");
if (mysql_num_rows($result)){
while($row = mysql_fetch_array($result)) {
echo "<a href=\"".$row['url']."\" target=\"_blank\">link</a>";
}
}else{ echo "No Result"; }
答案 3 :(得分:0)
mysql_num_rows()用于获取行数。
if( mysql_num_rows($result) == 0 ){
// Data not found
}
else{
while($row = mysql_fetch_array($result)) {
echo "<a href=\"".$row['url']."\" target=\"_blank\">link</a>";
}
}
答案 4 :(得分:0)
使用这个简单的代码:
if($result=="")
{
echo 'No link found';
}
else
{
--your link--
}
答案 5 :(得分:0)
考虑使用object-oriented mysqli和准备好的陈述:
#get the id from the paramater in the url
$id = $_GET['id'];
#initialize a mysqli object
$mysqli = new mysqli('host','user','pw','db');
#cache the query
$query = <<<Q
SELECT url FROM links WHERE movie_id=?
Q;
#initialize a prepared statement
$stmt = $mysqli->stmt_init();
#returns true and evaluates to true if the query is doable
if($stmt->prepare($query)) {
#binds your id the the ? in the query (this adds security to your script)
$stmt->bind_param("i",$id);
$stmt->execute();
#gives each result in the column "url" a name, as the variable $url (which I assigned)
$stmt->bind_result($url)
# $stmt->fetch() returns false when no more results are found
while ($stmt->fetch()) {
echo $url;
}
} else {
#if no results were found through your query, echo "none found"
echo 'None found';
}