2014-10-04 101 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); 

?> 

谢谢!