Upload image + inscription nom dans table

Répondre


Cette question est un moyen d’empêcher des soumissions automatisées de formulaires par des robots.
Smileys
:D :) :( :o :shock: :? 8-) :lol: :x :P :oops: :cry: :evil: :twisted: :roll: :wink: :!: :?: :idea: :arrow: :| :mrgreen: =D> #-o =P~ :^o :non: :priere: 8-|
Voir plus de smileys
  Revue du sujet
 

  Étendre la vue Revue du sujet : Upload image + inscription nom dans table

par numbers » 08 déc. 2006, 09:46

La programmation PHP c'est pas forcément simple. Moi je débute à peine et dès que je fais un truc j'ai des soucis mais c'est la meilleure façon d'apprendre.

par Invité » 08 déc. 2006, 02:11

Merci mais je me perds....

Alors j ai repris le tuto d'upload du site http://www.asp-php.net/tutorial/asp-php ... php?page=2

et j ai ajouté l inscription dans la base mais ca me met come erreur
Notice: Undefined index: userfile in d:\sites\easyphp\www\so\demoupload.php on line 35
Le champ 'photo' ne peut être vide (null)
voici mon code
<?php require_once('Connections/connect.php'); ?>
<?php
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO test (photo) VALUES (%s)",
                       GetSQLValueString($_POST['userfile'], "text"));

  mysql_select_db($database_connect, $connect);
  $Result1 = mysql_query($insertSQL, $connect) or die(mysql_error());
}
?>
<HTML><BODY><CENTER>

<?
// Taille max des fichiers (octets)
$MFS=10240;
// Répertoire de stockage
$rep="pics/art/";

if(isset($_FILES['userfile'])) {
if($_FILES['userfile']['size']>0) {
   $savefile= $rep.$_FILES['userfile']['name'];
   $temp = $_FILES['userfile']['tmp_name'];
   if (move_uploaded_file($temp, $savefile)) { ?>
      <b>Votre fichier a bien été enregistré !</b>
<BR>Nom : <?echo $_FILES['userfile']['name'];?>
<BR>Taille : <?echo $_FILES['userfile']['size'];?> o
<BR>Type : <?echo $_FILES['userfile']['type'];?>
<?   } else { ?>
      <b>Erreur d'enregistrement !</b>
   <? }

} else { ?>
   <b>Trop gros fichier !</b>
   <i>( <? echo $MFS;?> octets max.)</i>
<? } 
} ?>
   
<FORM action="<?php echo $editFormAction; ?>" name="form1" METHOD="POST" ENCTYPE="multipart/form-data">
   <INPUT TYPE=HIDDEN NAME=MAX_FILE_SIZE VALUE=<? echo $MFS;?>>
   <INPUT TYPE=FILE NAME="userfile"><BR>
   <INPUT TYPE=SUBMIT value="Enregistrer le fichier">
   <input type="hidden" name="MM_insert" value="form1">
</FORM>

LISTE DES FICHIERS TELECHARGES
<BR><TABLE border>
<? $dir = opendir($rep);

while ($f = readdir($dir))
   if(is_file($rep.$f)) { ?>
      <TR>
         <TH>
            <A href="<? echo $rep.$f; ?>"
               target="_blank"><? echo $f; ?></A>
         </TH>
         <TD align=right><? echo filesize($rep.$f); ?></TD>
         <TD>
            <? echo date("d/m/Y H:i:s",filectime($rep.$f)); ?>
         </TD></TR>
   <? }

closedir($dir); ?>
</TABLE>

</CENTER></BODY></HTML>

SVP HELP !!!

PS: je ne pensais pas que cela aller etre aussi dur...

par Ultim4T0m » 07 déc. 2006, 20:57

GetSQLValueString($_POST['prix'], "double")),
GetSQLValueString(.$_FILES['photo'] ['name']));
Tu fermes deux fois la parenthèse de ton srpintf();
Ca vient peut-être de là

par numbers » 07 déc. 2006, 19:55

numérote la ligne 41 ce sera plus pratique pour visualiser le problème

Mais là en commentaire dans le code //41 à la fin ça serait cool

par arentx » 07 déc. 2006, 18:46

Merci,

Alors je viens d"essayer un truc mais ca marche pas... peut etre une erreur dans mon code :oops:
<?php require_once('Connections/connect.php'); ?>
<?php
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO article (id_cat, id_scat, `ref`, nom_art, desi, stock, prix, photo) 
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['id_catcaché'], "text"),
                       GetSQLValueString($_POST['select'], "text"),
                       GetSQLValueString($_POST['ref'], "text"),
                       GetSQLValueString($_POST['nom_art'], "text"),
                       GetSQLValueString($_POST['desi'], "text"),
                       GetSQLValueString($_POST['stock'], "text"),
                       GetSQLValueString($_POST['prix'], "double")),
					   GetSQLValueString(.$_FILES['photo'] ['name']));

  mysql_select_db($database_connect, $connect);
  $Result1 = mysql_query($insertSQL, $connect) or die(mysql_error());

  $insertGoTo = "listart.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}

