PHP - Import A Csv File Into Mysql Database
<!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=iso-8859-1" /> <title>Import a CSV File with PHP & MySQL</title> </head> <body> <form action="" method="post" enctype="multipart/form-data" name="csv" id="csv"> Choose your file: <br /> <input name="csv" type="file" id="csv" /> <input type="submit" name="Submit" value="Submit" /> </form> </body> Similar TutorialsHi.. I have code for importing .xml file to database. the problem is I cannot upload my file but no error display. And also I got a problem in importing data from .xml file to database but not all row will be save. here is my code: Code: [Select] <?php $data = array(); $con = mysql_connect("localhost", "root",""); if (!$con) { die(mysql_error()); } $db = mysql_select_db("mes", $con); if (!$db) { die(mysql_error()); } $sql = "select * from sales_order"; $result = mysql_query($sql); if (!$result) { die(mysql_error()); } function add_employee($ProductType,$WorkOrder,$POIssueDate,$SalesMonth) { global $data; $con = mysql_connect("localhost", "root",""); if (!$con){ die(mysql_error());} $db = mysql_select_db("mes", $con); if (!$db) { die(mysql_error()); } $ProductType= $ProductType; $WorkOrder = $WorkOrder; $POIssueDate = $POIssueDate; $SalesMonth = $SalesMonth; $sql = "INSERT INTO sales_order (ProductType,WorkOrder,POIssueDate,SalesMonth) VALUES ('$ProductType','$WorkOrder','$POIssueDate','$SalesMonth')" or die(mysql_error()); mysql_query($sql, $con); $data []= array('ProductType'=>$ProductType,'WorkOrder'=>$WorkOrder,'POIssueDate'=>$POIssueDate,'SalesMOnth'=>$SalesMonth); } if ( $_FILES['file']['tmp_name'] ['error']) //f (empty($_FILES['file']['tmp_name']['error'])) { //$dom = DOMDocument::load('SalesOrder.xml'); $dom = DOMDocument::load($_FILES['file']['tmp_name']); $dom = DOMDocument::__construct(); $rows = $dom->getElementsByTagName('Row'); global $last_row; $last_row = false; $first_row = true; foreach ($rows as $row) { if ( !$first_row ) { $ProductType = ""; $WorkOrder = ""; $POIssueDate = ""; $SalesMonth = ""; $index = 1; $cells = $row->getElementsByTagName( 'Cell' ); foreach( $cells as $cell ) { $ind = $cell->getAttribute( 'Index' ); if ( $ind != null ) $index = $ind; if ( $index == 1 ) $ProductType = $cell->nodeValue; if ( $index == 2 ) $WorkOrder = $cell->nodeValue; if ( $index == 3 ) $POIssueDate = $cell->nodeValue; if ( $index == 4 ) $SalesMonth = $cell->nodeValue; $index += 1; } if ($ProductType=='' AND $WorkOrder=='' AND $POIssueDate=='' AND $SalesMonth=='') { $last_row = true; } else { add_employee($ProductType,$WorkOrder,$POIssueDate,$SalesMonth); } } if ($last_row==true) { $first_row = true; } else { $first_row = false; } } } ?> <html> <body> <table> <tr> <th>Sales Order</th> </tr> <?php foreach( $data as $row ) { ?> <tr> <td><?php echo( $row['ProductType'] ); ?></td> <td><?php echo( $row['WorkOrder'] ); ?></td> <td><?php echo( $row['POIssueDate']) ;?> </td> <td><?php echo( $row['SalesMonth'] ); ?></td> </tr> <?php } ?> </table> </body> </html> and I will attach my sample data and the data with color yellow background is only row I want to save to my database. Thank you so much.. Hi! I hope somebody can help me what im do wrong. i have checked that the data from the file is in $source_file but nothing imports to the database Code: [Select] <?php include('config.php'); include('opendb.php'); if(isset($_POST['upload'])) { $source_file = @$_POST['userfile']; //$source_file = fopen('http://localhost/test/upload/test.csv', 'r'); $target_table = 'foretag'; function csv_file_to_mysql_table($source_file, $target_table, $max_line_length=10000) { if (($handle = fopen("$source_file", "r")) !== FALSE) { $columns = fgetcsv($handle, $max_line_length, ","); foreach ($columns as $column) { $column = str_replace(".","",$column); } $insert_query_prefix = "INSERT INTO $target_table (".join(",",$columns).")\nVALUES"; while (($data = fgetcsv($handle, $max_line_length, ";")) !== FALSE) { while (count($data)<count($columns)) array_push($data, NULL); $query = "$insert_query_prefix (".join(",",quote_all_array($data)).");"; mysql_query($query); } fclose($handle); } } function quote_all_array($values) { foreach ($values as $key=>$value) if (is_array($value)) $values[$key] = quote_all_array($value); else $values[$key] = quote_all($value); return $values; } function quote_all($value) { if (is_null($value)) return "NULL"; $value = "'" . mysql_real_escape_string($value) . "'"; return $value; } } include('closedb.php'); echo "<br>done<br>"; ?> I think this is the right section to post this is in..... Anyway.....I'm building a web site that requires i have functionality to upload a tab delimited file (or some file format that is easiest) via php and insert the data into MYSQL. I've searched for many third party scripts but none seem to work. So I've decided to move to the community to see if someone can give me insight on how i might accomplish this script. I have some third party scripts but I'm not sure if they'd be of any use. Thank you kindly Goodevening.Thuis is the codes under these but i dont have any idea on how can i use it because i only use php and mysql as my database. i dont know how to use the xml as my database. can you help me? Thanks in advance
<?xml version="1.0" encoding="UTF-8" ?> <XMLDB PATH="plagiarism/programming/db" VERSION="20121207" COMMENT="XMLDB file for Moodle plagiarism/programming" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../lib/xmldb/xmldb.xsd" > <TABLES> <TABLE NAME="plagiarism_programming" COMMENT="This table saves settings for source code plagiarism detection in programming assignments" NEXT="plagiarism_programming_rpt"> <FIELDS> <FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="true" NEXT="cmid"/> <FIELD NAME="cmid" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="false" COMMENT="The course module id" PREVIOUS="id" NEXT="scandate"/> <FIELD NAME="scandate" TYPE="int" LENGTH="10" NOTNULL="false" UNSIGNED="true" SEQUENCE="false" COMMENT="The date submissions are scanned" PREVIOUS="cmid" NEXT="jplag"/> <FIELD NAME="jplag" TYPE="int" LENGTH="1" NOTNULL="false" UNSIGNED="true" SEQUENCE="false" COMMENT="JPlag tool is used or not" PREVIOUS="scandate" NEXT="moss"/> <FIELD NAME="moss" TYPE="int" LENGTH="1" NOTNULL="false" UNSIGNED="true" SEQUENCE="false" COMMENT="MOSS tool is used or not" PREVIOUS="jplag" NEXT="language"/> <FIELD NAME="language" TYPE="char" LENGTH="10" NOTNULL="true" SEQUENCE="false" COMMENT="Which language is used in the assignment" PREVIOUS="moss" NEXT="auto_publish"/> <FIELD NAME="auto_publish" TYPE="int" LENGTH="1" NOTNULL="false" UNSIGNED="true" SEQUENCE="false" PREVIOUS="language" NEXT="notification"/> <FIELD NAME="notification" TYPE="char" LENGTH="200" NOTNULL="false" SEQUENCE="false" COMMENT="Used to display notifications to students" PREVIOUS="auto_publish" NEXT="starttime"/> <FIELD NAME="starttime" TYPE="int" LENGTH="10" NOTNULL="false" UNSIGNED="false" SEQUENCE="false" COMMENT="The time when last plagiarism scanning occurred" PREVIOUS="notification" NEXT="latestscan"/> <FIELD NAME="latestscan" TYPE="int" LENGTH="10" NOTNULL="false" UNSIGNED="false" SEQUENCE="false" COMMENT="timestamp of the latest scan" PREVIOUS="starttime" NEXT="notification_text"/> <FIELD NAME="notification_text" TYPE="text" LENGTH="medium" NOTNULL="false" SEQUENCE="false" COMMENT="the customised notification text to appear on the student assignment page" PREVIOUS="latestscan"/> </FIELDS> <KEYS> <KEY NAME="primary" TYPE="primary" FIELDS="id"/> </KEYS> <INDEXES> <INDEX NAME="cmid_index" UNIQUE="false" FIELDS="cmid" COMMENT="Index for cmid for fast searching"/> </INDEXES> </TABLE> <TABLE NAME="plagiarism_programming_rpt" COMMENT="containing different report versions" PREVIOUS="plagiarism_programming" NEXT="plagiarism_programming_jplag"> <FIELDS> <FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="true" NEXT="cmid"/> <FIELD NAME="cmid" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="false" SEQUENCE="false" PREVIOUS="id" NEXT="time_created"/> <FIELD NAME="time_created" TYPE="int" LENGTH="15" NOTNULL="true" UNSIGNED="true" SEQUENCE="false" PREVIOUS="cmid" NEXT="version"/> <FIELD NAME="version" TYPE="int" LENGTH="11" NOTNULL="true" UNSIGNED="false" SEQUENCE="false" PREVIOUS="time_created" NEXT="detector"/> <FIELD NAME="detector" TYPE="char" LENGTH="10" NOTNULL="false" SEQUENCE="false" PREVIOUS="version"/> </FIELDS> <KEYS> <KEY NAME="report_primary" TYPE="primary" FIELDS="id" COMMENT="Primary key of the table"/> </KEYS> <INDEXES> <INDEX NAME="cmiverdet_index" UNIQUE="false" FIELDS="cmid, version, detector" COMMENT="Index for cmid, version, detector for fast searching"/> </INDEXES> </TABLE> <TABLE NAME="plagiarism_programming_jplag" COMMENT="containing JPlag scanning status of the lastest report" PREVIOUS="plagiarism_programming_rpt" NEXT="plagiarism_programming_moss"> <FIELDS> <FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="true" NEXT="submissionid"/> <FIELD NAME="submissionid" TYPE="char" LENGTH="20" NOTNULL="false" SEQUENCE="false" PREVIOUS="id" NEXT="status"/> <FIELD NAME="status" TYPE="char" LENGTH="20" NOTNULL="false" SEQUENCE="false" PREVIOUS="submissionid" NEXT="directory"/> <FIELD NAME="directory" TYPE="char" LENGTH="200" NOTNULL="false" SEQUENCE="false" PREVIOUS="status" NEXT="message"/> <FIELD NAME="message" TYPE="char" LENGTH="200" NOTNULL="false" SEQUENCE="false" PREVIOUS="directory" NEXT="settingid"/> <FIELD NAME="settingid" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="false" PREVIOUS="message" NEXT="progress"/> <FIELD NAME="progress" TYPE="int" LENGTH="3" NOTNULL="false" UNSIGNED="false" SEQUENCE="false" COMMENT="Show the progress (in percentage) of the current status" PREVIOUS="settingid" NEXT="token"/> <FIELD NAME="token" TYPE="char" LENGTH="32" NOTNULL="false" SEQUENCE="false" COMMENT="Contain a random token for security when a child process is initiated. This token is then compared with the token passed in to ensure it is a valid call" PREVIOUS="progress" NEXT="error_detail"/> <FIELD NAME="error_detail" TYPE="text" LENGTH="medium" NOTNULL="false" SEQUENCE="false" COMMENT="The detail of the error messages - for developer to see only" PREVIOUS="token"/> </FIELDS> <KEYS> <KEY NAME="primary" TYPE="primary" FIELDS="id"/> </KEYS> <INDEXES> <INDEX NAME="submissionid_index" UNIQUE="false" FIELDS="submissionid" COMMENT="Index for submissionid for fast searching"/> </INDEXES> </TABLE> <TABLE NAME="plagiarism_programming_moss" COMMENT="The table contains parameters and status for the last time the assignment is scanned with MOSS" PREVIOUS="plagiarism_programming_jplag" NEXT="plagiarism_programming_reslt"> <FIELDS> <FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="true" NEXT="settingid"/> <FIELD NAME="settingid" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="false" PREVIOUS="id" NEXT="resultlink"/> <FIELD NAME="resultlink" TYPE="char" LENGTH="200" NOTNULL="false" SEQUENCE="false" PREVIOUS="settingid" NEXT="status"/> <FIELD NAME="status" TYPE="char" LENGTH="20" NOTNULL="false" SEQUENCE="false" PREVIOUS="resultlink" NEXT="message"/> <FIELD NAME="message" TYPE="text" LENGTH="small" NOTNULL="false" SEQUENCE="false" PREVIOUS="status" NEXT="progress"/> <FIELD NAME="progress" TYPE="int" LENGTH="3" NOTNULL="false" UNSIGNED="false" SEQUENCE="false" COMMENT="The progress (in percentage) of the lattest MOSS scanning" PREVIOUS="message" NEXT="token"/> <FIELD NAME="token" TYPE="char" LENGTH="32" NOTNULL="false" SEQUENCE="false" COMMENT="For verification of valid call when a forked process initiated by the main process. The token is first generated by the main process and stored in this field, and passed that token to the forked process. It is a valid call if the token passed is the same with the token stored" PREVIOUS="progress" NEXT="error_detail"/> <FIELD NAME="error_detail" TYPE="text" LENGTH="medium" NOTNULL="false" SEQUENCE="false" COMMENT="Detail of the encountered error. Valid only when status=error" PREVIOUS="token"/> </FIELDS> <KEYS> <KEY NAME="primary" TYPE="primary" FIELDS="id"/> </KEYS> <INDEXES> <INDEX NAME="settingid_index" UNIQUE="false" FIELDS="settingid" COMMENT="Index for settingid for fast searching"/> </INDEXES> </TABLE> <TABLE NAME="plagiarism_programming_reslt" COMMENT="store the result of the scanning, each record contains a pair" PREVIOUS="plagiarism_programming_moss" NEXT="plagiarism_programming_cours"> <FIELDS> <FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="true" NEXT="student1_id"/> <FIELD NAME="student1_id" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="false" SEQUENCE="false" PREVIOUS="id" NEXT="student2_id"/> <FIELD NAME="student2_id" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="false" SEQUENCE="false" PREVIOUS="student1_id" NEXT="additional_codefile_name"/> <FIELD NAME="additional_codefile_name" TYPE="char" LENGTH="255" NOTNULL="false" SEQUENCE="false" COMMENT="not null when the pair match is a comparison between a student and an additional code file" PREVIOUS="student2_id" NEXT="similarity1"/> <FIELD NAME="similarity1" TYPE="number" LENGTH="5" NOTNULL="false" UNSIGNED="true" SEQUENCE="false" DECIMALS="2" COMMENT="similarity rate of student id 1" PREVIOUS="additional_codefile_name" NEXT="similarity2"/> <FIELD NAME="similarity2" TYPE="number" LENGTH="5" NOTNULL="false" UNSIGNED="true" SEQUENCE="false" DECIMALS="2" COMMENT="similarity rate of student id 2" PREVIOUS="similarity1" NEXT="comparison"/> <FIELD NAME="comparison" TYPE="char" LENGTH="100" NOTNULL="false" SEQUENCE="false" PREVIOUS="similarity2" NEXT="comments"/> <FIELD NAME="comments" TYPE="char" LENGTH="150" NOTNULL="false" SEQUENCE="false" PREVIOUS="comparison" NEXT="reportid"/> <FIELD NAME="reportid" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="false" SEQUENCE="false" COMMENT="foreign key to table programming_report" PREVIOUS="comments" NEXT="mark"/> <FIELD NAME="mark" TYPE="char" LENGTH="1" NOTNULL="false" SEQUENCE="false" COMMENT="used to mark a pair of assignment as having unusually high similarities" PREVIOUS="reportid"/> </FIELDS> <KEYS> <KEY NAME="pk_programming_result_id" TYPE="primary" FIELDS="id"/> </KEYS> <INDEXES> <INDEX NAME="repst1st2_index" UNIQUE="false" FIELDS="reportid, student1_id, student2_id" COMMENT="Index for reportid, student1_id, student2_id for fast searching"/> </INDEXES> </TABLE> <TABLE NAME="plagiarism_programming_cours" COMMENT="containing the courses which is enabled when level is set to global" PREVIOUS="plagiarism_programming_reslt" NEXT="plagiarism_programming_date"> <FIELDS> <FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="true" NEXT="course"/> <FIELD NAME="course" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="false" SEQUENCE="false" PREVIOUS="id"/> </FIELDS> <KEYS> <KEY NAME="id" TYPE="primary" FIELDS="id" COMMENT="Primary key"/> </KEYS> <INDEXES> <INDEX NAME="course_index" UNIQUE="false" FIELDS="course" COMMENT="Index for course for fast searching"/> </INDEXES> </TABLE> <TABLE NAME="plagiarism_programming_date" COMMENT="containing the scheduled scan date of each enabled assignment. One assignment can have several scan date" PREVIOUS="plagiarism_programming_cours"> <FIELDS> <FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="true" NEXT="scan_date"/> <FIELD NAME="scan_date" TYPE="int" LENGTH="20" NOTNULL="true" UNSIGNED="false" SEQUENCE="false" PREVIOUS="id" NEXT="finished"/> <FIELD NAME="finished" TYPE="int" LENGTH="1" NOTNULL="true" UNSIGNED="false" SEQUENCE="false" PREVIOUS="scan_date" NEXT="settingid"/> <FIELD NAME="settingid" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="false" SEQUENCE="false" PREVIOUS="finished"/> </FIELDS> <KEYS> <KEY NAME="date_primary" TYPE="primary" FIELDS="id" COMMENT="primary key"/> </KEYS> <INDEXES> <INDEX NAME="setfinsca_index" UNIQUE="false" FIELDS="settingid, finished, scan_date" COMMENT="Index for settingid, finished, scan_date for fast searching"/> </INDEXES> </TABLE> </TABLES> </XMLDB> when i input this code it only uploads a single column into my database
<html> <head> <title>MySQL file upload example</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body> <form action="try2.php" method="post" enctype="multipart/form-data"> <input type="file" name="uploaded_file"><br> <input type="submit" name="submit"value="Upload file"> </form> <p> <a href="list_files.php">See all files</a> </p> </body> <?php $con=mysqli_connect("localhost","root","","book"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } if(isset($_POST['submit'])) { $fname = $_FILES['uploaded_file']['name']; $chk_ext = explode(".",$fname); if(strtolower($chk_ext[1]) == "csv") { $filename = $_FILES['uploaded_file']['tmp_name']; $handle = fopen($filename, "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $sql = "INSERT into data(name,Groups,phone_number) values('$data[0]','$data[1]','$data[2]')"; $result=mysqli_query($con,$sql) or die(mysql_error()); } fclose($handle); echo "Successfully Imported"; } else { echo "Invalid File"; } } ?> </html> Hello, I'm having some frustrations right now. I have built an application form where an applicant inputs their info and then uploads their resume. Even though the resume gets uploaded to a directory on the server i would also like the file name of the resume to get inserted into the mysql database so that I can easily see which resume matches which applicant...if that makes sense. At any rate I'm able to get everything else to work, the applicant's info gets inserted into the database, the resume gets uploaded to the directory, i just can't seem to get the resume file name to also insert into the database. Most of the info i have found on this subject through googleing and the like has been a little over my head and/or a little more complex than what i'm looking for. Here is an extremely simplified version of what I have right now. I have excluded the 'connect to database' code since it's working fine and really doesn't have anything to do with this issue: Code: [Select] <?php $target_path = "docs/"; $target_path = $target_path . basename( $_FILES['resume']['name']); $first_name=$_POST['first_name']; $last_name=$_POST['last_name']; $middle_init=$_POST['middle_init']; $resume=$_POST['resume']; mysql_query("INSERT INTO `intern` VALUES ('$first_name', '$last_name', '$middle_init', '$resume')") ; if (move_uploaded_file($_FILES['resume']['tmp_name'], $target_path)); ?> HTML begins after that. At any rate, any info, help, etc. you could provide would be GREATLY appreciated! Thanks! Hi friends i need a small help in importing csv files into mySQL database table i tried all possible options but i am no where... here is the example for what i am trying to do Mysql DB name = raw Table name is = dump +--------------------+--------------------+ + Account + Bal + +--------------------+--------------------+ + + + +--------------------+--------------------+ CSV Format 50************13, 11095 When they upload the file it should automatically get inserted into appropriate fields any help would be great i tried all possible scripts found in the net could nothing is happening hi- i'm trying to browse for a CSV file and then upload it to my mysql database. i found the code below and not working. i don't get any errors. the connection to the database is ok bcz i get the existing results but not the ones from the CSV file added to the db.. any ideas? Code: [Select] <?php ob_start(); require_once('../../connections/congif.php'); mysql_select_db($dbname, $db); $sql_get_project="SELECT * FROM gifts_tbl ORDER BY autoID DESC LIMIT 25"; $get_project = mysql_query($sql_get_project, $db) or die(mysql_error()); $row_get_project = mysql_fetch_assoc($get_project); //database connect info here //check for file upload if(isset($_FILES['csv_file']) && is_uploaded_file($_FILES['csv_file']['tmp_name'])){ //upload directory $upload_dir = "csv_dir/"; //create file name $file_path = $upload_dir . $_FILES['csv_file']['name']; //move uploaded file to upload dir if (!move_uploaded_file($_FILES['csv_file']['tmp_name'], $file_path)) { //error moving upload file echo "Error moving file upload"; } //open the csv file for reading $handle = fopen($file_path, 'r'); //turn off autocommit and delete the product table mysql_query("BEGIN"); while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) { //Access field data in $data array ex. $name = $data[0]; //Use data to insert into db $sql = sprintf("INSERT INTO gifts_tbl (player_id) VALUES ('%s)", mysql_real_escape_string($name) ); mysql_query($sql) or (mysql_query("ROLLBACK") and die(mysql_error() . " - $sql")); } unlink($file_path); } 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>Gifts</title> </head> <body> <h1>Testing for CSV upload</h1> <form action="" method="post"> <input type="file" name="csv_file"> <input type="submit" name="csv_submit" value="Upload CSV File"> </form> <h2>Results</h2> <?php do { ?> <ul> <li><?php echo $row_get_project['player_id']; ?></li> </ul> <?php } while ($row_get_project = mysql_fetch_assoc($get_project)); ?> </body> </html> Hello all. Here is my script... Code: [Select] if (isset($_POST['submit'])) { if (is_uploaded_file($_FILES['filename']['tmp_name'])) { echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "<br></h1>"; echo "<h2>Displaying contents:</h2>"; readfile($_FILES['filename']['tmp_name']); echo "<br>"; echo $headers; } $handle = fopen($_FILES['filename']['tmp_name'], "r"); $header = fgetcsv($handle); while(! feof($handle)){ while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $import="INSERT into CSVtest($header[0],$header[1],$header[2],$header[3],$header[4]) values ('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]')"; mysql_query($import) or die(mysql_error()); } } fclose($handle); echo "Done"; } This is the way how I insert data into database according to header even it's not arranged same as the table column. If the csv has only "cell,firstname,lastname,," (and my table has only these 3 columns as well) then it still working...but if there are "cell,address,company,firstname,lastname" then it will show me unknown column error. Actually I wish to have a function that even there are many columns in csv that not exist in the table it still can just pick the right column and insert into table. Can anyone give me hints on how to change my script?I know there are many errors...it's really embarrassed to show my low standard script... Thanks in advance. I have a MySQL database with each record of a person who has registered for an event, I am displaying the information on a web page for a user, but he wants to be able to print out all the records in alphabetical order by last name, first name later on so he will have a hard copy of each person who has registered at the table when they arrive. How can I write each record to a Txt file that he can print out later that will be formated with the record contents along with each fields definition (Ex. Last Name - Smith, First Name - John, etc)? I am very new to php and am trying to create a simple application that uploads a PDF file to a database. I have one field for the Volume Number and on file field for the PDF to be uploaded. My issue is i can't get the PDF to upload or insert the name of the pdf (eg volume1.pdf) into the data base. I would also like to point out that I know i have a low post count, but i only seek help when i truly need it and have exhausted all other resources... Here is what i have, please go easy on me this is my first round at php: Code: [Select] <?php if(isset($_POST['submit'])){ $vol_num = $_POST['vol_num']; $pdf = $_FILES['pdf']['name']; $path = '../pdf/'.$_FILES['pdf']['name']; move_uploaded_file($_FILES["pdf"]["tmp_name"], $path); mysql_query("INSERT INTO volumes set vol_num='$vol_num', vol_link='$pdf'") or die (mysql_error()); echo "<script>location.href='add_volume.php'</script>"; } ?> what am i doing wrong here? Thanks in advance I have mysql exported in the following sql format: Code: [Select] - CREATE TABLE IF NOT EXISTS `pma_history` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(64) COLLATE utf8_bin NOT NULL DEFAULT '', `db` varchar(64) COLLATE utf8_bin NOT NULL DEFAULT '', `table` varchar(64) COLLATE utf8_bin NOT NULL DEFAULT '', `timevalue` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `sqlquery` text COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`), KEY `username` (`username`,`db`,`table`,`timevalue`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='SQL history for phpMyAdmin' AUTO_INCREMENT=3761 ; -- -- Dumping data for table `pma_history` -- INSERT INTO `pma_history` (`id`, `username`, `db`, `table`, `timevalue`, `sqlquery`) VALUES (2, 'root', 'information_schema', 'FILES', '2010-03-04 19:26:33', 'SELECT * FROM `FILES`') Just as an example anyway. What I need to be able to do, is import this using PHP. Does anyone know of a suitable class for doing this? I could make my own, but I cant quite work out the best way to seperate the queries out? Thanks I have a table I am trying to import to mySQL I am having trouble assigning the right variable which represents a column header to the correct column header in the mySQL table. <?php /********************************/ /* Code at http://legend.ws/blog/tips-tricks/csv-php-mysql-import/ /* Edit the entries below to reflect the appropriate values /********************************/ $databasehost = "xxx"; $databasename = "xxx"; $databasetable = "names"; $databaseusername ="xxx"; $databasepassword = "xxx"; $fieldseparator = "\t"; $lineseparator = "\n"; $csvfile = "AddEnt2.txt"; $con = @mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error()); @mysql_select_db($databasename) or die(mysql_error()); $fcontents = file ('AddEnt2.txt'); # expects the csv file to be in the same dir as this script for($i=0; $i<sizeof($fcontents); $i++) { $line = trim($fcontents[$i],'\t'); // '\t' for tab delimeted $arr = explode('\t', $line); // '\t' for tab delimeted $name=implode("','",$arr); $PA=implode("','",$line); # if your data is comma separated # instead of tab separated # change the '\t' above to ',' $sql = "insert into $databasetable values ('$PA','$name')"; $sql = str_replace("''", mysql_escape_string("NULL"), $sql); $sql = str_replace("' '", mysql_escape_string("NULL"), $sql); mysql_query($sql); echo $sql ."<br>\n"; if(mysql_error()) { echo mysql_error() ."<br><b><font color=red>\n</b>"; } } ?> Hello, I am new to PHP and am trying to make a script that will ftp into the server via a cron of every hour or so and save the data to a mysql table. The first step is to draw variables out of information in the file via ftp. Its a ban list for a game server I run. How could I get php to single out the ban reason, admin, etc. the looks like this Code: [Select] "STEAM_0:0:42741441" { "name" "good mom" "unban" "0" "time" "1329161245" "admin" "(Console)" "reason" "no more trolling for you" } "STEAM_0:1:40563669" { "unban" "0" "admin" "Headcrap(STEAM_0:1:42287608)" "time" "1332855999" "reason" "" } "STEAM_0:1:17693550" { "name" "ʎɖɑɱ" "time" "1323055427" "modified_time" "1323221308" "unban" "0" "modified_admin" "Strategos(STEAM_0:0:26662109)" "admin" "Strategos(STEAM_0:0:26662109)" "reason" "And so died the trolling" } Example: Code: [Select] <?php $bannedid = "STEAM_0:0:42741441"; $bannedby "(console)"; // and so on ?> I am trying to import csv file to wordpress using database.the files are uploaded in database but its not coming in wordpress . The code is as below: <?php if(isset($_POST['submit'])) { $fname=$_FILES["file"]["name"]; $datetime=$_FILES["file"][""]; $chk_ext = explode(".",$fname); if(strtolower(($chk_ext[1]) == "csv")) { $filename = $_FILES['file']['tmp_name']; $handle = fopen($filename, "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $fname=addslashes($data[0]); $datetime=addslashes($data[1]); $products=addslashes($data[2]); $preset=addslashes($data[3]); $format=addslashes($data[4]); $sql = "INSERT into ".$wpdb->prefix ."facebook(filename,datetime,products,preset,format) values('$fname','$datetime','$products','$preset','$format')"; mysql_query($sql) or die(mysql_error()); } fclose($handle); echo "Successfully Imported"; } else { echo "Invalid File"; } } ?> <form enctype="multipart/form-data" action="" method="post" name="uploadDetails"> <table cellpadding="4" cellspacing="0" border="1"> <tr> <td><label for="upload_a_file">Upload File:</label></td> <td><input type="file" name="file" id="upload_a_file" /></td> </tr> <tr> </tr> </table> <input type="hidden" name="fd_upload" value="1" /> <input type="submit" value="Submit" class="allbutton" name="submit" /> </form> Hope you will help me i was working on a mini project that imports csv file to the database through ajax and it's working fine
<?php if(!empty($_FILES["marks_file"]["name"])) { $connect = mysqli_connect("localhost", "root", "", "dbname"); $output = ''; $allowed_ext = array("csv"); $extension = end(explode(".", $_FILES["marks_file"]["name"])); if(in_array($extension, $allowed_ext)) { $file_data = fopen($_FILES["marks_file"]["tmp_name"], 'r'); fgetcsv($file_data); while($row = fgetcsv($file_data)) { $name = mysqli_real_escape_string($connect, $row[0]); $Physics = mysqli_real_escape_string($connect, $row[1]); $Maths = mysqli_real_escape_string($connect, $row[2]); $Chemistry = mysqli_real_escape_string($connect, $row[3]); $Biology = mysqli_real_escape_string($connect, $row[4]); $SST = mysqli_real_escape_string($connect, $row[5]); $query = " INSERT INTO csv (name, Physics, Maths, Chemistry, Biology, SST) VALUES ('$name', '$Physics', '$Maths', '$Chemistry', '$Biology' , '$SST') "; mysqli_query($connect, $query); } $select = "SELECT * FROM csv ORDER BY id DESC"; $result = mysqli_query($connect, $select); $output .= ' <table class="table table-bordered"> <tr> <th width="25%" >name</th> <th width="15%" >Physics</th> <th width="15%" >Maths</th> <th width="15%" >Chemistry</th> <th width="15%" >Biology</th> <th width="15%" >SST</th> </tr> '; while($row = mysqli_fetch_array($result)) { $output .= ' <tr> <td>'.$row["name"].'</td> <td>'.$row["Physics"].'</td> <td>'.$row["Maths"].'</td> <td>'.$row["Chemistry"].'</td> <td>'.$row["Biology"].'</td> <td>'.$row["SST"].'</td> </tr> '; } $output .= '</table>'; echo $output; } else { echo 'errorx'; } } else { echo "errory"; } ?> however the imported csv files inserts null values in the tables because the format of all csv files assigned to me are in the exact same format: ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,Fields,Physics~75,Maths~50,Chemistry~65,Bio~85,SST~100 ,,,Name1,10,25,35,42,62 ,,,Name2,80,45,45,45,25 ,,,Name3,63,25,63,36,36 ,,,Name4,82,36,75,48,42 ,,,Name5,45,45,78,25,24 ,,,Name6,36,36,15,75,36 ,,,Name7,99,45,24,24,45 ,,,Name8,45,85,85,85,96 i changed my code a bit modified the functions to espace blank spaces and not return null values in the data tables while (($row = fgetcsv($file_data, 1000, ",")) !== FALSE) { if ((string) $row[0] != '0' and empty($row[0])) { continue; } $name = mysqli_real_escape_string($connect, $row[0]); $Physics = mysqli_real_escape_string($connect, $row[1]); $Maths = mysqli_real_escape_string($connect, $row[2]); $Chemistry = mysqli_real_escape_string($connect, $row[3]); $Biology = mysqli_real_escape_string($connect, $row[4]); $SST = mysqli_real_escape_string($connect, $row[5]); $query = " INSERT INTO csv (name, Physics, Maths, Chemistry, Biology, SST) VALUES ('$name', '$Physics', '$Maths', '$Chemistry', '$Biology' , '$SST') "; mysqli_query($connect, $query); } But it doesn't work with the specified csv files i think the ajax call breaks and that's why nothing happens.However it works fine with csv files without blank spaces Edited March 19, 2019 by zetastreak Hello I am trying to do a simple CSV import of a file and then upload to mysql. I am basing my code on an example I have found and I am getting the error message 'invalid file'. The example used includes a text box for the file import field and I am referencing the file from my computer in that box 'Users/James/name.csv' My code is as follows: HTML <form action="results.php?data=upload" method='post'> Import File : <input type='text' name='sel_file' size='20'> <input type='submit' name='submit' value='submit'> </form> PHP if ($b == 'upload') { $fname = $_FILES['sel_file']['name']; $chk_ext = explode(".",$fname); if(strtolower($chk_ext[1]) == "csv") { $filename = $_FILES['sel_file']['tmp_name']; $handle = fopen($filename, "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $sql = "INSERT into ".$db['name']."(field1,field2,field3,field4) values('$data[0]','$data[1]','$data[2]', '$data[3]')"; mysql_query($sql) or die(mysql_error()); } fclose($handle); echo "Successfully Imported"; } else { echo "Invalid File"; } } my file format is: 1,23,1,5 1,24,2,5 1,25,3,5 1,26,4,5 1,27,5,5 1,28,6,5 1,29,7,5 1,30,8,5 1,31,9,5 1,32,10,5 If anybody can help that would be good - or perhaps point out if I am going about this the wrong way - cheers I have a problem with my project. i want to import Excel sheet directly into mysql database for PHP language without any conversion of Excel sheet into another format. i am very fed about this from last two weeks. So Please help me How I Do it. any expert please help me Hey guys, I'm having a nightmare at the moment.
I am trying to import a CSV file into a MySQL table, some of the data is interested properly into the rows however some of the CSV row do not get imported.
Here is my PHP script:
<?php $databasehost = "localhost"; $databasename = "name"; $databasetable = "import"; $databaseusername="username"; $databasepassword = "password"; $fieldseparator = ","; $lineseparator = "\n"; $enclosedbyquote = '"'; $csvfile = "db-core/feed/csv/test.csv"; if(!file_exists($csvfile)) { die("File not found. Make sure you specified the correct path."); } try { $pdo = new PDO("mysql:host=$databasehost;dbname=$databasename", $databaseusername, $databasepassword, array( PDO::MYSQL_ATTR_LOCAL_INFILE => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ) ); } catch (PDOException $e) { die("database connection failed: ".$e->getMessage()); } $pdo->exec("TRUNCATE TABLE `$databasetable`"); $affectedRows = $pdo->exec(" LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." REPLACE INTO TABLE `$databasetable` FIELDS OPTIONALLY ENCLOSED BY ".$pdo->quote($enclosedbyquote)." TERMINATED BY ".$pdo->quote($fieldseparator)." LINES TERMINATED BY ".$pdo->quote($lineseparator)." IGNORE 1 LINES"); echo "Loaded a total of $affectedRows records from this csv file.\n"; ?>As you can see the script is importing the CSV into the table however only 40 of the rows are added to the SQL table when there are actually 80 rows in the CSV. I am also telling the script to IGNORE 1 LINES if that has anything to do with the issue. Here is one of the rows from the CSV file: "AETA83919","AETV34458584","SD57VUP","BLACK","Diesel","2007","76778","Hatchback","3","VAUXHALL","CORSA","1.3 CDTi [90] SXi 3dr [AC]","1200","3989","","Manual","http://images.autoexposure.co.uk/AETA83919/AETV34458584_1b.jpg","0","3","","0","2007 57 reg VAUXHALL CORSA 1.3 CDTi [90] SXi 3dr [AC], Manual, Hatchback, Diesel, 76,778 miles. BLACK, Comprehensive Warranty Included In Price. HPI Checked! Pre Delivery Health Check!, 5 seats, LOVELY VAUXHALL CORSA SXI 1.3CDTI SXI WITH AIR CONDITIONING!! VERY WELL CARED FOR AND MAINTAINED AND JUST SERVICED BY DRIVEN CAR SALES LTD AT 76K!! GREAT COMBINATION OF PERFORMANCE AND ECONOMY!! VIEWING AND TEST DRIVING IS RECOMMENDED!! EACH CAR COMES WITH A MININIUM 9 MONTHS MOT. FULL MECHANICAL HEALTH CHECK GUARANTEES CAR IS PREPARED TO THE HIGHEST STANDARD. COMPREHENSIVE RAC WARRANTY INCLUDED. DRIVEN CAR SALES WELCOME ANY INSPECTION. BUY WITH CONFIDENCE AND REASSURANCE AS DRIVEN CAR SALES LTD ARE OFFICIAL MEMBERS OF RETAIL MOTOR INDUSTRY FEDERATION. VIEW OUR REVIEWS ON TRUSTPILOT. 3,989","","0","1","","UK","0","","0","0","","","",""As far as I can see everything looks fine with the row, all of the rows in the CSV end like this. One thing I have noticed is it looks like the rows that are missing are in fact being placed in the last column of every other row here is an example: So as you can see it looks like one row is being inserted into the last column of some rows and I am so confused to why this might be happening? Any ideas? This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=358188.0 |