簡體   English   中英

如何在數據庫中正確插入這些值

[英]How to insert these values correctly in the database

下面是將文件 (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);

如果您使用 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.";

您應該使用自動遞增的 id 來識別圖像,而不是為此使用字符串。

這將為您簡化流程,因為您只需要插入一個字段,並且自動增加的字段會自動更新。

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

ImageId 然后應該是 INT 類型的 PRIMARY KEY 與 AUTO INCREMENT 相反。 這也是設計表格的好方法。

您需要像這樣將值添加到查詢中

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

但首先要確保正確轉義這些值以避免出現任何問題。 另請注意,不建議再使用 mysql_ 函數。 而是使用 mysqli_ 等效項或更好的 PDO(使用 PDO,它將自動為您處理數據庫轉義。

你可以使用MySql Auto increment ..你不需要擔心IMG IMG2 ...等

見: 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. 要獲得X是增量值的IMGX將涉及多個 SQL 調用......而且效率不高

這就是我所做的。 要回答您的問題,請查看第二個文件末尾附近的 SELECT LAST_INSERT_ID() 的 mysql_query。 請注意,我沒有插入 id,而是讓數據庫自動遞增。

圖片是通過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();

?>

這段代碼可能有錯別字或遺漏,因為我未經測試就從原始文件中翻譯和修剪了它。

首先:在數據庫中插入值時始終使用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"])."'
          );";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM