PHP - Csv Upload To Mysql Using Php And Html Form
Hi All
I am trying to upload a csv file to a database using php html form however, the results shows none of the data passsing through to the database and it produces 1000's of empty fields here is the form Code: [Select] form action="lib/import.php" method="post" enctype="multipart/form-data"> Type file name to import: <input type="file" name="filename" size="20"><br /> <input type="submit" name="submit" value="submit"></form> and here is the passing info Code: [Select] $file = $_FILES['filename']; $sqlstatement="LOAD DATA INFILE '$file' into TABLE shop FIELDS TERMINATED BY ',' (id, merchant_name, product_name, description, category_name, Affiliate_deep_link, Affiliate_image_url, price)" ; mysql_query($sqlstatement); echo "it is done!"; can anyone help please? Similar TutorialsHi- the code below lets me upload a CSV file to my database if I have 1 field in my database and 1 column in my CSV. I need to add to my db "player_id" from the CVS file and "event_name" and "event_type" from the form... any ideas??? here's the code: Code: [Select] <?php $hoststring =""; $database = ""; $username = ""; $password = ""; $makeconnection = mysql_pconnect($hoststring, $username, $password); ?> <?php ob_start(); mysql_select_db($database, $makeconnection); $sql_get_players=" SELECT * FROM tabel ORDER BY player_id ASC"; // $get_players = mysql_query($sql_get_players, $makeconnection) or die(mysql_error()); $row_get_players = mysql_fetch_assoc($get_players); // $message = null; $allowed_extensions = array('csv'); $upload_path = '.'; //same directory if (!empty($_FILES['file'])) { if ($_FILES['file']['error'] == 0) { // check extension $file = explode(".", $_FILES['file']['name']); $extension = array_pop($file); if (in_array($extension, $allowed_extensions)) { if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_path.'/'.$_FILES['file']['name'])) { if (($handle = fopen($upload_path.'/'.$_FILES['file']['name'], "r")) !== false) { $keys = array(); $out = array(); $insert = array(); $line = 1; while (($row = fgetcsv($handle, 0, ',', '"')) !== FALSE) { foreach($row as $key => $value) { if ($line === 1) { $keys[$key] = $value; } else { $out[$line][$key] = $value; } } $line++; } fclose($handle); if (!empty($keys) && !empty($out)) { $db = new PDO( 'mysql:host=host;dbname=db', 'user', 'pw'); $db->exec("SET CHARACTER SET utf8"); foreach($out as $key => $value) { $sql = "INSERT INTO `table` (`"; $sql .= implode("`player_id`", $keys); $sql .= "`) VALUES ("; $sql .= implode(", ", array_fill(0, count($keys), "?")); $sql .= ")"; $statement = $db->prepare($sql); $statement->execute($value); } $message = '<span>File has been uploaded successfully</span>'; } } } } else { $message = '<span>Only .csv file format is allowed</span>'; } } else { $message = '<span>There was a problem with your file</span>'; } } ob_flush();?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>CSV File Upload</title> </head> <body> <form class="form" action="" method="post" enctype="multipart/form-data"> <h3>Select Your File</h3> <p><?php echo $message; ?></p> <input type="file" name="file" id="file" size="30" /> <br/> <label>Event Name:</label><input name="event_name" type="text" value="" /> <br/> <label>Event Type:</label><input name="event_type" type="text" value="" /> <br/> <input type="submit" id="btn" class="button" value="Submit" /> </form> <br/> <h3>Results:</h3> <?php do { ?> <p><?php echo $row_get_players['player_id'];?></p> <?php } while ($row_get_players = mysql_fetch_assoc($get_players)); ?> </body> </html> so what i have going on is that i need help writing a basic script to upload original and copy with resize for thumbnail. then also need to rename both image files with content in the form. My server supports GD Library and that imagemagik or whatever it is lol. upload dirs orig: ../media/photos/ thumb: ../media/photos/thumb/ mySQL DB: name: m_photos fields: id(INT) m_cat(varchar) m_sub_cat(varchar) pic(varchar) description(varchar) p_group(varchar) I have the form written up for how it should look like: Code: [Select] <form action="upload.php" method="post" enctype="multipart/form-data"> Upload an image for processing<br /> <input type="file" name="Image"><br /> <select name="sub_group"> <option value="Photo Shoot">Photo Shoot</option> <option value="Live Performances">Live Performances</option> <option value="Randoms">Randoms</option> <option value="Fan Photos">Fan Photos</option> </select><br /> Location: <input type="text" name="p_group" /><br /> Date of Pic: <input type="text" name="date" /><br /> Description: <input type="text" name="description" /><br /> <input type="submit" value="Upload"> </form> so what needs to happen is for the file upload name. it needs to grab a count from "p_group" database to give it a starting number in a "00" pattern and then the date of pic needs to go in there next then the p_group name. so when the files gets uploaded it would look something like this after upload. "03 - Oct 21, 2011 - The Mex.jpg" NOTE: all pics must be converted to ".jpg" extension. both the orig and thumb will use that same file name cuz they just go into different dirs re-sizing for the thumbnail should be done by aspect ratio and needs to either be 300px width or 400px height. so if anyone would like to help me out please do. im not the greatest at writing in php yet I have an excel file that has several columns with different data and I need to create a form that can upload this excel file and insert the data from the columns into its conrresponding data columns in a mysql database. I know how to create the form but I have no idea how to get the file and tell it to input each cell of data into its corresponding field in the mysql database. Does anyone know how to do this? Any help would be appreciated. Thanks, There are two pieces to this- The HTML Form and the resulting php. I can't seem to make the leap, from the code to having the form produce the php page so others can view it until the form is again submitted overwriting the php, thus generating new content. The environment I am working in is limited to IIs 5.1 and php 5.2.17 without mySQL or other DB I'm new to php, this isn't homework,or commercialization, it's for children. I am thinking perhaps fwrite / fread but can't get my head around it. Code snipets below. Any help, please use portions of this code in hopes I can understand it Thanks Code snipet from Output.php Code: [Select] <?php $t1image = $_POST["t1image"]; $t1title = $_POST["t1title"]; $t1info = $_POST["t1info"]; $t2image = $_POST["t2image"]; $t2title = $_POST["t2title"]; $t2info = $_POST["t2info"]; ?> ... <tbody> <tr><!--Headers--> <td style="vertical-align: top; text-align: center; background-color: rgb(204, 255, 255);">Animal</td> <td style="vertical-align: top; text-align: center; background-color: rgb(204, 255, 255);">Image thumb<br> </td> <td style="vertical-align: top; text-align: center; background-color: rgb(204, 255, 255);">Date<br> </td> <td style="vertical-align: top; text-align: center; background-color: rgb(204, 255, 255);">Information<br> </td> </tr> <tr> <td style="vertical-align: top; text-align: center;">Monkey </td> <td style="vertical-align: top; text-align: center;"><img src="<?php echo $t1image.'.gif'; ?>"><!--single image presented selected from radio buttons--> </td> <td style="vertical-align: top; text-align: center;"><?php echo date("m/d/Yh:i A"); ?><!--time stamp generated when submitted form populates all fields at once--> </td> <td style="vertical-align: top; text-align: center;"><a href="#monkey" rel="facebox"><?php echo $t1title ?></a><!--Link name provided by "Title 1", that links to hidden Div generated page with content from "Info1" field--> <div id="Monkey" style="display:none"> <?php echo $t1info; ?> </div> </td> </tr> <tr> <td style="vertical-align: top; text-align: center;">Cat<br> </td> <td style="vertical-align: top; text-align: center;"><img src="<?php echo $t2image.'.gif'?>"></td> <td style="vertical-align: top; text-align: center;"><?php echo date("m/d/Yh:i A"); ?></td> <td style="vertical-align: top; text-align: center;"><a href="#Cat" rel="facebox"><?php echo $t2title ?></a> <div id="Cat" style="display:none"> <?php echo $t2info; ?> </div> </td> </tr> <tr> This replicates several times down the page around 15-20 times ( t1### - t20###) Code Snipet from HTML Form Code: [Select] <form action="animals.php" method="post"> <div style="text-align: left;"><big style="font-family: Garamond; font-weight: bold; color: rgb(51, 51, 255);"><big><big><span>Monkey</span></big></big></big><br> <table style="text-align: left; width: 110px;" border="0" cellpadding="2" cellspacing="0"> <tbody><tr> <td style="vertical-align: top;">Image thumb<br> <input type="radio" name="t1image" value="No opinion" checked><img src="eh.gif" alt="Eh"> <input type="radio" name="t1image" value="Ok"><img src="ok.gif" alt="ok"> <input type="radio" name="t1image" value="Like"><img src="like.gif" alt="Like"> <input type="radio" name="t1image" value="Dont"><img src="dont.gif" alt="Don't Like"> <input type="radio" name="t1image" value="Hate"><img src="hate.gif" alt="Hate"> <input type="radio" name="t1image" value="Other"><img src="other.gif" alt="Other"> <br> Why Title:<input type="text" name="t1title" size="45" value="..."/></td> <td style="vertical-align: top;"> Explain:<br> <textarea name="t1info" cols=45 rows=3 value="..."></textarea> </td></tr></table> <br> <!--Next--> How do I get the Form data to save to the php page for others to view? Trying to figure out how to approach this. I have a form that uses php to pull from a mysql database. I can get the text submission form to work but I am having trouble with a drop down menu that pulls directly from the DB and submitting what is selected as the basis of the result query. I am including the two sets of code. one for my search.php and the other for my search_result.php. search.php Code: [Select] <?php require_once('Connections/search_db.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($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; } } mysql_select_db($database_search_db, $search_db); // Search engine functionality if ($_GET['title'] || $_GET['country2']) { $ti = $_GET['title']; $count = $_GET['country2']; $query_rsLinks = "SELECT * FROM tbl_links WHERE (tbl_links.linkemail LIKE '%$ti%' OR tbl_links.linktitle LIKE '%$ti%' OR tbl_links.linkurl LIKE '%$ti%') AND tbl_links.linkcat LIKE '$count' ORDER BY tbl_links.linkdate DESC"; } else { $query_rsCountries = "SELECT search_db.tb_name FROM search_db"; } $rsCountries = mysql_query($query_rsCountries, $search_db) or die(mysql_error()); $row_rsCountries = mysql_fetch_assoc($rsCountries); $totalRows_rsCountries = mysql_num_rows($rsCountries); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body><form action="search_result.php" method="get" name="fmsearch"> <table width="200" border="1"> <tr> <td>search</td> <td><label for="title"></label> <input name="title" type="text" id="title" /></td> <td><input name="Search" type="button" id="Submit" value="Submit" /> </td> </tr> </table> </form> <br> <!-- action="search_result.php" --> <form id="forminsert" name="fmsearch" action="search_result.php" method="get"> <table border="0" id="tblinsert"> <caption> search for country </caption> <tr> <th><label for="title">search for:</label></td> <th> <input type="text" name="title" id="title" <?php if (isset($_GET['title'])) { echo 'value="' .$GET['title']. '"'; } ?> /> </td> <td><input type="submit" id="button" value="Submit" /></td> </tr> </table> <form id="forminsert" name="fmsearch" action="search_result.php" method="get"> <table border="0" id="tblinsert2"> <caption> search for country </caption> <tr> <td><select name="country2" id="country2"> <option value="">All Countries</option>> <?php do { ?> <option value="<?php echo $row_rsCountries['tb_name']?>"> <?php echo $row_rsCountries['tb_name']?></option> <?php } while ($row_rsCountries = mysql_fetch_assoc($rsCountries)); $rows = mysql_num_rows($rsCountries); if($rows > 0) { mysql_data_seek($rsCountries, 0); $row_rsCountries = mysql_fetch_assoc($rsCountries); } ?> </select></td> <td><input type="submit" id="button" value="Submit" /></td> </tr> </table> </form> </body> </html> <?php mysql_free_result($rsCountries); ?> search_result.php Code: [Select] <?php require_once('Connections/search_db.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($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; } } $colname_rs83 = "-1"; if (isset($_GET['country2'])) { $colname_rs83 = $_GET['country2']; } mysql_select_db($database_search_db, $search_db); $query_rs83 = sprintf("SELECT * FROM search_db WHERE tb_name LIKE %s", GetSQLValueString("%" . $colname_rs83 . "%", "text"),GetSQLValueString("%" . $colname_rs83 . "%", "text")); $rs83 = mysql_query($query_rs83, $search_db) or die(mysql_error()); $row_rs83 = mysql_fetch_assoc($rs83); $colname_rs83 = "-1"; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body> <?php echo $row_rs83['']; ?> <?php do { ?> <table width="300" border="1"> <tr> <td rowspan="2"><img src="<?php echo $row_rs83['tb_Img']; ?>" alt="image" /></td> <td><?php echo $row_rs83['tb_name']; ?></td> </tr> <tr> <td><?php echo $row_rs83['tb_desc']; ?></td> </tr> </table> <?php } while ($row_rs83 = mysql_fetch_assoc($rs83)); ?> <a href="http://barium.worldteam.org/phptesting/search.php">Back to Search</a> </body> </html> <?php mysql_free_result($rs83); ?> Hi, I have this script which I would like to use to build an html form from a MySQL table. The <input text................ writes successfully to file but none of the other form types are written to file when using the elseif command Also, I would like this script to carry out the file write foreach row in the table It seems complicated and i am not sure if I am going about it in the right way, but here goes Code: [Select] //// Create Forms from MySQL $result = mysql_query("SELECT * FROM forms"); while($row = mysql_fetch_assoc($result)){ $field_label = $row['field_label']; $column_name = $row['column_name']; $field_type = $row['field_type']; if ($row['field_type'] = 'Text') { $stringData = "$field_label<input type=text name=$column_name>\n"; fwrite($fh, $stringData); } elseif ($row['field_type'] = 'Text Area') { $stringData = "$field_label<input type=textarea name=$column_name></textarea>\n"; fwrite($fh, $stringData); } elseif ($row['field_type'] = 'Select Menu') { $stringData = "$field_label<select name=$column_name></select>\n"; fwrite($fh, $stringData); } elseif ($row['field_type'] = 'Checkbox') { $stringData = "$field_label<input type=checkbox name=$column_name></textarea>\n"; fwrite($fh, $stringData); } fclose($fh); As always, any help is much appreciated Hi, I m doing some work for my self an because of that i been reading a lot arround about PHP, and theres something that i would like to ask a bit of enlightenment. So my question is as the title says about html form's using php to insert data into mysql, i been reading tutorials arround the interwebs and even made afew successful tests, but pretty much all tutorials use 2 files to accomplish this the html file with the form and an insert.php where the actual code is stored so this made me think is this how usually it's done? in over all you will have 1 file for the form, 1 for the insert, 1 for the edit php code and 1 for delete. How do you guys usually do it? PS: one of the tests i did was making 1 single file with all these using an switch. My interest in making this question is solo to learn how other people do it to see if i m in the right way. Thanks in advance. Hello Im quite confused at what filtering I should use on my data when pulling it from a MySQL database. I don't sanitize my data on input because I am using prepared statements with PHP's PDO Driver which means I don't need to use mysql_real_escape_string() at all. When I pull the data to be displayed i.e. in a HTML Table I use the below function to make it safe for HTML output. public static function htmlSafe($data) { return nl2br(htmlentities($data, ENT_QUOTES)); } However the rules change when Im using a HTML Form to edit the data, and I am unsure what I need to strip out. I.e. What would I need to do to make all data safe to insert into the following form input. <input id = "someInput" type = "text" value = "<?php echo $someVarThatNeedsFiltering ?>" /> Also, one more question, in my html attributes (Valid ones like class, name, id, style, _target) I use a mixture of double quotes(") and single quotes ('), for quoting my values. Which one should I use or which one is more valid, doubles, or singles? I'm trying to do something that I thought was very simple about 2 weeks ago :-( I want to put a form on my site and link it to a database so when a user types a surname into the form they can search the db and the page will only display the surnames that match the search criteria. I got the db set up using phpmyadmin in about 2 minutes flat, but keep getting error messages when I write the php. I'm currently working with the below script, which keeps giving me the error 'unexpected T_string' on line 176 I've searched every forum and help site I can find, and the mysql and php manuals are just mind-boggling. I'm sure I'm making some really amateur mistake, but I'd really appreciate help with this! thanks all! <html> <head> <title>SEARCH RECORDS</title> </head> <body> <FORM NAME ="Search" METHOD ="POST" ACTION = "test3"> <INPUT TYPE = "TEXT" VALUE ="surname" NAME = "surname"> <INPUT TYPE = "Submit" Name = "Search" VALUE = "Search"> </FORM> </body> </html> <? $user_name = "*****"; $password = "*****"; $database = "*****"; $server = "localhost"; $db_handle = mysql_connect($server, $user_name, $password); $db_found = mysql_select_db($database, $db_handle); if ($db_found) { $SQL = "SELECT * FROM *****" WHERE surname=$_POST['surname']; $result = mysql_query($SQL); while ($db_field = mysql_fetch_assoc($result)) { print $db_field['Grave'] . "<BR>"; print $db_field['Surname'] . "<BR>"; print $db_field['Forenames'] . "<BR>"; print $db_field['Death_Date'] . "<BR>"; print $db_field['Birth_Year'] . "<BR>"; } mysql_close($db_handle); } else { print "Database NOT Found "; mysql_close($db_handle); } ?> My problem could be odd if say it but i will spill it out, only don't say I am mad completely jut a bit ! 1.when comment is first in whole news if i press edit appear html form but if i am trying to submit any information it returns to comments and don't update ! 2.if there were more than one comment in news if i press edit appear html forms 1.not working | 2.working and do updates | 3.were appear but is gone but not sure does bug will return also not working ! Sample how it looks ! This is indeed odd hope somebody has knowledge in such issues or at least a cure for such severe bug website http://hostings.flush.ws/ user guest password guest11 | to test bug go to the news comments and spam as much needed ! Link to edit code Code: [Select] echo "<a href='/?section=nwcomment&id=".$id."&comment=edit&id_edit=".$row_news_comment['hosting_comment_id']."'>Edit Comment</a>"; Update code as far i know it is correct at least i do hope sow (also this code is inside while cycle ) Code: [Select] if ($_GET['comment'] == 'edit') { $comment_id_edit = (INT)$_GET['id_edit']; $comment_text = $row_news_comment['hosting_comment_text']; $edit_comment_text = $_POST['hosting_comment_text']; if(isset($_POST['hosting_comment_text'])) { mysql_query("UPDATE hosting_comment SET hosting_comment_text = '".$edit_comment_text."' WHERE hosting_comment_id = '".$comment_id_edit."' ") or die (mysql_error()); } if (isset($_POST['Submit'])) { echo "<meta http-equiv='REFRESH' content='0;url=/?section=nwcomment&id=".$id."'>"; } echo ("<form action='/?section=nwcomment&id=".$id."&comment=edit&id_edit=".$comment_id_edit."'' id='edit_comment' name='edit_comment' method='post'> <p> <textarea name='hosting_comment_text' cols='50' rows='10' id='textarea' value='$edit_comment_text' ></textarea> <p> <input type='submit' name='Submit' id='button' value='{$lang['BODY_NEWS_COMMENT_SUBMIT']}' /> <input type='reset' name='Reset' id='button' value='{$lang['BODY_NEWS_COMMENT_RESET']}' /> </p> </form>"); } if is needed more complete code just ask i will publish it (i hope to fix bug as soon possible grand opening of registration will be on the Aprils Fools Day) Hi, I have two html made text boxes one that is called "name" and another that is called "regnum". I also have a submit button. They are both used to add data to a database. The name text box should add a name to the database under the "name" heading and the regnum should add a number under the "regnum" heading Here is the code for them: HTML Code: <form action="" method="post"> <p> Name: <input type="text" name="name"/> </p> <p> Regnum: <input type="text" name="regnum"/> </p> <p> <input type="submit" value="Add To Database" name = "submit2" /> </p> </form> Here is the PHP code that i am using for adding the user to the database: PHP Code: $host="localhost"; $username="root"; $password=""; $database="lab2"; mysql_connect("$host", "$username", "$password") or die(mysql_error()); mysql_select_db("$database") or die(mysql_error()); $name = $_POST['name']; $regnum = $_POST['regnum']; if(!$_POST['submit2']){ echo "Enter A Vaue"; }else{ mysql_query("INSERT INTO lab2('name', 'regnum') VALUES(NULL, '$name', '$regnum')") or die(mysql_error()); echo "User Added To Database"; } The problem i get with this is "Undefined Index name and regnum". I watched a video on youtube and this is how the guy did it but it worked for him and for some reason it doesn't work for me. Can anyone help?? Thanks. Hey guys i have a problem, I have a form to upload 2 image files however sometimes i want to only upload the one file, but if i only upload one image, it tells me that it can't upload because there is no name for the second image. I tried fixing it with if (isset($fieldname2)) however i just realised that $feildname2 is always set so im not quite sure how to fix? Code: [Select] ($action == "add"){ $add = $_POST['add']; $reference = $_POST['reference']; $category = $_POST['category']; $sub_cat = $_POST['sub_cat']; $fieldname = 'file'; $fieldname2 = 'file2'; error_reporting(E_ALL); ini_set('display_errors',1); is_uploaded_file($_FILES[$fieldname]['tmp_name']); getimagesize($_FILES[$fieldname]['tmp_name']); if (isset($fieldname2)) { is_uploaded_file($_FILES[$fieldname2]['tmp_name']); getimagesize($_FILES[$fieldname2]['tmp_name']); } $now = time(); while(file_exists($uploadFilename = $uploadsDirectory.$_FILES[$fieldname]['name'])) { $now++; } if (isset($fieldname2)) { while(file_exists($uploadFilename2 = $uploadsDirectory.$_FILES[$fieldname2]['name'])) { $now++; } } move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename); if (isset($fieldname2)) { move_uploaded_file($_FILES[$fieldname2]['tmp_name'], $uploadFilename2); } $sqlname = $_FILES[$fieldname]['name']; if (isset($fieldname2)) { $sqlname2 = $_FILES[$fieldname2]['name']; } $id = mysql_insert_id(); $query = "INSERT INTO cakes (id, reference, category, sub_cat, image, image2) VALUES ('$id', '$reference', '$category', '$sub_cat','$sqlname','$sqlname2')"; $sql = mysql_query($query) or die (mysql_error()); } echo("<form name='add' method='post' enctype='multipart/form-data' action='?action=add'>"); echo("<input type='hidden' name='MAX_FILE_SIZE' value='3000000"); echo("<input type='hidden' name='?action=add'>"); echo("<table class=main cellspacing=0 cellpadding=2 width=60%>"); echo("<tr><td>Reference: </td><td align='right'><input type='text' size=50 name='reference' value='$reference'></td></tr>"); echo("<tr><td>Category: </td><td align='center'><select name='category'><option>Occasional</option><option>Special</option><option>Figures</option><option>Novelty</option><option>Wedding</option></SELECT></td></tr>"); echo("<tr><td>Sub Category: </td><td align='center'><select name='sub_cat'><option></option><option>Birthday</option><option>Anniversary</option><option>Christmas</option><option>Christening</option><option>Valentine</option><option>Mothers Day</option><option>Fathers Day</option><option>Easter</option></select></td></tr>"); echo("<tr><td>Cake Image: </td><td align='center'><input id='file' type='file' name='file'></td></tr>"); echo("<tr><td>Cake Image 2: </td><td align='center'><input id='file2' type='file' name='file2'></td></tr>"); echo("Before uploading an image please resize the image to 290px x 218px"); echo("<tr><td></td><td><div align='right'><input type='Submit'></div></td></tr>"); echo("</table>"); Hi guys, I am trying to create a coding which allows users to upload and download files into mysql server, but I came across some errors. The coding itself works fine on the surface, but when I uploaded the file into mysql and download them, the contents of the downloaded file was different from the original file that was upload. One good example would be when I upload txt file or doc file. I was stuck on this for quite a few days without any leads. Here are the codes: index.html <form action="add_file.php" method="post" enctype="multipart/form-data"> <input type="file" name="uploaded_file"><br> <input type="submit" value="Upload file"> </form> <p> <a href="list_files.php">See all files</a> </p> add_file.php <?php // Check if a file has been uploaded if(isset($_FILES['uploaded_file'])) { // Make sure the file was sent without errors if($_FILES['uploaded_file']['error'] == 0) { // Connect to the database $dbLink = new mysqli('localhost', 'root', 'pwd', 'myTable'); if(mysqli_connect_errno()) { die("MySQL connection failed: ". mysqli_connect_error()); } // Gather all required data $name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']); $mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']); $data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name'])); $size = intval($_FILES['uploaded_file']['size']); // Create the SQL query $query = " INSERT INTO `file` ( `name`, `mime`, `size`, `data`, `created` ) VALUES ( '{$name}', '{$mime}', {$size}, '{$data}', NOW() )"; // Execute the query $result = $dbLink->query($query); // Check if it was successfull if($result) { echo 'Success! Your file was successfully added!'; } else { echo 'Error! Failed to insert the file' . "<pre>{$dbLink->error}</pre>"; } } else { echo 'An error accured while the file was being uploaded. ' . 'Error code: '. intval($_FILES['uploaded_file']['error']); } // Close the mysql connection $dbLink->close(); } else { echo 'Error! A file was not sent!'; } // Echo a link back to the main page echo '<p>Click <a href="index.html">here</a> to go back</p>'; ?> list_files.php <?php // Connect to the database $dbLink = new mysqli('localhost', 'root', 'pwd', 'myTable'); if(mysqli_connect_errno()) { die("MySQL connection failed: ". mysqli_connect_error()); } // Query for a list of all existing files $sql = 'SELECT `id`, `name`, `mime`, `size`, `created` FROM `file`'; $result = $dbLink->query($sql); // Check if it was successfull if($result) { // Make sure there are some files in there if($result->num_rows == 0) { echo '<p>There are no files in the database</p>'; } else { // Print the top of a table echo '<table width="100%"> <tr> <td><b>Name</b></td> <td><b>Mime</b></td> <td><b>Size (bytes)</b></td> <td><b>Created</b></td> <td><b> </b></td> </tr>'; // Print each file while($row = $result->fetch_assoc()) { echo " <tr> <td>{$row['name']}</td> <td>{$row['mime']}</td> <td>{$row['size']}</td> <td>{$row['created']}</td> <td><a href='get_file.php?id={$row['id']}'>Download</a></td> </tr>"; } // Close table echo '</table>'; } // Free the result $result->free(); } else { echo 'Error! SQL query failed:'; echo "<pre>{$dbLink->error}</pre>"; } // Close the mysql connection $dbLink->close(); ?> get_file.php <?php // Make sure an ID was passed if(isset($_GET['id'])) { // Get the ID $id = intval($_GET['id']); // Make sure the ID is in fact a valid ID if($id <= 0) { die('The ID is invalid!'); } else { // Connect to the database $dbLink = new mysqli('localhost', 'root', 'pwd', 'myTable'); if(mysqli_connect_errno()) { die("MySQL connection failed: ". mysqli_connect_error()); } // Fetch the file information $query = " SELECT `mime`, `name`, `size`, `data` FROM `file` WHERE `id` = {$id}"; $result = $dbLink->query($query); if($result) { // Make sure the result is valid if($result->num_rows == 1) { // Get the row $row = mysqli_fetch_assoc($result); // Print headers header("Content-Type: ". $row['mime']); header("Content-Length: ". $row['size']); header("Content-Disposition: attachment; filename=". $row['name']); // Print data echo $row['data']; } else { echo 'Error! No image exists with that ID.'; } // Free the mysqli resources @mysqli_free_result($result); } else { echo "Error! Query failed: <pre>{$dbLink->error}</pre>"; } @mysqli_close($dbLink); } } else { echo 'Error! No ID was passed.'; } ?> I am not too sure where the error could be but I suspect that it could be somewhere at the add_file or get_file. Seriously hope someone could help me with this bug and thanks for the trouble. Regards Jasmine Hi, I'm not sure if this is the right forum to post this question, but I'll still post it. I'm a newbie programmer, have 1 year experience of php, mysql and html and know how to make a basic website, but I've never actually uploaded the already written code on the internet.So my question is, if you use vertrigo serv and have folders full of php files, what do you do after getting a domain? I read that dreamweaver does that for you, but i also read that it is a closed source software with limitations if you get the free version.The other choice is using FileZilla(which I don't fully understand yet ) i presume.
Hey everyone ... This should be a pretty easy question for someone who is used to using fgetcsv: I have a script that needs to import a csv file into a mysql table ... I keep getting stuck in a loop that only ends when the script hits the 30 second timeout I have set on the server ... It never actually inserts a record, and it never spits out a message indicating and error ... Can someone help figure out why I get caught in this loop? Here's the code: Code: [Select] function import_csv() { if(isset($_POST['submit_csv'])) { $filename=$_POST['filename']; $handle = fopen("$filename", "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $import="INSERT INTO `{mydatabase}`.`{my table}` (`name`, `qrl`, `begin`) VALUES ('$data[0]','$data[1]','$data[2]')"; mysql_query($import) or die(mysql_error()); } fclose($handle); print "Import done"; } else { print "<form action='results.php' method='post'><input type='file' name='filename'><br /><input type='submit' value='submit' name='submit_csv' /></form>"; } } Hey guys! I'm not that good with PHP, and I really need to finish this script. I'm having a hard time finding the problem..it keeps saying Error, query failed and I've also checked the database info, connectivity info and even tried a connection and database selection verification to see if that was working. Is there any other error you guys can find in the script that may be causing the message? Edit: The files I want to be able to upload should be pdf's, txts, docs, etc. Would that be possible with this script? Thanks!! Code: [Select] <form method="post" enctype="multipart/form-data"> <table width="350" border="0" cellpadding="1" cellspacing="1" class="box"> <tr> <td width="246"> <input type="hidden" name="MAX_FILE_SIZE" value="104857600"></td> <td width="80"> </td> </tr> </table> <p>Archivo: <input name="userfile" type="file" id="userfile" /> </p> <p>Nomb <label for="name"></label> <input type="text" name="nombrelista" id="nombrelista" /> </p> <p>Password (para luego borrar si necesario): <input type="text" name="pass" id="pass" /> </p> <p> <input name="upload" type="submit" class="box" id="upload" value=" Upload " /> </p> <?php if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0) { $fileName = $_FILES['userfile']['name']; $tmpName = $_FILES['userfile']['tmp_name']; $fileSize = $_FILES['userfile']['size']; $fileType = $_FILES['userfile']['type']; $filePass = $_POST['pass']; $nombreLista = $_POST['nombrelista']; $fp = fopen($tmpName, 'r'); $content = fread($fp, filesize($tmpName)); $content = addslashes($content); fclose($fp); $host_db = "localhost"; $user_db = "melkien_rudesa"; $pass_db = "jorlan2407"; $base_db = "melkien_rudesa"; $link = mysql_connect($host_db, $user_db, $pass_db); if (!$link) { die('Could not connect: ' . mysql_error()); mysql_close($link); } mysql_select_db($base_db, $link) or die(mysql_error()); if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); } $query = "INSERT INTO 'upload'('nombrelista', 'name', 'pass', 'size', 'type', 'content' ) VALUES ('$nombreLista', $fileName', '$filePass', $fileSize', '$fileType', '$content')"; mysql_query($query) or die('Error, query failed'); echo "<br>File $fileName uploaded<br>"; mysql_close($link); } ?> </form> Hi Guys, I am trying to use a script that is available on the net to upload an image into a mysql using BLOB. However it wont upload it keep getting Warning: fread() [function.fread]: Length parameter must be greater than 0 in /home/theacidf/public_html/attendance/upload.php on line 17 Here is the code... <?php // Connect to database $errmsg = ""; if (! @mysql_connect("localhost","theacidf_admin","password")) { $errmsg = "Cannot connect to database"; } @mysql_select_db("theacidf_attendanc"); // Insert any new image into database if ($_REQUEST[completed] == 1) { move_uploaded_file($_FILES['imagefile']['tmp_name'],"latest.img"); $instr = fopen("latest.img","rb"); $image = addslashes(fread($instr,filesize("latest.img"))); if (strlen($image) < 149000) { mysql_query ("insert into pix (title, imgdata) values (\"". $_REQUEST[whatsit]. "\", \"". $image. "\")"); } else { $errmsg = "Too large!"; } } // Find out about latest image $gotten = @mysql_query("select * from pix order by pid desc limit 1"); if ($row = @mysql_fetch_assoc($gotten)) { $title = htmlspecialchars($row[title]); $bytes = $row[imgdata]; } else { $errmsg = "There is no image in the database yet"; $title = "no database image available"; // Put up a picture of our training centre $instr = fopen("../images/logo_png.png","rb"); $bytes = fread($instr,filesize("../images/logo_png.png")); } // If this is the image request, send out the image if ($_REQUEST[gim] == 1) { header("Content-type: image/jpeg"); print $bytes; exit (); } ?> <html><head> <title>Upload an image to a database</title> <body bgcolor=white><h2>Here's the latest picture</h2> <font color=red><?= $errmsg ?></font> <center><img src=?gim=1><br> <?= $title ?></center> <hr> <h2>Please upload a new picture and title</h2> <form enctype=multipart/form-data method=post> <input type=hidden name=MAX_FILE_SIZE value=150000> <input type=hidden name=completed value=1> Please choose an image to upload: <input type=file name=imagefile><br> Please enter the title of that pictu <input name=whatsit><br> then: <input type=submit></form><br> <hr> </body> </html> Why wont it run properly? Thanks in advance... S Hi all, creating a MYSQL, PHP & XHTML site designed to support local rugby clubs. Just putting the final touches to the functionality now so thanks for your help so far. I would like to provide site administrators with the ability to assign photos to a members profile when initially registering their account, I have no experience of dealing with what presumably will be a function that will upload a photo to a location and then linking it some how to data in the database. Thanks for your help, Tom I receive files/images and loop through an array as follows:
$files=rearrfiles( $_FILES['image']); foreach($files as $key=>$item) { if(is_array($item) && !empty($item['name']) && !empty($item['tmp_name'])){ //$_POST['imageFile']=$item['name']; //echo $item['name']; if($error!=true && !uploadImageB(array('image'=>'image'), DB_EXTENTION."mod_projects_images", $naming, $search = $editId, $dir, 'photo')) { $error=true; $action='Edit'; $message.='<br>Images were unable to be uploaded.'; } } }The function uploadImageB() is as follows: function uploadImageB($info, $table, $naming, $search, $path, $add='uploaded', $maxw=1280, $maxh=1280, $dynamic=true, $id='Id', $thumbMaxWidth = 120) { global $connection; if(!$_POST){ global $HTTP_POST_VARS; @$_POST=$HTTP_POST_VARS;} if(!$_FILES){ global $HTTP_POST_FILES; @$_FILES=$HTTP_POST_FILES;} if(is_array($info) && !empty($info) && $table!='' && !empty($path)) { $error=false; $d=$naming; foreach($info as $key=>$val) { $names[$val]=$dynamic==true?$add.'_'.$result[$id].'_'.$d.'_.'.strtolower(mygetext($_FILES[$val]['name'])):$add.strtolower(mygetext($_FILES[$val]['name'])); if(is_array(@$_FILES[$val]) && !empty($_FILES[$val]['name']) && !empty($names[$val])) { if(!singMove($path, $names[$val], $_FILES[$val], array(), array('gif', 'jpeg', 'jpg', 'png', 'bmp', 'svg'))) { $error=true; break; } else{ $valid[$val]=$names[$val]; resizeImage($path.$names[$val], $maxw, $maxh); make_thumb($path.$names[$val],$names[$val], $path, $thumbMaxWidth); } } } if($error==true) return false; elseif(!empty($valid)) { $connection->info=$info; $connection->input=$valid; $connection->id=array('field'=>$id, 'val'=>addslashes($result[$id])); $connection->makenew($table); $connection->return_db($connection->query); } } return true; }I get the error: Images were unable to be uploaded. Any help? |