what my code does right now is echo the links from MySQL where movie_id is equal to the GET id. what I want to add is make it echo a message like "No links were fond" if there are no links where 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>";
}
?>
Just add a check before the while loop.
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.";
}
If possible, use PDO extension for database queries. http://php.net/pdo
use empty()
if(empty($result))
{
echo 'your link here';
}
else
{
while($row = mysql_fetch_array($result)) {
echo "<a href=\"".$row['url']."\" target=\"_blank\">link</a>";
}
}
Or You can also use
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>";
}
}
Try to use PDO.MYSQL deprecated. Try like this :
$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"; }
mysql_num_rows() is used to get the number of 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>";
}
}
Use this simple code:
if($result=="")
{
echo 'No link found';
}
else
{
--your link--
}
Consider using object-oriented mysqli and prepared statements:
#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';
}