如何同时将上传表主键(ID)插入信息表(ID)?

时间:2014-08-14 04:58:31

标签: php mysql

信息表查询:

CREATE TABLE `info` (
  `id_info` int(10) NOT NULL auto_increment,
  `judul_info` varchar(50) collate latin1_general_ci NOT NULL,
  `konten` varchar(255) collate latin1_general_ci NOT NULL,
  `diubah_oleh` varchar(20) collate latin1_general_ci NOT NULL,
  `id_kategori` int(10) NOT NULL,
  `tgl_buat` timestamp NOT NULL default '0000-00-00 00:00:00',
  `tgl_ubah` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
  `dibuat_oleh` varchar(20) collate latin1_general_ci NOT NULL,
  `id` int(10) NOT NULL,
  PRIMARY KEY  (`id_info`),
  KEY `id_kategori` (`id_kategori`),
  KEY `id` (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=62 ;

上传表格查询:

CREATE TABLE `upload` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `deskripsi` text,
  `filetype` varchar(200) default NULL,
  `filedata` longblob,
  `filename` varchar(200) default NULL,
  `filesize` bigint(20) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=34 ;

我想在发布新信息时插入与info.id相同的upload.id。请帮我。 这是我的源代码(对于我无法上传图片的查询而感到抱歉,我的声誉仍然很低):

<?php
include "config.php";

$id_info=$_POST['id_info'];
$judul=$_POST['judul_info'];
$konten=$_POST['konten'];
$tgl_ubah=$_POST['tgl_ubah'];
$diubah_oleh=$_POST['diubah_oleh'];
$id_kategori=$_POST['id_kategori'];

// update data in mysql database 
$sql="UPDATE info SET judul_info='$judul', konten='$konten', diubah_oleh='$diubah_oleh', id_kategori='$id_kategori' WHERE id_info='$id_info'";
$result=mysql_query($sql);

// if successfully updated. 
if($result){
echo "Telah diupdate";
echo "<BR>";
echo "<a href='list_info.php'>View result</a>";
}

else {
echo "ERROR";
}

?>

1 个答案:

答案 0 :(得分:0)

您需要在插入信息表后使用 last_insert_id() mysql_insert_id()来插入新ID,然后在下一个中使用它将记录插入上传表时查询。请参阅以下链接,了解如何使用它们。

http://dev.mysql.com/doc/apis-php/en/apis-php-function.mysql-insert-id.html http://php.net/manual/en/function.mysql-insert-id.php http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id