>  기사  >  백엔드 개발  >  PHP로 업로드하는 동안 이미지 파일 이름과 기타 양식 데이터를 데이터베이스에 저장하는 방법은 무엇입니까?

PHP로 업로드하는 동안 이미지 파일 이름과 기타 양식 데이터를 데이터베이스에 저장하는 방법은 무엇입니까?

Patricia Arquette
Patricia Arquette원래의
2024-10-26 06:20:02918검색

How to Store Image File Names and Other Form Data in a Database During Uploads with PHP?

PHP를 사용하여 서버에 이미지를 업로드하는 동안 다른 정보와 함께 파일 이름을 저장하는 방법

문제:

이미지를 서버에 업로드할 때 파일 이름과 다른 양식 데이터가 데이터베이스에 저장되도록 어떻게 보장할 수 있나요?

답변:

PHP를 사용하여 서버에 이미지를 업로드하는 동안 양식의 파일 이름과 추가 정보를 저장하려면 다음 단계를 따르세요.

양식:

만들기 파일 업로드 및 저장하려는 기타 데이터에 대한 필드가 포함된 양식.

PHP 스크립트:

  1. 데이터베이스에 연결하세요.
  2. 파일 이름을 포함하여 양식에서 정보를 가져옵니다.
  3. 파일 이름을 포함하여 정보를 데이터베이스 테이블에 삽입합니다.
  4. 업로드된 이미지를 이동하려면 move_uploaded_file() 함수를 사용하세요. 의도한 목적지로 이동합니다.

다음은 예제 스크립트입니다.

<code class="php">// Database connection details
$host = 'localhost';
$user = 'username';
$password = 'password';
$database = 'database_name';

// Connect to the database
$conn = mysqli_connect($host, $user, $password, $database);

// Get the form data, including the File
$name = $_POST['nameMember'];
$position = $_POST['bandMember'];
$photo = $_FILES['photo']['name'];
$about = $_POST['aboutMember'];
$otherBands = $_POST['otherBands'];

// Insert data into the database
$sql = "INSERT INTO tableName (nameMember, bandMember, photo, aboutMember, otherBands) VALUES ('$name', '$position', '$photo', '$about', '$otherBands')";

if ($conn->query($sql) === TRUE) {
    // Upload the file to the server
    $target = "your directory" . $photo;
    if (move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
        echo "The file $photo has been uploaded, and your information has been added to the database.";
    } else {
        echo "Sorry, there was a problem uploading your file.";
    }
} else {
    echo "Error: " . $conn->error;
}

// Close the database connection
$conn->close();</code>

위 내용은 PHP로 업로드하는 동안 이미지 파일 이름과 기타 양식 데이터를 데이터베이스에 저장하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.