2015-04-16 20 views
-2

我正在尋找一種方法來顯示錯誤消息,如果表中沒有任何內容。如果數據庫表中有0項,返回錯誤

我有一個照片表。

如果這個表是空的,id就像回聲一樣。

否則,顯示圖片。

這個表裏面我有

id, name, url 
id = id 
name = name of image 
url = url of image. 

如果沒有行,我們有一個錯誤。

$query1 = mysql_query("SELECT COUNT(*) FROM photos;"); 
mysql_fetch_array($query1); 
if(empty($query1)) { 
echo "nothing"; 
} else { 
echo "good"; 
} 
+0

謝謝,很好的問題。我開始查詢SELECT COUNT(*)FROM照片。如果(query1 = 0)顯示錯誤 – newJavaCoder

+0

在查詢結果中使用'if()','empty()' – ajaykumartak

+1

您可以添加有問題的代碼嗎? –

回答

0

什麼像...

$sql = "SELECT COUNT(*) AS amountPhotos FROM photos"; 
$result = mysql_query($sql); 
$row = mysql_fetch_assoc($result); 
if ($row["amountPhotos"] == 0) { 
    echo "There are no photos in the photo table."; 
} 

$sql = "SELECT * FROM photos LIMIT 1"; 
$result = mysql_query($sql); 
if (mysql_num_rows($result) == 0) { 
    echo "There are no photos in the photo table."; 
} 
+0

我選了這個,因爲它是最簡單的。其他人工作得很好,但這很容易。謝謝@tobse – newJavaCoder

0

試試這個

$query1 = mysql_query("SELECT COUNT(*) FROM photos;"); 

$result = mysql_fetch_array($query1); 

if(empty($result)) { 
    echo "nothing"; 
} else { 
    echo "good"; 
} 
1

試試這個,

$query = "SELECT * FROM photos"; 
$result= mysql_query($query); 
$length= mysql_num_rows($result); 

if($length>0) 
{ 
    while($rows = mysql_fetch_array($result)) 
    { 
     echo $rows['name']; 
     echo "<img src='$rows[url]' />"; 
    } 
} 
else 
{ 
    echo "Nothing to display"; 
} 

希望這將工作

0

這幾乎總結了答案這個問題:http://www.w3schools.com/php/php_mysql_select.asp

他們甚至還提供了一個示例代碼:

<?php 
$servername = "localhost"; 
$username = "username"; 
$password = "password"; 
$dbname = "myDB"; 

// Create connection 
$conn = new mysqli($servername, $username, $password, $dbname); 
// Check connection 
if ($conn->connect_error) { 
    die("Connection failed: " . $conn->connect_error); 
} 

$sql = "SELECT id, firstname, lastname FROM MyGuests"; 
$result = $conn->query($sql); 

if ($result->num_rows > 0) { //<--- here they check if number of rows returned is greater than 0 (so there is data to display) 
    // output data of each row 
    while($row = $result->fetch_assoc()) { 
     echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>"; 
    } 
} else { 
    echo "0 results"; //<----- nothing found 
} 
$conn->close(); 
?> 

就修改這一點,你會好於走。

相關問題