2015-12-22 29 views
-2

使用mysql结果添加时,我无法获得总数。 在php中简单添加

<?php 

//execute the SQL query and return records 
$result = mysql_query("SELECT * FROM table ORDER BY ID DESC LIMIT 1 "); 

while($row = mysql_fetch_assoc($result)){ 
    echo "{{$row['id']}+1}"; 
} 

?> 

在这里我得到的结果是 “27 + 1”。
但我想要“28”。请指出我出错的地方。

+1

注意:'mysql_ *'函数已被弃用,它们将在未来的版本中从PHP中删除,您的代码将停止工作。您不应使用它们编写新代码,而应使用['mysqli_ *'或PDO](http://php.net/manual/en/mysqlinfo.api.choosing.php)。 –

回答

3

PHP认为你正试图在连接字符串,所以我建议你明确两个数字相加和回声结果:

<?php 
    //execute the SQL query and return records 
    $result = mysql_query("SELECT * FROM table ORDER BY ID DESC LIMIT 1 "); 
    while($row = mysql_fetch_assoc($result)) { 
     $incremented = $row['id'] + 1; 
     echo $incremented; 
    } 

?> 

此外,不直接关系到你的问题,我建议你停止使用mysql_query和类似的函数,因为它们已被弃用,并在PHP 7中被删除。尝试使用PDO或mysqli扩展。

+3

为什么要使用附加变量?为什么不使用'increment operator'?所以简单地在循环内部:'echo ++ $ row ['id'];' – arkascha

+0

很好。它工作正常。我明白。感谢您的早日回复。 – rns

+0

是的,我应该使用增量运算符。那更好。 – rns

-1

为什么不能你理清这在查询本身,使用预先递增运算符试试这个..

$result = mysql_query("SELECT (id+1) as id, col2 FROM table ORDER BY ID DESC LIMIT 1 "); 
+0

可以请你解释一下为什么在这上面投了票.. – Sarath

0

您的需求将是全填:

<?php 
    //execute the SQL query and return records 
    $result = mysql_query("SELECT * FROM table ORDER BY ID DESC LIMIT 1 "); 
    while($row = mysql_fetch_assoc($result)) { 
     echo ++$row['id']; 
    } 
?> 

Result

+0

我不同意。这会改变变量的值,我们不能确定这是否正确。我们只需要打印递增的结果,为什么要改变这个值呢? –

0

你也可以直接通过查询完成它(如果你想继续添加ID)

SELECT count(id) as idCount FROM table ORDER BY ID DESC LIMIT 1 

如果你想知道总数

SELECT count(*) as idCount FROM table ORDER BY ID DESC LIMIT 1 

和应用层

echo $row['id']+1; 

将做的工作。