我正在尝试使用表单帖子向mySQL表添加行。每行都有一个主要的我正在调用quoteID。提交新表单时,它应将自身添加为表中的一行,其quoteID大于前一个quoteID。它目前看起来像这样:
<?
session_start();
if(!session_is_registered(myusername)){
header("location:login.php");
}
include 'verify.php';
$con = mysql_connect("localhost","user","$password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("internal", $con);
$previousOrderID = mysql_query("SELECT * FROM sourcingQuote ORDER BY quoteID DESC LIMIT 1");
$newOrderID = $previousOrderID + 1;
mysql_close($con);
?>
目前这个表中有4行,引用ID为1,2,3和4.奇怪的是,如果我尝试:
<? echo $previousOrderID; ?><br>
<? echo $newOrderID; ?><br>
输出结果为:
Resource id #3
4
无论表中有多少行,$ previousOrderID都固定为3.如何更正此问题?更重要的是,当我添加它时它是正确的,但为什么它首先输出'资源ID#3'?
答案 0 :(得分:2)
您可以通过选择phpmyadmin中的自动增量
来完成此操作或通过sql示例,表名是demo,冒号是自动增量及其前缀键的演示
CREATE TABLE IF NOT EXISTS `demo` (
`demmo` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`demmo`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
答案 1 :(得分:1)
不,这是资源链接,您必须获取数据:
<?php
$previousOrder = mysql_query("SELECT * FROM `sourcingQuote` ORDER BY `quoteID` DESC LIMIT 1");
$previousOrder = mysql_fetch_assoc($previousOrder);
$previousOrderID = $previousOrder['quoteID'];
$newOrderID = $previousOrderID + 1;
echo $previousOrderID."<br />";
echo $newOrderID."<br />";
?>
答案 2 :(得分:1)
避免重复的最佳方法是将QuoteID
设置为AUTO_INCREMENT
ed PRIMARY KEY
CREATE TABLE sourcingQuote
(
QuoteID INT AUTO_INCREMENT,
-- other columns,
CONSTRAINT t_pk PRIMARY KEY (QuoteID)
)
答案 3 :(得分:0)
你可以在mysql phpmyadmin中将'quoteID'设为自动增量.....
并且你获得了资源ID#3 ..因为你正在引用资源链接.. 你可以通过
打印数据$previousOrderID = mysql_query("SELECT * FROM sourcingQuote ORDER BY quoteID DESC LIMIT 1");
$previousOrderID = mysql_fetch_assoc($previousOrderID);
$newOrderID = $previousOrderID['ID'] + 1;