2014-10-04 106 views
0

在下面的代碼中,我試圖連接到我的數據庫,從我的表中拉出最大ID,然後使用rand()函數生成一個隨機數。代碼成功地將我連接到數據庫,但是當我嘗試調用最大ID時,它不會返回值。未在PHP變量聲明中運行mySQL語句

當我嘗試回顯變量時,它返回SELECT MAX(id)FROM'file'。

<?php 

// Connect to the database 
     $dbLink = new mysqli('localhost', 'username', 'password', 'database'); 
     if(mysqli_connect_errno()) { 
      die("MySQL connection failed: ". mysqli_connect_error()); } 


    $amount = "SELECT MAX(id) FROM 'table'"; 
    $rannmr = rand(1, $amount); 


// Close the mysql connection 
    mysqli_close($dbLink); 

?> 

任何幫助解決此問題將不勝感激。

回答

2

當我嘗試回顯變量時,它返回SELECT MAX(id)FROM'file'。

首先,您使用了錯誤的identifierFROM 'table'是單引號。

如果table確實是表名,用反引號包起來,你的問題顯示file

$amount = "SELECT MAX(id) FROM `table`"; 

無論哪種方式,不能使用引號表名。看起來你正在使用file作爲你的表名。

所以,如果table僅僅是一個例子,它被稱爲file讓我們只說,你會怎麼做:

$amount = "SELECT MAX(id) FROM `file`"; 

$amount = "SELECT MAX(id) FROM file"; 

然後,還需要查詢,使用mysqli_query()你沒有做的。

$amount = mysqli_query($dbLink,"SELECT MAX(id) FROM `file`"); 

或面向對象的風格:

$amount = $dbLink->query("SELECT MAX(id) FROM `file`"); 

if($amount){ 
    echo "Success!"; 
}else{ 
    die('Error : ('. $dbLink->errno .') '. $dbLink->error); 
} 

使用or die(mysqli_error($dbLink))mysqli_query()這將標誌着錯誤。


編輯:

嘗試以下。您可能需要根據列號將$row[0]rand(0,$count)修改爲1

$result = $dbLink->query("SELECT MAX(id) FROM mytable") 
while ($row=$result->fetch_row()) { $count = $row[0]; } 
$random = rand(0,$count); 
echo $random; 
+0

錯誤報告返回以下錯誤「rand()期望參數2很長,對象給定...」 – Sangeet 2014-10-04 17:08:19

+0

@Sangeet爲什麼不只是使用MySQL的'RAND()'函數?即'ORDER BY RAND()' – 2014-10-04 17:09:29

+0

我希望速度優先。 – Sangeet 2014-10-04 17:11:43

0

使用這樣的:

$量= 「SELECT MAX(ID)FROM表」;

0

你忘了執行的MySQL查詢:

$amount = $dbLink->query("SELECT MAX(id) FROM table")->fetch_assoc(); 
$rannmr = rand(1, $amount[0]); 
+0

,並且已經提到過您有錯誤的單引號,則以下是方法。 – 2014-10-04 16:38:57

0

你永遠不執行的查詢,則需要更多的邏輯

if ($result = mysqli_query($dbLink, "SELECT MAX(id) as amount FROM `table`")) { 
    printf("Select returned %d rows.\n", mysqli_num_rows($result)); 
    if ($row = mysqli_fetch_assoc($result)) { 
     $amount = $row['amount']; 
     $rannmr = rand(1, $amount);    
    }else{ 
     echo 'no row found'; 
    } 
} 
mysqli_close($dbLink); 
0

我似乎沒有看到的代碼行實際上沒有查詢:

試試這個:使用面向對象的mysqli方法

<?php 

// Connect to the database 
    $dbLink = new mysqli('localhost', 'username', 'password', 'database'); 
    if(mysqli_connect_errno()) { 
     die("MySQL connection failed: ". mysqli_connect_error()); } 


$amount = "SELECT MAX(id) as max_id FROM 'table'"; 

// Do the actual query : 
$run_query = $dbLink->mysql->query($amount); 
// Retrieve the values: 
$result = $run_query->fetch_array(); 
// Do the rand function together with the retrieved value 
$rannmr = rand(1, $result['max_id']); 

// Now you can echo the variable: 
echo $rannmr; 



// Close the mysql connection 
mysqli_close($dbLink); 

?> 

謝謝!