laurent vignaux Posted April 10, 2013 Share Posted April 10, 2013 Hello Larry, i bought a lot of your books (php/ sql 4th dynamic site, javascript ) and evidently they are greats and clever. So, i imagine with the first ex E-commerce to add an image at the content of add_page. In the db table 'page' i create a row 'image' with VARCHAR 50 NULL, because If the user don't add an image the db will be always right. For the form, with radio button $_POST['image'] value = yes value=no; My problem is about the realisation in php. I'am beginner with php and i don't find the good idea for resolve this. You are certainly an advice to built this. thanks cordially Link to comment Share on other sites More sharing options...
margaux Posted April 10, 2013 Share Posted April 10, 2013 There's a chapter in the php/mysql for dynamic sites which goes through using a form to upload an image (You probably want to read that book first before you tackle Effortless Ecommerce). You can store the name of and file path to the image in your database and the actual image in another folder. Strictly speaking you don't need a radio button in your form as you can check the global $_FILES variable to see if a file has indeed been uploaded. With the radio button you have extra checking - what if a user checks yes but there is no file or checks no and there is a file? But maybe I haven't understood what you are trying to do. Link to comment Share on other sites More sharing options...
laurent vignaux Posted April 10, 2013 Author Share Posted April 10, 2013 Hello Margaux thanks for reply i own this book php/mysql and upload a photo is ok for my test, my table 'page' insert the filename and display it in action. In fact, with the only form of the addPage.php, i propose with the radio button to add or not an image to the table 'page' of the bd. My problem is : if the user check the button YES, the image is insert in table db . if the user check NO, no image is insert in the table and as my row 'image' NULL in my db it's ok. i don't know write this action with a code if/else and perhaps isn't the good action. Thanks if you think you could help me cordially Link to comment Share on other sites More sharing options...
HartleySan Posted April 10, 2013 Share Posted April 10, 2013 It's a bit hard to help you without more information/code, but you might want to do something like the following: First, let's imagine that you have the following markup: <input type="radio" id="add_image_yes" name="add_image" value="yes"> Yes <input type="radio" id="add_image_no" name="add_image" value="no"> No Then on the PHP side, you could verify the value as follows as well as write the necessary query depending on the selected radio button: if (isset($_POST['add_image']) && $_POST['add_image'] === 'yes') { // Move file and give it a new name. Let's imagine that this path/name is now stored in the $file_name variable. $q = "INSERT INTO pages (file_name) VALUES ('$file_name');"; // Do whatever else you need to do to make the actual insert, etc. } else if (isset($_POST['add_image']) && $_POST['add_image'] === 'no') { $q = "INSERT INTO pages (file_name) VALUES (NULL);"; // Do whatever else you need to do to make the actual insert, etc. } Does that make sense? Also, please note that there may be additional columns present in your INSERT queries, but I'm providing the above code for demonstration purposes. Lastly, make sure the appropriate column in your pages table supports NULL values, or else you will run into problems. Thanks. Edit: margaux, my apologies if I stepped on your toes here. I debated coming in and attempting to answer Laurent's question since you had already contributed to the thread. 1 Link to comment Share on other sites More sharing options...
laurent vignaux Posted April 11, 2013 Author Share Posted April 11, 2013 hello HartleySan, sorry i'm reply late, i don't work today in my home. your reply make sense. I test this proposition. Rapidly i can record with image but not without. see my script is longer but certainly an error is inside I work this solution Thanks cordially to help me and for your advice Laurent ////////// <?php require ('./aincs/config.inc.php'); redirect_invalid_user('user_admin'); // Include the header file: $page_title = 'Ajouter une recette'; include ('./aincs/header.html'); require (MYSQL); $add_page_errors = array(); if($_SERVER['REQUEST_METHOD'] == 'POST') { if(empty($_POST['title'])) { $add_page_errors['title']= 'SVP, écrivez un titre'; } if(filter_var($_POST['category'], FILTER_VALIDATE_INT, array('min_range'=>1) ) ) { $cat = $_POST['category']; }else{ $add_page_errors['category'] = 'SVP, selectionnez une catégorie'; } if(empty($_POST['description'])) { $add_page_errors['description']= 'SVP, écrivez une description'; } if(empty($_POST['content'])) { $add_page_errors['content']= 'SVP, écrivez la recette'; } /* YOUR PROPOSITION */ if (isset($_POST['add_image']) && $_POST['add_image'] === 'yes') { // Move file and give it a new name. Let's imagine that this path/name is now stored in the $file_name variable. // Check for an image: if ( is_uploaded_file ($_FILES['image']['tmp_name']) && ($_FILES['image']['error'] == UPLOAD_ERR_OK)) { $file = $_FILES['image']; $size = ROUND($file['size']/1024); // Validate the file size: if ($size > 512) { $add_page_errors['image'] = 'The uploaded file was too large.'; } // Validate the file type: $allowed_mime = array ('image/gif', 'image/pjpeg', 'image/jpeg', 'image/JPG', 'image/X-PNG', 'image/PNG', 'image/png', 'image/x-png'); $allowed_extensions = array ('.jpg', '.gif', '.png', 'jpeg'); $image_info = getimagesize($file['tmp_name']); $ext = substr($file['name'], -4); if ( (!in_array($file['type'], $allowed_mime)) || (!in_array($image_info['mime'], $allowed_mime) ) || (!in_array($ext, $allowed_extensions) ) ) { $add_page_errors['image'] = 'The uploaded file was not of the proper type.'; } // Move the file over, if no problems: if (!array_key_exists('image', $add_page_errors)) { // Create a new name for the file: $new_name = (string) sha1($file['name'] . uniqid('',true)); // Add the extension: $new_name .= ((substr($ext, 0, 1) != '.') ? ".{$ext}" : $ext); // Move the file to its proper folder but add _tmp, just in case: $dest = "./uploads/$new_name"; if (move_uploaded_file($file['tmp_name'], $dest)) { // Store the data in the session for later use: $_SESSION['image']['new_name'] = $new_name; $_SESSION['image']['file_name'] = $file['name']; // Print a message: echo '<section><article><h4>The file has been uploaded!</h4></article></section>'; } else { trigger_error('The file could not be moved.'); unlink ($file['tmp_name']); } } // End of array_key_exists() IF. } elseif (!isset($_SESSION['image'])) { // No current or previous uploaded file. switch ($_FILES['image']['error']) { case 1: case 2: $add_page_errors['image'] = 'The uploaded file was too large.'; break; case 3: $add_page_errors['image'] = 'The file was only partially uploaded.'; break; case 6: case 7: case 8: $add_page_errors['image'] = 'The file could not be uploaded due to a system error.'; break; case 4: default: $add_page_errors['image'] = 'No file was uploaded.'; break; } // End of SWITCH. } // End of $_FILES IF-ELSEIF-ELSE. if(empty($add_page_errors)) { //$q ="INSERT INTO pages (category_id, title, description, content, image) VALUES($cat, '$t','$d', '$c', '$file')"; $q= 'INSERT INTO pages (category_id, title, description, content, image ) VALUES(?,?,?,?,?)'; $stmt = mysqli_prepare($dbc,$q); if(!$stmt) echo mysqli_stmt_error($stmt); mysqli_stmt_bind_param($stmt,'issss',$_POST['category'], $t, $d,$c,$_SESSION['image']['new_name']); $t= strip_tags($_POST['title']); $d= strip_tags($_POST['description']); $allowed='<div><p><span><br><a><img><h1><h2><h3><h4><ul><ol><li><blockquote>'; $c= strip_tags($_POST['content'], $allowed); mysqli_stmt_execute($stmt); //$r = mysqli_query($dbc,$q); if(mysqli_stmt_affected_rows($stmt) == 1){ echo'<section><article><h4>La recette a été ajoutée</h4></article></section>'; $_POST =array(); $_FILES = array(); unset($file, $_SESSION['image']); }else{ trigger_error('la page n\'a pas pu être enregistrée'); unlink($dest); } }//enderrorif }else{ unset($_SESSION['image']); } //YOUR PROPOSITION end / } else if (isset($_POST['add_image']) && $_POST['add_image'] === 'no') { //$q = "INSERT INTO pages (file_name) VALUES (NULL);"; // Do whatever else you need to do to make the actual insert, etc. if(empty($add_page_errors)) { //$q ="INSERT INTO pages (category_id, title, description, content, image) VALUES($cat, '$t','$d', '$c', '$file')"; $q= 'INSERT INTO pages (category_id, title, description, content, image ) VALUES(?,?,?,?, NULL)'; $stmt = mysqli_prepare($dbc,$q); if(!$stmt) echo mysqli_stmt_error($stmt); mysqli_stmt_bind_param($stmt,'issss',$_POST['category'], $t, $d,$c, $i); $t= strip_tags($_POST['title']); $d= strip_tags($_POST['description']); $allowed='<div><p><span><br><a><img><h1><h2><h3><h4><ul><ol><li><blockquote>'; $c= strip_tags($_POST['content'], $allowed); $i = NULL; mysqli_stmt_execute($stmt); //$r = mysqli_query($dbc,$q); if(mysqli_stmt_affected_rows($stmt) == 1){ echo'<section><article><h4>La recette a été ajoutée</h4></article></section>'; $_POST =array(); }else{ trigger_error('la page n\'a pas pu être enregistrée'); } }//enderrorif } require('./aincs/form_functions.inc.php'); ?> <section> <article> <h3>Ajouter une recette</h3> <form method="post" enctype="multipart/form-data" action="add_page.php" accept-charset="utf-8" id="form-page" > <input type="hidden" name="MAX_FILE_SIZE" value="524288" /> <fieldset> <ul> <li><label for="title"><strong>Title</strong></label> <?php create_form_input('title', 'text', $add_page_errors); ?> </li> <li><label for="category">Catégorie</label> <select name="category"<?php if(array_key_exists('category', $add_page_errors))echo 'class="error"';?>><option>Selection</option> <?php // $q = "SELECT id, category FROM categories ORDER BY category ASC"; $r = mysqli_query($dbc, $q); while ($row = mysqli_fetch_array($r, MYSQLI_NUM)) { echo "<option value=\"$row[0]\""; // if (isset($_POST['category']) && ($_POST['category'] == $row[0])) echo 'selected="selected"'; echo ">$row[1]</option>\n"; } ?> </select> <?php if(array_key_exists('category', $add_page_errors)) echo'<span class="error">' .$add_page_errors['category'].'</span>'; ?> </li> <li> <label for="description">Resumé</label> <?php create_form_input('description', 'textarea',$add_page_errors); ?> </li> <li> <label for="content">Recette</label> <?php create_form_input('content', 'textarea',$add_page_errors); ?> </li> <li> <label for="image">Une photo</label> <input type="radio" id="add_image_yes" name="add_image" value="yes"> Yes <li> <label for="image">Image</label> <?php if(array_key_exists('image', $add_page_errors)){ echo '<span class="error">'.$add_page_errors['image'].'</span> <input type="file" name="image" class="error" />'; }else{ echo '<input type="file" name="image" />'; if( isset($_SESSION['image'])) { echo "<br />Currently '{$_SESSION['image']['file_name']}'"; } } ?> </li> <input type="radio" id="add_image_no" name="add_image" value="no"> No </li> <li> <input type="submit" name="submit_button" id="submit_button" value="Ajouter cette recette" class="formbutton"/> </li> </ul> </fieldset> </form> </article> </section> Link to comment Share on other sites More sharing options...
HartleySan Posted April 11, 2013 Share Posted April 11, 2013 That's a lot of code to go through. Could you please try some basic debugging yourself and try to narrow things down a bit? Also, please use the code formatting tags (the less than and greater than symbols button) to format the code and make it easier to read. Thank you. Link to comment Share on other sites More sharing options...
laurent vignaux Posted April 12, 2013 Author Share Posted April 12, 2013 } else if (isset($_POST['add_image']) && $_POST['add_image'] === 'no') { //$q = "INSERT INTO pages (file_name) VALUES (NULL);"; // Do whatever else you need to do to make the actual insert, etc. if(empty($add_page_errors)) { //$q ="INSERT INTO pages (category_id, title, description, content, image) VALUES($cat, '$t','$d', '$c', '$file')"; $q= 'INSERT INTO pages (category_id, title, description, content, image ) VALUES(?,?,?,?, NULL)'; $stmt = mysqli_prepare($dbc,$q); if(!$stmt) echo mysqli_stmt_error($stmt); mysqli_stmt_bind_param($stmt,'issss',$_POST['category'], $t, $d,$c, $i); $t= strip_tags($_POST['title']); $d= strip_tags($_POST['description']); $allowed='<div><p><span><br><a><img><h1><h2><h3><h4><ul><ol><li><blockquote>'; $c= strip_tags($_POST['content'], $allowed); $i = NULL; mysqli_stmt_execute($stmt); //$r = mysqli_query($dbc,$q); if(mysqli_stmt_affected_rows($stmt) == 1){ echo'<section><article><h4>La recette a été ajoutée</h4></article></section>'; $_POST =array(); }else{ trigger_error('la page n\'a pas pu être enregistrée'); } }//enderrorif } Hello HartleySan, Yes it's true it's a long code. i think that the error is in this part of the script. I could test this section tomorow, i work on another projet today. Thanks Link to comment Share on other sites More sharing options...
margaux Posted April 12, 2013 Share Posted April 12, 2013 do you get any error message or just not the result you expected? @HartleySan - not stepping on my toes in any way! Its all about providing helpful info when you can. Thanks for asking though. Link to comment Share on other sites More sharing options...
HartleySan Posted April 13, 2013 Share Posted April 13, 2013 One problem I can immediately see is that you're attempting to insert four values with the query string (i.e., there are four question marks), but with the mysqli_stmt_bind_param function, you are attempting to bind five parameters, which will cause an error. If the image column will always be NULL (and not a question mark), then you should not attempt to bind a variable to it. I'm not sure if that's the only problem, but please try to resolve that first and see where it gets you. Link to comment Share on other sites More sharing options...
laurent vignaux Posted April 13, 2013 Author Share Posted April 13, 2013 Hello Hartley and Margaux, it's great, the script run. After few hours testing and testing if find a solution. i test first add_image === no with this own db query and after add_image ===yes with this personnal db query. Certainly, it's possible to do much better, more concis but it's match. And for me it's well. i see you my "final script". It's sooooo long Thanks a lot for your patient. Cordially, Laurent <?php require ('./aincs/config.inc.php'); redirect_invalid_user('user_admin'); $page_title = 'Ajouter une recette'; include ('./aincs/header.html'); require (MYSQL); $add_page_errors = array(); if ($_SERVER['REQUEST_METHOD'] == 'POST') { //first NO image if (isset($_POST['add_image']) && $_POST['add_image'] === 'no' ) { if(empty($_POST['title'])) { $add_page_errors['title']= 'SVP, écrivez un titreNO'; } if(filter_var($_POST['category'], FILTER_VALIDATE_INT, array('min_range'=>1) ) ) { $cat = $_POST['category']; }else{ $add_page_errors['category'] = 'SVP, selectionnez une catégorieNO'; } if(empty($_POST['description'])) { $add_page_errors['description']= 'SVP, écrivez une descriptionNO'; } if(empty($_POST['content'])) { $add_page_errors['content']= 'SVP, écrivez la recetteNO'; } if(empty($add_page_errors)) { $q= 'INSERT INTO pages (category_id, title, description, content ) VALUES(?,?,?,?)'; $stmt = mysqli_prepare($dbc,$q); if(!$stmt) echo mysqli_stmt_error($stmt); mysqli_stmt_bind_param($stmt,'isss',$_POST['category'], $t, $d,$c); $t= strip_tags($_POST['title']); $d= strip_tags($_POST['description']); $allowed='<div><p><span><br><a><img><h1><h2><h3><h4><ul><ol><li><blockquote>'; $c= strip_tags($_POST['content'], $allowed); mysqli_stmt_execute($stmt); //$r = mysqli_query($dbc,$q); if(mysqli_stmt_affected_rows($stmt) == 1){ echo'<section><article><h4>La recette a été ajoutée</h4></article></section>'; $_POST =array(); }else{ trigger_error('la page n\'a pas pu être enregistrée'); } }//enderrorif //if image Yes } elseif(isset($_POST['add_image']) && $_POST['add_image'] === 'yes'){ if(empty($_POST['title'])) { $add_page_errors['title']= 'SVP, écrivez un titreYES'; } if(filter_var($_POST['category'], FILTER_VALIDATE_INT, array('min_range'=>1) ) ) { $cat = $_POST['category']; }else{ $add_page_errors['category'] = 'SVP, selectionnez une catégorieYES'; } if(empty($_POST['description'])) { $add_page_errors['description']= 'SVP, écrivez une descriptionYES'; } if(empty($_POST['content'])) { $add_page_errors['content']= 'SVP, écrivez la recetteYES'; } // Check for an image: if ( is_uploaded_file ($_FILES['image']['tmp_name']) && ($_FILES['image']['error'] == UPLOAD_ERR_OK)) { $file = $_FILES['image']; $size = ROUND($file['size']/1024); if ($size > 512) { $add_page_errors['image'] = 'The uploaded file was too large.'; } $allowed_mime = array ('image/gif', 'image/pjpeg', 'image/jpeg', 'image/JPG', 'image/X-PNG', 'image/PNG', 'image/png', 'image/x-png'); $allowed_extensions = array ('.jpg', '.gif', '.png', 'jpeg'); $image_info = getimagesize($file['tmp_name']); $ext = substr($file['name'], -4); if ( (!in_array($file['type'], $allowed_mime)) || (!in_array($image_info['mime'], $allowed_mime) ) || (!in_array($ext, $allowed_extensions) ) ) { $add_page_errors['image'] = 'The uploaded file was not of the proper type.'; } if (!array_key_exists('image', $add_page_errors)) { $new_name = (string) sha1($file['name'] . uniqid('',true)); $new_name .= ((substr($ext, 0, 1) != '.') ? ".{$ext}" : $ext); $dest = "./uploads/$new_name"; if (move_uploaded_file($file['tmp_name'], $dest)) { // Store the data in the session for later use: $_SESSION['image']['new_name'] = $new_name; $_SESSION['image']['file_name'] = $file['name']; // Print a message: echo '<section><article><h4>The file has been uploaded!</h4></article></section>'; } else { trigger_error('The file could not be moved.'); unlink ($file['tmp_name']); } } // End of array_key_exists() IF. } elseif (!isset($_SESSION['image'])) { // No current or previous uploaded file. switch ($_FILES['image']['error']) { case 1: case 2: $add_page_errors['image'] = 'The uploaded file was too large.'; break; case 3: $add_page_errors['image'] = 'The file was only partially uploaded.'; break; case 6: case 7: case 8: $add_page_errors['image'] = 'The file could not be uploaded due to a system error.'; break; case 4: default: $add_page_errors['image'] = 'No file was uploaded.'; break; } // End of SWITCH. } // End of $_FILES IF-ELSEIF-ELSE. if(empty($add_page_errors)) { $q= 'INSERT INTO pages (category_id, title, description, content, image ) VALUES(?,?,?,?,?)'; $stmt = mysqli_prepare($dbc,$q); if(!$stmt) echo mysqli_stmt_error($stmt); mysqli_stmt_bind_param($stmt,'issss',$_POST['category'], $t, $d,$c,$_SESSION['image']['new_name']); $t= strip_tags($_POST['title']); $d= strip_tags($_POST['description']); $allowed='<div><p><span><br><a><img><h1><h2><h3><h4><ul><ol><li><blockquote>'; $c= strip_tags($_POST['content'], $allowed); mysqli_stmt_execute($stmt); if(mysqli_stmt_affected_rows($stmt) == 1){ echo'<section><article><h4>La recette a été ajoutée</h4></article></section>'; $_POST =array(); $_FILES = array(); unset($file, $_SESSION['image']); }else{ trigger_error('la page n\'a pas pu être enregistrée'); unlink($dest); } }//enderrorif }else{ unset($_SESSION['image']); } } require('./aincs/form_functions.inc.php'); ?> <section> <article> <h3>Ajouter une recette</h3> <form method="post" enctype="multipart/form-data" action="add_page.php" accept-charset="utf-8" id="form-page" > <input type="hidden" name="MAX_FILE_SIZE" value="524288" /> <fieldset> <ul> <li><label for="title"><strong>Title</strong></label> <?php create_form_input('title', 'text', $add_page_errors); ?> </li> <li><label for="category">Catégorie</label> <select name="category"<?php if(array_key_exists('category', $add_page_errors))echo 'class="error"';?>><option>Selection</option> <?php // $q = "SELECT id, category FROM categories ORDER BY category ASC"; $r = mysqli_query($dbc, $q); while ($row = mysqli_fetch_array($r, MYSQLI_NUM)) { echo "<option value=\"$row[0]\""; // if (isset($_POST['category']) && ($_POST['category'] == $row[0])) echo 'selected="selected"'; echo ">$row[1]</option>\n"; } ?> </select> <?php if(array_key_exists('category', $add_page_errors)) echo'<span class="error">' .$add_page_errors['category'].'</span>'; ?> </li> <li> <label for="description">Resumé</label> <?php create_form_input('description', 'textarea',$add_page_errors); ?> </li> <li> <label for="content">Recette</label> <?php create_form_input('content', 'textarea',$add_page_errors); ?> </li> <li> <label for="add_image">Vous pouvez choisir</label> <ul> <li> <label for="add_image">Avec photo</label> <input type="radio" id="add_image_yes" name="add_image" value="yes"> <ul> <li> <label for="image">Image</label> <?php if(array_key_exists('image', $add_page_errors)){ echo '<span class="error">'.$add_page_errors['image'].'</span> <input type="file" name="image" class="error" />'; }else{ echo '<input type="file" name="image" />'; if( isset($_SESSION['image'])) { echo "<br />Currently '{$_SESSION['image']['file_name']}'"; } } ?> </li> </ul> </li> <li> <label for="add_image">Sans photo</label> <input type="radio" id="add_image_no" name="add_image" value="no"> </li> </ul> <li> <input type="submit" name="submit_button" id="submit_button" value="Ajouter cette recette" class="formbutton"/> </li> </ul> </fieldset> </form> </article> </section> <script src="./tiny_mce/tiny_mce.js" type="text/javascript"></script> <script type="text/javascript"> tinyMCE.init({ mode:"exact", elements:"content", theme:"advanced", width: 340, height:400, plugins: "advlink,advlist,autoresize,autosave,contextmenu,fullscreen,iespell,inlinepopups,media,paste,preview,safari,searchreplace,visualchars,wordcount,xhtmlxtras", // Theme options theme_advanced_buttons1 : "cut,copy,paste,pastetext,pasteword,|,undo,redo,removeformat,|,search,replace,|,cleanup,help,code,preview,visualaid,fullscreen", theme_advanced_buttons2 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,|,bullist,numlist,|,outdent,indent,blockquote,|,sub,sup,cite,abbr", theme_advanced_buttons3 : "hr,|,link,unlink,anchor,image,|,charmap,emotions,iespell,media", theme_advanced_toolbar_location : "top", theme_advanced_toolbar_align : "left", theme_advanced_statusbar_location : "bottom", theme_advanced_resizing : true, // Example content CSS (should be your site CSS) content_css : "../css/main.css", }); </script> <?php // Include the HTML footer: include ('./aincs/footer.html'); ?> Link to comment Share on other sites More sharing options...
Recommended Posts