【问题标题】:How to insert these values correctly in the database如何在数据库中正确插入这些值
【发布时间】:2012-04-26 17:35:01
【问题描述】:

以下是将文件 (fileImage) 上传到文件夹 (ImageFiles) 的部分代码。但我还想做的是使用 INSERT VALUES 代码将文件位置(文件上传到的位置)插入数据库。我希望将文件位置插入“ImageFile”字段,对于“ImageId”,我希望它显示字符串“IMG”,然后在字符串后面包含一个数字。例如:

在我的数据库表中,如果它是这样的:

ImageId     ImageFile

IMG1        ImageFiles/penguins.png
IMG2        ImageFiles/desert.png
IMG3        ImageFiles/jellyfish.jpg

然后,如果我将文件从我的计算机“tulips.png”上传到 ImageFiles 文件夹中,那么它应该在数据库中插入如下值:

ImageId    ImageFile

IMG4       ImageFiles/tulips.png

但是如何编码呢?以下是我目前成功上传文件的代码,并且仅包含 INSERT VALUES 的部分编码:

      move_uploaded_file($_FILES["fileImage"]["tmp_name"],
      "ImageFiles/" . $_FILES["fileImage"]["name"]);
      $result = 1;

      $imagesql = "INSERT INTO Image (ImageId, ImageFile) 
    VALUES ("");

mysql_query($imagesql);

【问题讨论】:

  • ImageId 行实际上是用 IMG[某个数字] 命名的吗?
  • 是的,它是用 IMG[一些数字] 命名的

标签: php mysql


【解决方案1】:

如果您使用 PHP 的 PDO 对象,它将简化您的代码并同时使其更安全(通过使用准备好的语句)。

下面是一个示例,说明您将如何做到这一点:

首先,将您的 ID 存储为 AUTO_INCREMENT-ed INT 而不是“IMG#”,因为这会使事情变得更容易(然后您不需要插入 ID 值)

DROP TABLE IF EXISTS tbl_img_store;
CREATE TABLE tbl_img_store(
    id INT NOT NULL AUTO_INCREMENT,
    PRIMARY KEY(id),
    filename VARCHAR(25) --increase this if you think you need to
) ENGINE=InnoDB;

另外,创建一个表来存储配置设置以使您的数据库更高效:

DROP TABLE IF EXISTS tbl_img_config;
CREATE TABLE tbl_img_config(
    img_path VARCHAR(50)
);
INSERT INTO tbl_img_config (img_path) VALUES ("http://img.mysite.com/?i=");

现在回到 PHP,您可以像这样快速插入大量图像:

# Create a DB connection
$db = new PDO("mysql:host=X.X.X.X;dbname=mydb", $user, $pass);

# Compile an array of image paths
$img1path = "img1.png";
$img2path = "img2.png";
$img3path = "img3.png";
$images = array($img1path, $img2path, $img3path);

# Create a query to insert the paths to the db
$sql = "INSERT INTO tbl_img_store (filename) VALUES (?),(?),(?);";
$query = $db->prepare($sql);
$query->execute($images);

# Check rows affected
$rows = $query->rowCount();
echo "$rows images were saved.";

【讨论】:

    【解决方案2】:

    您应该使用自动递增的 id 来识别图像,而不是使用字符串。

    这将为您简化流程,因为您只需插入单个字段,自动增加的字段会自动更新。

    $imagesql = "INSERT INTO Image (ImageFile) VALUES ('ImageFiles/".mysql_real_escape_string($_FILES['fileImage']['name'])."')";
    

    ImageId 然后应该是 INT 类型,作为 PRIMARY KEY 和 AUTO INCREMENT 代替。这也是设计表格的好方法。

    【讨论】:

      【解决方案3】:

      您需要像这样将值添加到查询中

      $imagesql = "INSERT INTO Image (ImageId, ImageFile) 
      VALUES ('$imageName','$imageFile');";
      

      但首先要确保正确转义值以避免任何问题。另请注意,不建议再使用 mysql_ 函数。而是使用 mysqli_ 等价物或更好的 PDO(使用 PDO,它会自动为您处理数据库转义。

      【讨论】:

        【解决方案4】:

        你可以使用MySql自动增量..你不用担心IMGIMG2...等

        见:http://dev.mysql.com/doc/refman/5.5/en/example-auto-increment.html

        示例:

        假设:ImageId 是一个自动递增字段

        http://dev.mysql.com/doc/refman/5.5/en/example-auto-increment.html

        $tmpName = $_FILES ["fileImage"] ["tmp_name"];
        $fileName = $_FILES ["fileImage"] ["tmp_name"];
        
        move_uploaded_file ( $tmpName, $fileName );
        $sql = "INSERT INTO Image (ImageId, ImageFile)   VALUES (NULL,'%s');";
        mysql_query ( sprintf ( $sql, mysql_real_escape_string ( $fileName ) ) );
        

        当你想得到你的图片时

        $sql = "SELECT ImageId, ImageFile FROM Image";
        $result = mysql_query ( $sql );
        while ( $row = mysql_fetch_assoc ( $result ) ) {
            echo "IMG", $row ["ImageId"], " = ", 'ImageFiles/'  , $row ["ImageFile"], PHP_EOL;
        }
        

        你应该使用这个的原因

        A. IMGImageFiles/ 不断保存它们几次效率不高

        B.基于integer 的id 也会比varchar 更快,并且在`JOIN

        上表现更好

        C.要获得IMGX 其中X 是增量值将涉及多个SQL 调用.. 效率不高

        【讨论】:

        • 嗨,ImageId 不是自动递增的,它是一个 varchar。它应该始终显示字符串“IMG”,但在字符串末尾会显示下一个数字,例如如果最后一个 ImageId 是 'IMG3',那么下一个 ImageId 应该是 'IMG4',然后下一个是 'IMG5' 等等
        【解决方案5】:

        这就是我所做的。要回答您的问题,请查看第二个文件末尾附近的 mysql_query for SELECT LAST_INSERT_ID()。请注意,我没有插入 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();
        
        ?>
        

        此代码中可能存在拼写错误或遗漏,因为我未经测试就从原始文件中翻译和修剪了它。

        【讨论】:

          【解决方案6】:

          首先:在数据库中插入值时始终使用mysql_real_escape_string

          那么:

          $query = "INSERT INTO `Image` (`ImageId`, `ImageFile`) 
                    VALUES ('".mysql_real_escape_string($_FILES["fileImage"]["tmp_name"])."','".
                               mysql_real_escape_string($_FILES["fileImage"]["name"])."'
                    );";
          

          【讨论】:

          • 这会将临时文件名添加为不是 OP 想要的 ImageId?
          猜你喜欢
          • 1970-01-01
          • 2022-01-19
          • 1970-01-01
          • 1970-01-01
          • 2012-12-25
          • 1970-01-01
          • 2014-11-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多