这就是我所做的。要回答您的问题,请查看第二个文件末尾附近的 SELECT LAST_INSERT_ID() 的 mysql_query。请注意,我没有插入 id,而是让数据库 auto_increment。
图片是通过upload.php上传的,其中一部分是这样的:
<form>
<?php
session_start();
if (isset($error["image"])) echo '<span class="error">'.$error["image"].'</span>'; else echo 'Select an image<span class="required"> *</span>';
if ($imgVars["is_image"] == "J") {
echo '
<input type="hidden" name="image_url" value="'.$imgVars["image_url"].'">
<input type="hidden" name="image_type" value="'.$imgVars["image_type"].'">
<input type="hidden" name="is_image" value="J">
<img src="'.$imgVars["image_url"].'" width="224" height="168" alt="Image">
<p>Change image?</p>';
?>
<input type="file" name="image">
<input type="submit" name="upload" value="Upload" title="Upload your image">
</form>
然后通过process.php对上传的文件进行处理,其中一部分是这样的:
<?php
session_start();
if (!session_is_registered("error"))
session_register("error");
$error = array();
if (!session_is_registered("imgVars"))
session_register("imgVars");
foreach($_POST as $varname => $value)
$imgVars[$varname] = trim(EscapeShellCmd(stripslashes($value)));
$imgVars = array();
if ($imgVars["is_image"] != 'J') {
$imgVars["is_image"] = 'N';
if ($_FILES["image"]["size"] > 0) {
$size = GetImageSize($_FILES["image"]["tmp_name"]);
$width = $size[0];
$height = $size[1];
if(($width != 224) || ($height != 168)) {
$error["image"] = 'Image dimensions must be exactly 224 x 168 pixel!';
$imgVars["is_image"] = "N";
}
preg_match("/(\.\w+)$/",
$_FILES["image"]["name"],$match);
$imagetype = $match[1];
if (!in_array(strtolower($imagetype), array(".jpg",".jpeg",".gif",".png"))) {
$error["image"] = 'You may upload only images of type JPEG, GIF and PNG!';
$imgVars["is_image"] = "N";
}
if ($imgVars["is_image"] == "J") {
$filename = time().$imagetype;
copy($_FILES["image"]["tmp_name"], "img/".$filename);
$imgVars["image_url"] = "img/".$filename;
$imgVars["image_type"] = $imagetype;
}
} else {
$error["image"] = 'Please upload an image!';
}
}
if (count($error))
{
header('Location: upload.php');
exit();
}
// connect to database
$query = "INSERT INTO images SET image_url = '" . $imgVars["image_url"] . "';
if (!($result = @ mysql_query ($query, $connection)))
die("Your mysql error routine here.");
$rs = mysql_query("SELECT LAST_INSERT_ID()", $connection);
$lid = mysql_fetch_row($rs);
$image_id = $lid[0];
if ($imgVars["is_image"] == 'J') {
rename ($imgVars["image_url"], "img/".$image_id.$imgVars["image_type"]);
$query = "UPDATE images SET image_url = 'img/".$image_id.$imgVars["image_type"]."' WHERE image_id = '".$image_id."'";
if (!(@ mysql_query ($query, $connection)))
die("Your mysql error routine here.");
}
session_unregister("formVars");
session_unregister("fehler");
header('Location: danke.php');
exit();
?>
此代码中可能存在拼写错误或遗漏,因为我未经测试就从原始文件中翻译和修剪了它。