在DB列中保存图像url路径


Save image url path in DB columns

我正在通过php表单更新注册用户的DB中的名称,电子邮件。

class.usr.php

public function update($uname,$email, $tax)
    {
    try {
    $stmt = $this->conn->prepare('UPDATE tbl_users SET userName = ?, userEmail = ? , tax = ?  WHERE userID = ? ');
    $stmt->execute(array($uname,$email, $tax , $_SESSION['userSession']));
    return $stmt->fetch();
    } catch(PDOException $e) {
        echo '<p class="bg-danger">'.$e->getMessage().'</p>';
    }

<form action="profile.php" method="POST" enctype="multipart/form-data">
Name : 
<input type="text" name="txtuname" value="<?php echo $row['userName'] ?>" /><br/>
Email :
<input type="text" name="txtemail" value="<?php echo $row['userEmail'] ?>" /><br>
Image
<input type="file" name="photo" id="fileSelect"><br> 
<input type="submit" name="submit" value="Save" />
</form>

将相关代码保存到db

<?php
$user_home = new USER();
if(!$user_home->is_logged_in())
{
    header("Location: index.php");
die();
}
if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$tax = trim($_POST['tax']); // image url path
$uid = (isset($_SESSION['userSession']) ? intval($_SESSION['userSession']) : 0);
if ($uid > 0 && $user_home->update($uname,$email, $tax, $uid))
{
    header("Location: profile1.php");
   die(); 
}
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>

在此之后,现在我通过相同的PHP表单成功上传图像到文件夹,下面的代码。

    <?php 
if(isset($_FILES["photo"]["error"])){ 
if($_FILES["photo"]["error"] > 0){ 
echo "Error: " . $_FILES["photo"]["error"] . "<br>"; 
} else{ 
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png"); 
$filename = $_FILES["photo"]["name"]; 
$filetype = $_FILES["photo"]["type"]; 
$filesize = $_FILES["photo"]["size"]; 
// Verify file extension 
$ext = pathinfo($filename, PATHINFO_EXTENSION); 
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format."); 
// Verify file size - 5MB maximum 
$maxsize = 5 * 1024 * 1024; 
if($filesize > $maxsize) die("Error: File size is larger than the allowed limit."); 
// Verify MYME type of the file 
if(in_array($filetype, $allowed)){ 
// Check whether file exists before uploading it 
if(file_exists("upload/" . $_FILES["photo"]["name"])){ 
echo $_FILES["photo"]["name"] . " is already exists."; 
} else{ 
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $_FILES["photo"]["name"]); 
echo "Your file was uploaded successfully."; 
} 
} else{ 
echo "Error: There was a problem uploading your file - please try again."; 
} 
} 
} else{ 
echo ""; 
} 
?>

现在图像只是保存在文件夹中,我需要的是我希望图像路径保存在数据库中,并将该图像路径分配给数据库中上传的用户。以便注册用户可以更新现有的图像,但不能再上传一个图像。

我试了下面的代码,但不工作:

<?php
$folder = "upload/"; 
    $file = basename( $_FILES['image']['name']); 
    $full_path = $folder.$file; 
    $tax= $full_path;
    if(in_array($filetype, $allowed)){ 
// Check whether file exists before uploading it 
if(file_exists("upload/" . $_FILES["photo"]["name"])){ 
echo $_FILES["photo"]["name"] . " is already exists."; 
} else{ 
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $_FILES["photo"]["name"]); 
echo "Your file was uploaded successfully."; 
} 
} else{ 
echo "Error: There was a problem uploading your file - please try again."; 
} 
} 
} else{ 
echo ""; 
} 
?>

db columns: userName, userEmail, tax, photo

在谷歌的帮助下我做了以上所有,我是新的php,所以请帮助我。

这是另一个解决方案:

首先手动执行此查询以添加新列:

