¿Cómo almacenar el nombre del archivo en la base de datos, con otra información al subir la imagen al servidor usando PHP?

Hola he leido muchos foros y sitios web que te dicen como subir una imagen a un servidor y he conseguido que esto funcione, puedo subir un archivo a un mi servidor pero almacenar el nombre del archivo no funciona en el siguiente ejemplo que encontre y tambien necesito crear un formulario que permita introducir mas datos a la base de datos. Estoy atascado con esto como un han hecho mucho PHP antes. He llegado al final de probar diferentes sitios web tutoriales sin mucho éxito ¿alguien podría ayudarme? Lo necesito hecho para un proyecto que estoy haciendo.

Básicamente estoy tratando de hacer un CMS que permite a los usuarios subir una foto de un miembro de la banda y tienen información almacenada sobre ellos para que pueda ser mostrado en una página web para el público para ver.


Mi tabla se parece a esto:

Field              Type             Null    Default     
id                 int(10)          No                   
nameMember         varchar(25)      No                   
bandMember         text             No                   
photo              varchar(30)      No                   
aboutMember        text             No                   
otherBands         text             No      

El formulario que quiero se verá así

   <h1>Adding a new Band Member or Affiliate</h1>
      <form method="post" action="addMember.php" enctype="multipart/form-data">
       <p>
              Please Enter the Band Members Name.
            </p>
            <p>
              Band Member or Affiliates Name:
            </p>
            <input type="text" name="nameMember"/>
            <p>
              Please Enter the Band Members Position. Example:Drums.
            </p>
            <p>
              Member's Position:
            </p>
            <input type="text" name="bandMember"/>
            <p>
              Please Upload a Photo in gif or jpeg format. The file name should be named after the Members name. If the same file name is uploaded twice it will be overwritten!
            </p>
            <p>
              Photo:
            </p>
            <input type="file" name="filep" size=35 />
            <p>
              Please Enter any other information about the band member here.
            </p>
            <p>
              Other Member Information:
            </p>
<textarea rows="10" cols="35" name="aboutMember">
</textarea>
            <p>
              Please Enter any other Bands the Member has been in.
            </p>
            <p>
              Other Bands:
            </p>
            <input type="text" name="otherBands" size=30 />
            <br/>
            <br/>
            <input TYPE="submit" title="Add data to the Database" value="Add Member"/>
          </form>

El Ejemplo que sube una Imagen al servidor y solo, es este:

<?

if ($_POST["action"] == "Load")
{
$folder = "images/";

move_uploaded_file($_FILES["filep"]["tmp_name"] , "$folder".$_FILES["filep"]["name"]);

echo "
<p align=center>File ".$_FILES["filep"]["name"]."loaded...";

$result = mysql_connect("localhost", "******", "*****") or die ("Could not save image name

Error: " . mysql_error());

mysql_select_db("project") or die("Could not select database");
mysql_query("INSERT into dbProfiles (photo) VALUES('".$_FILES['filep']['name']."')");
if($result) { echo "Image name saved into database

"; }

}

?>

Y el formulario de Ejemplos que tengo que usar es este:

<form action=addMember.php method=post enctype="multipart/form-data">
<table border="0" cellspacing="0" align=center cellpadding="3" bordercolor="#cccccc">
<tr>
<td>File:</td>
<td><input type="file" name="filep" size=45></td>
</tr>
<tr>
<td colspan=2><p align=center>
<input type=submit name=action value="Load">
</td>
</tr>
</table>
</form>

PS: Archivo de imágenes está abierto para escribir en.

Aquí está la respuesta para aquellos de ustedes buscando como yo lo hice por toda la web tratando de averiguar cómo hacer esta tarea. Subir una foto a un servidor con el nombre del archivo almacenado en una base de datos mysql y otros datos de formulario que desea en su Database. Por favor, hágamelo saber si ayudó.

En primer lugar la forma que usted necesita:


    <p>
              Please Enter the Band Members Name.
            </p>
            <p>
              Band Member or Affiliates Name:
            </p>
            <input type="text" name="nameMember"/>
            <p>
              Please Enter the Band Members Position. Example:Drums.
            </p>
            <p>
              Band Position:
            </p>
            <input type="text" name="bandMember"/>
            <p>
              Please Upload a Photo of the Member in gif or jpeg format. The file name should be named after the Members name. If the same file name is uploaded twice it will be overwritten! Maxium size of File is 35kb.
            </p>
            <p>
              Photo:
            </p>
            <input type="hidden" name="size" value="350000">
            <input type="file" name="photo"> 
            <p>
              Please Enter any other information about the band member here.
            </p>
            <p>
              Other Member Information:
            </p>
<textarea rows="10" cols="35" name="aboutMember">

            <br/>
            <br/>
            <input TYPE="submit" name="upload" title="Add data to the Database" value="Add Member"/>

Luego este código procesa los datos del formulario:

   <?php

// This is the directory where images will be saved
$target = "your directory";
$target = $target . basename( $_FILES['photo']['name']);

// This gets all the other information from the form
$name=$_POST['nameMember'];
$bandMember=$_POST['bandMember'];
$pic=($_FILES['photo']['name']);
$about=$_POST['aboutMember'];
$bands=$_POST['otherBands'];

// Connects to your Database
mysqli_connect("yourhost", "username", "password") or die(mysqli_error()) ;
mysqli_select_db("dbName") or die(mysqli_error()) ;

// Writes the information to the database
mysqli_query("INSERT INTO tableName (nameMember,bandMember,photo,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;

// Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{

// Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {

// Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?> 

Código editado de www.about.com

Comentarios (2)

Si desea introducir más datos en el formulario, sólo tiene que acceder a los datos enviados a través de $_POST.

Si dispone de

<input type="text" name="firstname" />

se accede con

$firstname = $_POST["firstname"];

A continuación, podría actualizar su línea de consulta para leer

mysql_query("INSERT INTO dbProfiles (photo,firstname)
             VALUES('{$filename}','{$firstname}')");

Nota: Filtre y desinfecte siempre los datos.

Comentarios (1)

Tu parte:

$result = mysql_connect("localhost", "******", "*****") or die ("Could not save image name

Error: " . mysql_error());

mysql_select_db("project") or die("Could not select database");
mysql_query("INSERT into dbProfiles (photo) VALUES('".$_FILES['filep']['name']."')");
if($result) { echo "Image name saved into database

";

No tiene mucho sentido, su conexión no debería llamarse $resultado, pero eso es un problema de nomenclatura, no de codificación.

Lo que es un problema de codificación es if($result), su diciendo que si se puede conectar a la base de datos, independientemente de la consulta de inserción de fallar o tener éxito que la salida "Imagen guardada en la base de datos".

Intente añadir do

$realresult = mysql_query("INSERT into dbProfiles (photo) VALUES('".$_FILES['filep']['name']."')");

y cambia el if($resultado) por $resultadoreal

Sospecho que tu consulta está fallando, ¿quizás tienes columnas adicionales o algo así?

Prueba a copiar/pegar tu consulta, sustituyendo el ".$_FILES['filep']['nombre']." por test y ejecútalo en tu navegador de consultas a ver si entra.

Comentarios (1)