2017-06-16 88 views
0

以下是我從中獲取數據庫表中的行數的PHP代碼。但是下面的代碼總是返回1個行。請幫我解決問題,從數據庫中獲取正確數量的行。SQL計數查詢返回預設爲1的行數而不是實際的行數

$db=mysqli_connect("localhost","root","","test");    
    echo "<div class='row text-center col-lg-12' align='center'>";  
    $cmd="SELECT COUNT(*) FROM product WHERE product_name LIKE '%$search_query%'"; 

    $result = mysqli_query($db, $cmd); 
    $total = mysqli_num_rows($result); 
+0

你試圖在phpMyAdmin例如,或者直接到MySQL的SQL部分運行相同的查詢?如果是,它會返回什麼? – SebastianGreen

+1

'COUNT(*)'是行數(如1行)。選擇值...或返回所有行,然後使用'num_rows'函數。您還應該參數化查詢。 – chris85

回答

2

如果你做一個SELECT COUNT(*)你會得到一個行的計數值在第一列。所以,你需要得到這樣的COUNT()值:

$result = mysqli_query($db, $cmd); 
$row = mysqli_fetch_array($result); 
$total = $row[0]; 
0

這應該工作:

$db=mysqli_connect("localhost","root","","test");    
    echo "<div class='row text-center col-lg-12' align='center'>";  
    $cmd="SELECT * FROM product WHERE product_name LIKE '%$search_query%'"; 

    $result = mysqli_query($db, $cmd); 
    $total = mysqli_num_rows($result); 
相關問題