1

有没有一种快速的方法可以为 php mysql 上传添加一个唯一的 id - 我已经浏览了这些论坛,但希望有一个更简单的方法来实现我的目标。

本质上,我有一个完美的上传 - 我希望为每个项目添加一个产品代码,这些项目将使用 mysql 中的自动递增唯一 id 字段生成。

到目前为止,我有以下 php:

<?php include 'dbc.php'; page_protect();

if(!checkAdmin()) {header("Location: login.php");
exit();
}

$host  = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$login_path = @ereg_replace('admin','',dirname($_SERVER['PHP_SELF']));
$path   = rtrim($login_path, '/\\');

foreach($_GET as $key => $value) {
    $get[$key] = filter($value);
}

foreach($_POST as $key => $value) {
    $post[$key] = filter($value);
}   
?>

<?php 
if($_FILES['photo']) //check if we uploading a file
{
    $target = "images/furnishings/"; 
    $target = $target . basename( $_FILES['photo']['name']); 

    $title = mysql_real_escape_string($_POST['title']); 
    $desc = mysql_real_escape_string($_POST['desc']); 
    $price = mysql_real_escape_string($_POST['price']);  
    $pandp = mysql_real_escape_string($_POST['pandp']);  
    $pic = "images/furnishings/" .(mysql_real_escape_string($_FILES['photo']['name']));
    $productcode = "FUR000" .(mysql_real_escape_string($_POST['id']));
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) 
{
    mysql_query("INSERT INTO `furnishings` (`title`, `desc`, `price`, `pandp`, `photo`,`productcode`) VALUES ('$title', '$desc', '$price', '$pandp', '$pic', '$productcode')") ;     

    echo "The product has been added to the furnishings category"; 
} 
else 
{ 
    echo "Please fill out the specifications and select the respective file to upload for the main image"; 

}
} 
?> 

以及以下 HTML:

<form enctype="multipart/form-data" action="addfurn.php" method="POST">
  <table width="100%" border="2" cellpadding="5"class="myaccount">
   <tr>
       <td>Title: </td>
       <td><input type="text" name="title" /></td>
    </tr>
     <tr>
       <td>Description: </td>
       <td><input type="text" name = "desc" /></td>
     </tr>
          <tr>
       <td>Price: </td>
       <td><input type="text" name = "price" /></td>
     </tr>
        <tr>
       <td>P&amp;P: </td>
       <td><input type="text" name = "pandp" /></td>
     </tr>
     <tr>
       <td>Main Image: </td>
       <td><input type="file" name="photo" /></td>
     </tr>
     <tr>
       <td colspan="2"><input type="submit" class="CMSbutton" value="Add" /></td>
     </tr>
  </table>
</form>

现在假设一切正常 - 代码中唯一的“问题行”是:

$productcode = "FUR000" .(mysql_real_escape_string($_POST['id']));

假设由于 id 尚未生成,它无法将其添加到插入查询中 - 因此 mysql 中的表只为添加的每个新项目返回 FUR000。

有没有办法将这一行修改为 mysql 中的自动增量,类似于添加新行 - 或者我是否必须为我的 HTML 表中的每个项目包含一个唯一代码?

非常感谢任何帮助!

谢谢京东

4

2 回答 2

1

为此,您需要 2 个查询。

首先,插入没有产品代码的数据。
接下来,使用 mysql_insert_id()
最后获取 id,创建您的产品代码并使用这个新生成的 id 更新您的表

但是,我认为这样的领域没有意义。为什么不即时创建它?

于 2011-10-21T13:57:39.620 回答
0

您想使用uniqid,它会生成唯一的 ID。为了安全起见,我建议使用更多的熵。

于 2011-10-21T13:46:19.423 回答