上传图片+图片信息从 php 表单到 mysql 数据库

uploading pictures +picture information from php form to mysql database

我有一个表单代码,可以将图片上传到我的网站并将信息保存到 mysql 数据库:

<form method='post'>
        Album Name: <input type="text" name="title" /> 
        <input type="submit" name="submit" value="create" />
    </form>
<h4>Add Photo</h4>
<form enctype="multipart/form-data" method="post">
        <?php
        require_once 'config.php'; 
    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
    if(isset($_POST['upload'])){
        $caption = $_POST['caption'];
        $albumID = $_POST['album'];
        $file = $_FILES ['file']['name'];
        $file_type = $_FILES ['file']['type'];
        $file_size = $_FILES ['file']['size'];
        $file_tmp = $_FILES ['file']['tmp_name'];
        $random_name = rand();

        if(empty($file)){
            echo "Please enter a file <br>";
        } else{
             move_uploaded_file($file_tmp, 'uploads/'.$random_name.'.jpg');
    $ret = mysqli_prepare($mysqli, "INSERT INTO photos (caption, image_url, date_taken)
    VALUES(?, ?, NOW())");
    $filename = "uploads/" + $random_name + ".jpeg";
    mysqli_stmt_bind_param($ret, "ss", $caption, $filename);
    mysqli_stmt_execute($ret);
    echo "Photo successfully uploaded!<br>";
    }
    }
    ?>
    Caption: <br>
    <input type="text" name="caption">
    <br><br>
    Select Album: <br>
    <select name="album">
    <?php
    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
    $result = $mysqli->query("SELECT * FROM albums");
    while ($row = $result->fetch_assoc()) {
        $albumID = $row['albumID'];
        $title = $row['title'];
        echo "<option value='$albumID'>$title</option>";
    }
    ?>
    </select>
    <br><br>
    Select Photo: <br>
    <input type="file" name="file">
    <br><br>
    <input type="submit" name="upload" value="Upload">
</form>

这成功地将图片上传到我的 'uploads' 文件夹以及我的 mysql 数据库,但是,我想放入图片 URL "uploads/(random name generated).jpg" 我目前的代码没有做到这一点,我的照片 table 的 'image_url' 列中记录的信息只是生成的随机数。没有开头的 "uploads/" 和结尾的“.jpg”。

我应该提到我的照片 table 的架构是: 标题,image_url,date_taken,图片 ID

非常感谢任何帮助!! 提前谢谢你

您正在使用 +(加号)符号连接,在这一行中:

$filename = "uploads/" + $random_name + ".jpeg";

PHP 使用 dots/periods 连接而不是加号,这是 JS/C 语言语法:

$filename = "uploads/" . $random_name . ".jpeg";

错误检查会指示语法错误。