[英]Inserting a row to a table with auto_increment column
我正在处理一个有 4 列的表,第一个是一个名为 id 的自动递增整数。
如果我要使用 mysqli 准备好的语句插入到这个表中,我在插入一个有效的查询时总是遇到问题。 使用 phpMyAdmin 它告诉我给它 NULL。 我试过这个:
$query = "INSERT INTO tbl (id, col2, col3, col4) VALUES ('NULL', ?, ?, ?)";
$stmt -> bind_param("ssi", $col2, $col3, $col4)
和这个
$query = "INSERT INTO tbl (id, col2, col3, col4) VALUES (NULL, ?, ?, ?)";
$stmt -> bind_param("ssi", $col2, $col3, $col4)
并且只给出 bind_param 3 个参数(最后 3 个)。 这些都不起作用。 我也试过这个:
$null = NULL;
$query = "INSERT INTO tbl (id, col2, col3, col4) VALUES (?, ?, ?, ?)";
$stmt -> bind_param("issi", $null, $col2, $col3, $col4);
这些都不起作用。 是否有插入此类表的标准化方法?
只需跳过id
字段,MySQL 会自动填充它:
$query = "INSERT INTO tbl (col2, col3, col4) VALUES (?, ?, ?)";
$stmt->bind_param("ssi", $col2, $col3, $col4)
如果id
字段是auto_increment
,那么不要在insert
查询中指定它:
$query = "INSERT INTO tbl (col2, col3, col4) VALUES (?, ?, ?)";
而且,当然,不要尝试将任何参数绑定到它;-)
由于它是由 MySQL 生成的,因此无需传递该列。
这应该可以工作,因为 id 是由 mysql 自动添加的(因此会增加):
$query = "INSERT INTO tbl (col2, col3, col4) VALUES (?, ?, ?)";
在某些情况下,您必须显式插入 auto_incremtnt 字段,如果是这种情况,那么您可以使用INSERT IGNORE
语句,有关它的更多信息,请参阅 mysql 手册。
这个
$query = "INSERT INTO tbl (id, col2, col3, col4) VALUES (NULL, ?, ?, ?)";
$stmt -> bind_param("ssi", $col2, $col3, $col4)
应该肯定工作。 你得到的确切错误是什么?
现在我看起来好多了,你有 $query 和 $stmt。 你之间有什么? 可能你遗漏了某些部分。
它应该是
$stmt = $mysqli->prepare("INSERT INTO tbl (id, col2, col3, col4) VALUES (NULL, ?, ?, ?)");
$stmt -> bind_param("ssi", $col2, $col3, $col4);
$stmt ->execute();
$sql=("SELECT max(id) id FROM tbl_uploads where username='{$_SESSION['username']}'");
$result_set=mysqli_query($conn,$sql) or die ("<b>Error:</b> Problem on Retrieving Image From upload folder.<br/>" . mysqli_error($con));
while($row=mysqli_fetch_array($result_set))
{
$id=$row['id']+1; // used it for increament that is not working
your code
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.