SakiManiac SakiManiac - 1 year ago 59
MySQL Question

Storing an image's URL in database (PHP / MySql)

I have just started learning PHP during this 2 last weeks, I'm trying to code a form that sends informations, including an Image to the database.
My problem being : I want to save the image on a specific folder and save only its URL on the database (Or even its name but it must be something related to the informations I inserted with the image). I managed to make all other fields work expect the image since I couldn't figure out how to make it work.
So I need help to make it work. Thanks everyone and have a nice day, I'll share my code with you here.


if(isset($_POST['regie'])) $regie=$_POST['regie'];
else $regie="";

if(isset($_POST['annonceur'])) $annonceur=$_POST['annonceur'];
else $annonceur="";

if(isset($_POST['categorie'])) $categorie=$_POST['categorie'];
else $categorie="";

if(isset($_POST['titre'])) $titre=$_POST['titre'];
else $titre="";

if(isset($_POST['image'])) $image=$_POST['image'];
else $image="";

if(isset($_POST['nombrepassage'])) $nombrepassage=$_POST['nombrepassage'];
else $nombrepassage="";

if(isset($_POST['datefin'])) $datefin=$_POST['datefin'];
else $datefin="";

if(empty($regie) OR empty($annonceur) OR empty($categorie) OR empty($titre) OR empty($image) OR empty($nombrepassage) OR empty($datefin))
echo '<font color="red">Attention, aucun champs ne peut rester vide !</font>';


$db = mysql_connect('localhost', 'root', 'test123') or die('Erreur de connexion '.mysql_error());

mysql_select_db('geomedia',$db) or die('Erreur de selection '.mysql_error());

$sql = "INSERT INTO ajout(Régie, Annonceur, Catégorie, Titre, Lien, Image, Nombre_Passage, Date_Fin ) VALUES('$regie','$annonceur','$categorie','$titre','$image','$nombrepassage','$datefin')";

mysql_query($sql) or die('Erreur SQL !'.$sql.'<br>'.mysql_error());

echo 'Vos infos ont bien été ajoutées.';


Max Max
Answer Source

You must use an <input type="file"> for that. Your form should look like this :

<form enctype="multipart/form-data" action="#" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
    Select file : <input name="my-file" type="file" />
    <input type="submit" name="send-file" />

Then you will not access the file by $_POST, but $_FILES :

Documentation :


The original name of the file on the client machine.


The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.


The size, in bytes, of the uploaded file.


The temporary filename of the file in which the uploaded file was stored on the server.


The error code associated with this file upload.

Also, you have many samples in the documentation.

File uploading in PHP should be carefully designed, because of the many security pitfalls. An example of coping with those :