mysql MAX()返回0而不是实际值

时间:2014-05-23 14:02:56

标签: php mysql

以下代码返回0,而不是行order_id

中的最大数字
if ($result_oid = $link->prepare("SELECT MAX(order_id) AS order_id FROM $table")) {
  $result_oid->execute();
  $obj = $result_oid->get_result()->fetch_object();
  $oid_o = $obj->id;
  $result_oid->close();
  $oid = $oid_o + 1;
}

以下是使用PHP mysql而不是mysqli(使用相同的mysql数据库)的工作示例:

mysql_connect($host, $user, $pwd) or die ("Couldn't connect to MySQL database.");

mysql_select_db($db) or die ("No Database found!");

$query = mysql_query('SELECT MAX(order_id) FROM airsale_list');
$result = mysql_fetch_array($query, MYSQL_NUM);
$max_order_id = $result[0];
$max_order_id = (int)$max_order_id;
$oid = $max_order_id++;
echo "<h4>order_id: $oid</h4>";

mysql_close();

表格结构

CREATE TABLE IF NOT EXISTS `airsale_list` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `cat` int(11) NOT NULL,
  `title` varchar(255) NOT NULL,
  `desc_small` varchar(1000) DEFAULT NULL,
  `name` varchar(255) NOT NULL,
  `lastupdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `price` int(20) NOT NULL,
  `currency` varchar(3) NOT NULL DEFAULT 'EUR',
  `total_time` varchar(255) DEFAULT NULL,
  `engine` varchar(1000) DEFAULT NULL,
  `engine_time` varchar(255) DEFAULT NULL,
  `prop` varchar(1000) DEFAULT NULL,
  `prop_time` varchar(255) DEFAULT NULL,
  `exterior` varchar(2000) DEFAULT NULL,
  `interior` varchar(2000) DEFAULT NULL,
  `avionics` varchar(5000) DEFAULT NULL,
  `add_info` varchar(5000) DEFAULT NULL,
  `order_id` int(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=103;

1 个答案:

答案 0 :(得分:0)

我认为您应该使用$obj->order_id而不是$obj->id,因为您在查询中将最大值作为order_id。

if ($result_oid = $link->prepare("SELECT MAX(order_id) AS order_id FROM $table")) {
    $result_oid->execute();
    $obj = $result_oid->get_result()->fetch_object();
    $oid_o = $obj->order_id;
    $result_oid->close();
    $oid = $oid_o + 1;
}