ALTER TABLE `tbl_users` ADD `photo` VARCHAR(255) NOT NULL ;
下面是php代码:
<?php
$dbConn = new Database();
$dbConn->dbConnection();
$user_home = new USER();
function uploadUserPhoto($uid) {
    global $dbConn;
    if(isset($_FILES["photo"]["error"])) {
        if($_FILES["photo"]["error"] > 0) {
            echo "Error: " . $_FILES["photo"]["error"] . "<br>";
        } else {
            $allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
            $filename = $_FILES["photo"]["name"];
            $filetype = $_FILES["photo"]["type"];
            $filesize = $_FILES["photo"]["size"];
            $userDir = $uid;
            // Verify file extension
            $ext = pathinfo($filename, PATHINFO_EXTENSION);
            if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
            // Verify file size - 5MB maximum
            $maxsize = 5 * 1024 * 1024;
            if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
            // Verify MYME type of the file
            if(in_array($filetype, $allowed)) {
                if(!is_dir('upload/'.$uid)) {
                    mkdir('upload/'.$uid);
                }
                $photoname = time().$uid.'_photo'.'.'.$ext;
                // delete all the files in this directory
                $files = glob('upload/'.$uid.'/*'); // get all file names
                foreach($files as $file){ // iterate files
                    if(is_file($file))
                        unlink($file); // delete file
                }
                // Upload the photo
                move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $uid . '/'. $photoname);
                $updateData = array(':userID' => $uid, ':photo' => $photoname);
                $stmt = $dbConn->conn->prepare("UPDATE tbl_users SET photo=:photo WHERE userID=:uid");
                $stmt->execute($updateData);
                echo "Your file was uploaded successfully.";
            } else {
                echo "Error: There was a problem uploading your file - please try again.";
            }
        }
    } else {
        echo "";
    }
}
if(!$user_home->is_logged_in())
{
    header("Location: index.php");
    die();
}
if (isset($_POST['submit'])) {
    // new data
    $uname = $_POST['txtuname'];
    $email = $_POST['txtemail'];
    $tax = trim($_POST['tax']); // image url path
    $uid = (isset($_SESSION['userSession']) ? intval($_SESSION['userSession']) : 0);
    if ($uid > 0 && $user_home->update($uname,$email, $tax, $uid))
    {
        uploadUserPhoto($uid);
        header("Location: profile1.php");
        die();
    }
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>

$dbConnection变量,这是连接到DB,但因为我不知道你的代码的其余部分,你应该用你适当的DB连接变量替换它。

用户的照片保存在tbl_usersphoto列中,并在uploads dir中为每个用户创建子目录。子目录是userID。例如,对于userID = 1的用户,其上传路径将为uploads/1/<filename>

文件名是动态生成的-这避免了缓存上传的照片与相同的名称,例如…这是一个更好的方法。

你需要修改代码来显示照片因为现在它的文件名在DB中并且uploads中有subdir(即用户的userID)

添加保存文件的新功能,并使用全局php var $_FILES

1

在DB中添加新列来存储文件路径,命名为photo

2

为用户类添加新函数:

<?php
class User {
...
  const PATH_PHOTOS = '/path/to/photo/folder/';
  const BASE_URL = 'http://YOUR_DOMAIN_NAME:YOUR_PORT/YOUR_PATH/';
  public function add_photo($file)
  {
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $file['new_name'] = uniqid(rand(), true) . ".$ext";
    if (!$this->_upload_file($file))
      return false;
    return $this->_remove_previous_photo()->_add_file_to_db(self::PATH_PHOTOS .     basename($file['new_name']));
  }
  protected function _remove_previous_photo()
  {
    $photo = $this->get_photo();
    if ($photo)
      unlink($photo);
    return $this;
  }
  public function get_photo()
  {
    global $_SESSION;
    $stmt = $this->conn->prepare('SELECT photo FROM tbl_users WHERE userID = ?     ');
    $stmt->execute(array($_SESSION['userSession']));
    $result = $stmt->fetch();
    return reset($result);
  }
  public function get_photo_url()
  {
    $pathInfo = pathinfo($this->get_photo());
    $last_dir = end(explode(DIRECTORY_SEPARATOR, $pathInfo['dirname']));
    return self::BASE_URL . "$last_dir/" . basename($this->get_photo());
  }
  protected function _upload_file($file)
  {
    $uploadfile = self::PATH_PHOTOS . $file['new_name'];
    return move_uploaded_file($file['tmp_name'], $uploadfile);
  }
  protected function _add_file_to_db($file_path)
  {
    try {
      $stmt = $this->conn->prepare('UPDATE tbl_users SET photo = ? WHERE userID = ? ');
      return $stmt->execute(array($file_path, $_SESSION['userSession']));
    } catch (PDOException $e) {
      echo '<p class="bg-danger">' . $e->getMessage() . '</p>';
    }
  }
...
}
?>

3 主文件应该像这样:

<?php
$user_home = new USER();
if(!$user_home->is_logged_in())
{
    header("Location: index.php");
die();
}
if (isset($_POST['submit'])) {
// new data
$uname = $_POST['txtuname'];
$email = $_POST['txtemail'];
$tax = trim($_POST['tax']); // image url path
$uid = (isset($_SESSION['userSession']) ? intval($_SESSION['userSession']) : 0);
if ($uid > 0 && $user_home->update($uname,$email, $tax, $uid) && $user_home->add_photo($_FILES['photo']))
{
    header("Location: profile1.php");
   die(); 
}
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>

希望能有所帮助