Jak*_*son 5 php mysql mysql-insert-id
我发誓我已倾倒并倾倒在本网站和其他人的所有其他类似问题......但我想我只是遗漏了一些东西.希望有人可以指出一个愚蠢的错误,我的大脑正在躲避我.:)
我的脚本将表单中的值插入名为"notes"的表中
此时,它通过名为newRelationship的函数在名为"relationships"的表中创建两个条目.
变量"$ note_id"的值通过我的mysql_insert_id()填充; 并传入上述功能.
执行代码时,条目成功添加到"notes","id"列使用auto_increment赋予适当的值.
接下来,将两个条目添加到"关系"表中(正如它们所应).
但是,我的mysql_insert_id()不断推出值为"0"而不是新的行id.
对于我的生活,我无法弄清楚我做错了什么.我甚至尝试从头开始创建一个具有相同结果的新表.踢球者是我在项目的其他文件中使用几乎完全相同的代码而没有任何问题.有谁看到我做错了什么?
有问题的代码
if ($user->is_loaded())
{
if($_POST['project_id']) {
$project_id = $_post['project_id'];
$long_note = $_POST['long_note'];
$created_by = $_POST['created_by'];
$note_sql="INSERT INTO notes (`long_note`, `added`, `created_by`) VALUES ('$long_note', '$timenow', '$created_by')";
if (!mysql_query($note_sql,$con))
{
die('Error: ' . mysql_error($note_sql));
}
else {
echo "note created Creating relationship ";
$note_id = mysql_insert_id();
echo $note_id;
newRelationship($project_id, "project", $note_id, "note");
newRelationship($client_id, "client", $note_id, "note");
echo "note added successfuly";
}
Run Code Online (Sandbox Code Playgroud)
而我的功能
function newRelationship($parent_id, $parent_type, $child_id, $child_type)
{
global $sql, $con, $timenow;
$relationship_sql="INSERT INTO `relationships` (`parent_id`, `parent_type`, `child_id`, `child_type`) VALUES ('$parent_id', '$parent_type', '$child_id', '$child_type');";
if (!mysql_query($relationship_sql,$con))
{
die('Error: ' . mysql_error($relationship_sql));
}
else {
echo $parent_type." ".$parent_id." realationship with ".$child_type." ".$child_id." successful ";
}
}
Run Code Online (Sandbox Code Playgroud)
Per @ jack的建议是我的笔记表的sql
CREATE TABLE `notes` (
`id` int(10) unsigned zerofill NOT NULL AUTO_INCREMENT,
`contact_id` int(10) NOT NULL,
`client_id` int(10) NOT NULL,
`status` text NOT NULL,
`long_note` text NOT NULL,
`added` int(11) NOT NULL,
`modified` int(11) NOT NULL,
`edit_by` int(10) NOT NULL,
`short_note` text NOT NULL,
`created_by` int(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=295 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC
Run Code Online (Sandbox Code Playgroud)
根据文件:
上次查询成功时为AUTO_INCREMENT列生成的ID,如果上一个查询未生成AUTO_INCREMENT值,则为0;如果未建立MySQL连接,则为FALSE.
该文档指出它只能0在上次执行的查询未生成AUTO_INCREMENT值时返回,这应该意味着您的PRIMARY KEY列notes未正确设置auto_increment.我建议仔细检查PRIMARY KEY列notes 是否实际设置为auto_increment(从不伤害再次检查!).
查看示例代码,您可以mysql_insert_id()在插入后立即调用,因此不应该在两者之间存在任何冲突查询以使结果偏斜.
我看到的唯一可能导致问题的是你将MySQL资源传递给mysql_query(),但不是mysql_insert_id():
if (!mysql_query($note_sql,$con))
...
$note_id = mysql_insert_id();
Run Code Online (Sandbox Code Playgroud)
由于此原因,资源可能存在冲突.尝试将您的通话更新为:
$note_id = mysql_insert_id($con);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12441 次 |
| 最近记录: |