$colname_Recordset1 = "-1";
if (isset($_GET['id_cat'])) {
  $colname_Recordset1 = (get_magic_quotes_gpc()) ? $_GET['id_cat'] : addslashes($_GET['id_cat']);
}
mysql_select_db($database_connect, $connect);
$query_Recordset1 = sprintf("SELECT id_scat, nom_scat FROM scat WHERE id_cat = %s ORDER BY id_scat ASC", $colname_Recordset1);
$Recordset1 = mysql_query($query_Recordset1, $connect) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);

$colname_Recordset2 = "-1";
if (isset($_GET['id_cat'])) {
  $colname_Recordset2 = (get_magic_quotes_gpc()) ? $_GET['id_cat'] : addslashes($_GET['id_cat']);
}
mysql_select_db($database_connect, $connect);
$query_Recordset2 = sprintf("SELECT * FROM cat WHERE id_cat = %s", $colname_Recordset2);
$Recordset2 = mysql_query($query_Recordset2, $connect) or die(mysql_error());
$row_Recordset2 = mysql_fetch_assoc($Recordset2);
$totalRows_Recordset2 = mysql_num_rows($Recordset2);
?>
<?php

if(isset($_FILES['photo']))
{
  // params
  unset($erreur);
  $extensions_ok = array('png', 'gif', 'jpg', 'jpeg');
  $taille_max = 100000;
  $dest_dossier = './pics/art/';
  // vérifications
  if( !in_array( substr(strrchr($_FILES['photo']['name'], '.'), 1), $extensions_ok ) )
  {
    $erreur = 'Veuillez sélectionner un fichier de type png, gif ou jpg !';  
  }
  elseif( file_exists($_FILES['photo']['tmp_name']) 
          and filesize($_FILES['photo']['tmp_name']) > $taille_max)
  {
    $erreur = 'Votre fichier doit faire moins de 500Ko !';
  }
  // copie du fichier
  if(!isset($erreur))
  {
    $dest_fichier = basename($_FILES['photo']['name']);
    // formatage nom fichier
    // enlever les accents
    $dest_fichier = strtr($dest_fichier, 'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ',
 'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
    // remplacer les caracteres autres que lettres, chiffres et point par _
    $dest_fichier = preg_replace('/([^.a-z0-1]+)/i', '_', $dest_fichier);
    // copie du fichier
    move_uploaded_file($_FILES['photo']['tmp_name'], $dest_dossier . $dest_fichier);
  }
}

?>
<html>
<head>
<title>Ajout d'article</title>
</head>

<body>
<p>&nbsp;</p>
<p><?php echo $row_Recordset2['nom_cat']; ?></p>
<p>la sous cat </p>
<form name="form1" method="POST" action="<?php echo $editFormAction; ?>">
  <p><!-- -->
    <select name="select">
      <?php
do {  
?>
      <option value="<?php echo $row_Recordset1['id_scat']?>"><?php echo $row_Recordset1['nom_scat']?></option>
      <?php
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
  $rows = mysql_num_rows($Recordset1);
  if($rows > 0) {
      mysql_data_seek($Recordset1, 0);
	  $row_Recordset1 = mysql_fetch_assoc($Recordset1);
  }
?>
    </select>
  </p>
  <p>ref :
  <input type="text" name="ref">
</p>
<p>nom :
  <input type="text" name="nom_art">
</p>
<p>désignation :
  <input type="text" name="desi">
</p>
<p>stock :
  <input type="text" name="stock">
</p>
<p>prix :
  <input type="text" name="prix">
</p>
<p>photo : 
  <input type="file" name="photo">
</p>
<p>
  <input type="submit" name="Submit" value="Envoyer">
</p>
<p>
  <input name="id_catcaché" type="hidden" value="<?php echo $row_Recordset2['id_cat']; ?>">
</p>
<input type="hidden" name="MM_insert" value="form1">
</form>
<p>&nbsp;</p>
<p>&nbsp;</p>
</body>
</html>
<?php
mysql_free_result($Recordset1);

mysql_free_result($Recordset2);
?>
Cela me met une erreur ligne 41 mais je ne sais pas pourquoi ...

par Devether » 07 déc. 2006, 18:22

si tu as dans ton formulaire :

Code : Tout sélectionner

<input type="file" name="monFichier" />
le nom du fichier que tu upload est récupérable via
$_FILES['monFichier']['name']
ensuite tu peux très bien insérer le nom dans ta base
$sql = 'INSERT INTO tb (photo) VALUES ("'.$_FILES['monFichier']['name'].'")';

Upload image + inscription nom dans table

par arentx » 07 déc. 2006, 18:11

Bonjour,

aprés avoir lu plusieurs tuto je suis perdu.... :cry:

Je cherche simplement à Uploader une image et que le nom de cette image (ex: image1.jpg) s'incrive dans le champ d'une table (ex: table "tb" champ "photo" valeur "image1.jpg)

Tout ce que j ai vu jusqu'a présent, demande d'insérer le nom obligatoirement et je voudrai une automatisation sans écrire le nom de l'image.

J'espère avoir été asser clair ... :oops:

Merci par avance de vos aides