Uploading CSV file to MySql table by PHP - php

I am trying to write a code on PHP that will allow me to upload some specific columns from a CSV file to MySql table. I'm very new on PHP. Tried to watch some of tutorials, but they were not much helpful as they are only showing the examples on very little CSV files such as 2 rows and 2 columns... I am talking about approx 100 cols and hundreds of rows. I only need the information from some specific columns to add my table. Here's my code so far.. It gives Undefined offset error. I am open to new ideas.
$connection = mysqli_connect('localhost', 'root', 'MyPass', 'database') or die('connection failed');
if(isset($_POST['upload'])){
$fname = $_FILES['sel_file']['name'];
echo 'upload file name: '.$fname.' ';
$chk_ext = explode(".",$fname);
if(strtolower(end($chk_ext)) == "csv")
{
$filename = $_FILES['sel_file']['tmp_name'];
$handle = fopen($filename, "r");
while (($data = fgetcsv($handle, 10, ",")) !== FALSE)
{
$sql = "INSERT into turbolister(site,format,currency) values('$data[0]','$data[1]','$data[2]')";
mysqli_query($connection, $sql) or die(mysqli_error($connection));
}
fclose($handle);
echo "Successfully Imported";
}
else
{
echo "Invalid File";
}
} `
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
Import File: <input class="btn btn-primary" type="file" name='sel_file' size='20'> <br>
<input class="btn btn-primary" type="submit" name="upload" value='upload'>
</form>

For such a project I would recommend you another way of doing this.
For me there are some open questions:
Is it correct, that one line in csv is one line in database?
Is there a header-line in csv containing the column-names so that the order of the columns can change?
I've overworked your script a little bit - what you need to do is to adjust the behavior to your needs and also change the separation item for header-columns and normal-lines.
<?php
// Just for development purpose
error_reporting(E_ALL);
ini_set('display_errors', 1);
try {
// Try to connect to mysql-server with pdo instated of using mysqli
$dbCon = new PDO('mysql:dbname=testdb;host=127.0.0.1', 'root', 'MyPass');
} catch (PDOException $e) {
// Catching error && stoping script
die('<strong>Error:</strong> Connection failed with error "' . $e->getMessage() . '"');
}
if(isset($_POST['upload'])) {
$filename = $_FILES['sel_file']['name'];
// Show filename of uploaded file
echo 'Uploaded file: ' . $filename . '<br>';
// Check file-extension for csv
// #ToDo: Determinate which mime-type your csv-files generally have and check for mime-type additionally or instated
if (pathinfo($filename, PATHINFO_EXTENSION) == 'csv') {
// Get file-content
$fileContent = file_get_contents($_FILES['sel_file']['tmp_name']);
// Split file into lines
$rows = explode("\n", $fileContent);
// Check for data
if (empty($rows) || count($rows) < 2) {
// Shwo error-messages && stopping script
die('<strong>Error:</strong> CSV-File does not contain data!');
}
// Get columns of header-row
$header = explode('|', $rows[0]);
// Set query variables
$query = 'INSERT INTO test (';
$values = '(';
// Build query based on header-columns
for($a = 0; $a < count($header); ++$a) {
// Add column
$query .= $header[$a] . ', ';
$values .= ':column' . $a . ', ';
}
// Finish query
$query = substr($query, 0, -2) . ') VALUES ' . substr($values, 0, -2) . ')';
// Loop through rows, starting after header-row
for ($b = 1; $b < count($rows); ++$b) {
// Split row
$row = explode(',', $rows[$b]);
// Check that row has the same amount of columns like header
if (count($header) != count($row)) {
// Show message
echo '<strong>Warning:</strong> Skipped line #' . $b . ' because of missing columns!';
// Skip line
continue;
}
// Create statement
$statement = $dbCon->prepare($query);
// Loop through columns
for ($c = 0; $c < count($row); ++$c) {
// Bind values from column to statement
$statement->bindValue(':column' . $c, $row[$c]);
}
// Execute statement
$result = $statement->execute();
// Check for error
if ($result === false) {
// Show info
echo '<strong>Warning:</strong>: DB-Driver returned error on inserting line #' . $b;
}
}
// #ToDo: Get numbers of row before import, check number of rows after import against number of rows in file
// Show success message
echo '<span style="color: green; font-weight: bold;">Import successfully!</span>';
} else {
die('<strong>Error:</strong> The file-extension of uploaded file is wrong! Needs to be ".csv".');
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
Import File: <input class="btn btn-primary" type="file" name='sel_file' size='20'> <br>
<input class="btn btn-primary" type="submit" name="upload" value='upload'>
</form>

Related

HTML PHP Form Upload to PHPMyAdmin

I am trying to pass users data through internal html form via Uploading a .csv with 1st row as header, but facing 2 issues:
'hashedpwords.csv' file is generated successfully on same path, but column name of Passwords gets hashed too, even though in code there's a skip first line of file.
data is not being submitted at all to my database table, I couldn't figure out why.
code below:
PHP:
<?php
require_once 'PHP/dbinfo.php';
$dbc = new mysqli($hn,$user,$pass,$db) or die("Unable to connect");
$has_title_row = true;
$not_done = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
if(is_uploaded_file($_FILES['csvfile']['tmp_name'])){
$filename = basename($_FILES['csvfile']['name']);
if(substr($filename, -3) == 'csv'){
$tmpfile = $_FILES['csvfile']['tmp_name'];
if (($fh = fopen($tmpfile, "r")) !== FALSE) {
$i = 0;
while (($items = fgetcsv($fh, 1000000, ",")) !== FALSE) {
if($has_title_row === true && $i == 0){ // skip the first row if there is a tile row in CSV file
$i++;
continue;
}
set_time_limit(0);
$infile = $filename;
$myfile = "hashedpwords.csv";
$reader = fopen($infile, 'r');
$writer = fopen($myfile, 'w');
$buffer = '';
while ($line = fgetcsv($reader)) {
$line[8] = password_hash($line[8], PASSWORD_DEFAULT);
$buffer .= implode(',', $line) . "\n";
if (strlen($buffer) > 1024) {
fwrite($writer, $buffer);
$buffer = '';
}
}
fwrite($writer, $buffer);
fclose($reader);
fclose($writer);
$sql = "LOAD DATA LOCAL INFILE '".$myfile."'
INTO TABLE usersdata
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\n'
(depid, pid, authid, mainrole, firstname, lastname, username, userinitials, password, mail, phonenumber)";
$result = $dbc->query($sql);
echo "Success";
if (!$result) die("Fatal Error");
if (mysqli_query($dbc, $sql)){
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($dbc);
}
$i++;
}
}
// if there are any not done records found:
if(!empty($not_done)){
echo "<strong>There are some records could not be inserted</strong><br />";
print_r($not_done);
}
}
else{
die('Invalid file format uploaded. Please upload CSV.');
}
}
else{
die('Please upload a CSV file.');
}
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Users Data Upload</title>
</head>
<body>
<form enctype="multipart/form-data" action="userdatauploadfunction.php" method="post" id="add-users">
<table cellpadding="5" cellspacing="0" width="500" border="0">
<tr>
<td class="width"><label for="image">Upload CSV file : </label></td>
<td><input type="file" name="csvfile" id="csvfile" value=""/></td>
<td><input type="submit" name="uploadCSV" value="Upload" /></td>
</tr>
</table>
</form>
</body>
</html>
I fixed the code and it runs properly now. Modified code is below:
PHP:
<?php
$has_title_row = true;
$not_done = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
//echo "success";
if(is_uploaded_file($_FILES['csvfile']['tmp_name'])){
//echo "success";
$filename = basename($_FILES['csvfile']['name']);
if(substr($filename, -3) == 'csv'){
//echo "success";
$tmpfile = $_FILES['csvfile']['tmp_name'];
if (($fh = fopen($tmpfile, "r")) !== FALSE) {
//echo "success";
$i = 0;
set_time_limit(0);
$infile = $filename;
$myfile = "hashedpwords.csv";
$reader = fopen($infile, 'r');
$writer = fopen($myfile, 'w');
$buffer = '';
while ($line = fgetcsv($reader)) {
$line[9] = password_hash($line[9], PASSWORD_DEFAULT);
$buffer .= implode(',', $line) . "\n";
if (strlen($buffer) > 1024) {
fwrite($writer, $buffer);
$buffer = '';
}
}
fwrite($writer, $buffer);
fclose($reader);
fclose($writer);
$sql = "LOAD DATA LOCAL INFILE '".$myfile."'
INTO TABLE usersdata
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(uid, depid, pid, authid, mainrole, firstname, lastname, username, userinitials, password, mail, phonenumber)";
require_once 'PHP/dbinfo.php';
$dbc = new mysqli($hn,$user,$pass,$db) or die("Unable to connect");
mysqli_options($dbc, MYSQLI_OPT_LOCAL_INFILE, true);
$result = mysqli_query($dbc, $sql);
//echo "Success";
}
// if there are any not done records found:
if(!empty($not_done)){
echo "<strong>There are some records could not be inserted</strong><br />";
print_r($not_done);
}
}
else{
die('Invalid file format uploaded. Please upload CSV.');
}
}
else{
die('Please upload a CSV file.');
}
}

Using PHPEXCEL with SQLSRV

I am looking into a way of taking a pre-defined order template (XLSX), which my customer completes and uploads, which then uses PHP Excel to insert the data into my sql database.
I have this working fine using mysql, but really need it to work with sql server, as our database (which pre-dates me) is sql server.
The code I am using for mysql is:
if(isset($_POST['submit'])) {
if(isset($_FILES['uploadFile']['name']) && $_FILES['uploadFile']['name'] != "") {
$allowedExtensions = array("xls","xlsx");
$ext = pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION);
if(in_array($ext, $allowedExtensions)) {
$file_size = $_FILES['uploadFile']['size'] / 1024;
if($file_size < 50) {
$file = "uploads/".$_FILES['uploadFile']['name'];
$isUploaded = copy($_FILES['uploadFile']['tmp_name'], $file);
if($isUploaded) {
include("db.php");
include("Classes/PHPExcel/IOFactory.php");
try {
//Load the excel(.xls/.xlsx) file
$objPHPExcel = PHPExcel_IOFactory::load($file);
} catch (Exception $e) {
die('Error loading file "' . pathinfo($file, PATHINFO_BASENAME). '": ' . $e->getMessage());
}
//An excel file may contains many sheets, so you have to specify which one you need to read or work with.
$sheet = $objPHPExcel->getSheet(0);
//It returns the highest number of rows
$total_rows = $_POST["xNum"]+1;
//It returns the highest number of columns
$highest_column = $sheet->getHighestColumn();
echo '<div class="container-fluid">';
echo '<h4 style="margin-top: 40px;">Data from Excel file</h4>';
echo '<table cellpadding="5" cellspacing="1" border="1" class="table table-striped table-bordered table-sm table-hover">';
$query = "insert into `tblorderitems` (`Vehicle`, `DriveTrain`, `Product`, `otherProduct`, `Price`, `RegNo`, `StockNo`, `ChassisNo`, `CommNo`, `PartNo`, `InStockDate`, `PlannedDate`) VALUES ";
//Loop through each row of the worksheet
for($row =2; $row <= $total_rows; $row++) {
//Read a single row of data and store it as a array.
//This line of code selects range of the cells like A1:D1
$single_row = $sheet->rangeToArray('A' . $row . ':' . $highest_column . $row, NULL, TRUE, FALSE);
echo "<tr>";
//Creating a dynamic query based on the rows from the excel file
$query .= "(";
//Print each cell of the current row
foreach($single_row[0] as $key=>$value) {
echo "<td>".$value."</td>";
$query .= "'".mysqli_real_escape_string($con, $value)."',";
}
$query = substr($query, 0, -1);
$query .= "),";
echo "</tr>";
}
$query = substr($query, 0, -1);
echo '</table>';
// At last we will execute the dynamically created query an save it into the database
mysqli_query($con, $query);
if(mysqli_affected_rows($con) > 0) {
echo '<script> alert("Order Added");</script>';
} else {
echo '<script> aleft("Can\'t update database table! try again"); </script>';
}
// Finally we will remove the file from the uploads folder (optional)
unlink($file);
} else {
echo '<script> alert("File not uploaded"); </script>';
}
} else {
echo '<script> alert("Maximum file size should be 50kb"); </script>';
}
} else {
echo '<script> alert("Incorrect File Type"); </script>';
}
} else {
echo '<script> alert("Select an XLSX File First"); </script>';
}
}
echo '</div>';
?>
Anyone any ideas what I would change to get this to work with sqlsrv?
Thanks
David
You just have to replace the calls to pure mysqli functions.
Replace mysqli_query with sqlsrv_query
Replace mysqli_affected_rows with sqlsrv_rows_affected
Replace mysqli_real_escape_string with your own function mssql_escape :
function mssql_escape($data) {
if(is_numeric($data))
return $data;
$unpacked = unpack('H*hex', $data);
return '0x' . $unpacked['hex'];
}

CSV file upload with data validation

I'm trying to upload a *.CSV file to the database using PhP.
I can't really make the data validation work with the file upload.
The script should see if the data from certain cells is valid by searching in the db's tables.
The file should not be uploaded if there are errors!
Here's the code!
<form name="import" method="post" enctype="multipart/form-data">
<input type="file" name="file" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
include ("connection2.php");
if(isset($_POST["submit"]))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;
$err = 0;
if ($_FILES["file"]["type"]=='application/vnd.ms-excel')
{
while(($filesop = fgetcsv($handle, 3000, ",")) !== false)
{
$tid = trim($filesop[0]);
$beneficiar = ucwords(strtolower(trim($filesop[1])));
$locatie = ucwords(strtolower(trim($filesop[2])));
$localitate = ucwords(strtolower(trim($filesop[3])));
$judet = ucwords(strtolower(trim($filesop[4])));
$adresa = ucwords(strtolower(trim($filesop[5])));
$model = trim($filesop[6]);
$query = mysqli_query("SELECT * FROM modele WHERE `model` = '".$model."'");
if (!empty($query)) {
$err ++;
$msg=$msg."Model error on row $c <br>";
}
$query = mysqli_query("SELECT * FROM judete WHERE `nume` = '".$judet."'");
if (!empty($query)) {
$err ++;
$msg=$msg."Judet error on row $c <br>";
}
$query = mysqli_query("SELECT * FROM beneficiari WHERE `nume` = '".$beneficiar."'");
if (!empty($query)) {
$err ++;
$msg=$msg." Beneficiar error on row $c <br>";
}
// if (strlen($tid)!==8){
// $err ++;
// $msg=$msg."TID length error at row $c <br>";
// }
$c ++;
}
if ($err!==0){
echo $msg; echo "ERROR COUNT= ".$err;
break;
}
$c=0;
while(($filesop = fgetcsv($handle, 3000, ",")) !== false)
{
$tid = trim($filesop[0]);
$beneficiar = ucwords(strtolower(trim($filesop[1])));
$locatie = ucwords(strtolower(trim($filesop[2])));
$localitate = ucwords(strtolower(trim($filesop[3])));
$judet = ucwords(strtolower(trim($filesop[4])));
$adresa = ucwords(strtolower(trim($filesop[5])));
$model = trim($filesop[6]);
$qry=mysql_query("SELECT id FROM beneficiari WHERE `nume` = '".$beneficiar."'");
while ($row = mysql_fetch_assoc($qry)){
$id_client=$row['id'];
echo "Beneficiar=".$row['id'];
}
$qry_id_model=mysql_query("SELECT id FROM modele WHERE `model` = '".$model."'");
while ($row = mysql_fetch_assoc($qry_id_model)){
$id_model=$row['id'];
echo "Model=".$row['id'];
}
echo "MODEL2:".$id_model;
$adresa1 = $adresa.", ".$localitate;
if ($c!==0){
$sql = mysql_query("INSERT INTO equipments
(id_client, model, tid, beneficiar, adresa, agentie, judet)
VALUES
('$id_client','$id_model','$tid','$beneficiar','$adresa1','$locatie','$judet')");
}
$c = $c + 1;
}
if($sql){
echo "You database has imported successfully. You have inserted ". $c ." recordes <br>";
}else{
echo "Sorry! There is some problem.<br>";
}
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
}
else echo "NOT CSV!";
}
?>
What's wrong here?
When i try to run it the data is not uploaded and no errors are shown, I left errors in the file to test it. Also i uploaded a clean file and also the file is not uploaded. If i break the code in 2 and make 2 separate codes, one to verify and one to upload, the upload works, but i need the verification and the upload to be in the same code. also tried mysql_query in stead of mysqli_query.
The procedural style of mysqli_query takes 2 arguments - the connection and the query. You're only passing the query.
You can read the official documentation for the mysqli_query() method here:
http://php.net/manual/en/mysqli.query.php
A suggestion as to how to approach this would be something like:
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
if(!$link)
{
echo("Unable to connect");
} else {
if($ret = mysqli_query($link, "SELECT id FROM modele WHERE `model` = '".mysqli_real_escape_string($link, $model)."'"))
{
$data = mysqli_fetch_assoc($ret);
echo($data["id"]);
}
mysqli_close($link);
}
Important: Note my use of mysqli_real_escape_string in the example above - your current code leaves you vulnerable to SQL injection attacks.
first of all you should upload this file on a temporary folder and save the file name. Then use getCSV php function to read properly the file.
Finally you can check if it's all OK, insert on database, and, if not, echo an error message and delete the file (remember we saved the name and we know the static route of the temporary folder).
Hope it helps!

Export Data in excel and then import from excel using PHP. DB is MySQL

--I have some rows from my table which I would like to export in excel format. This step is equivalent to the user enters the search criteria and all matching rows will be exported in an excel file.
--The user makes changes to the excel file. Add or update rows.
--The user upload the file and all updated rows gets updated in the database and all added rows gets added in the database.
All this I want to do in PHP and the database it is using is MySQL. Servers are running Linux (no COM!)
I have exporting and importing part I explained above done seperately.
I am using PHPExcelReader to read the file and save it. But that requires the user to download the template first, copy data from exported excel and paste it in the template.
For exporting, I am just creating a simple HTML table and fool the browser, its an excel!
Excel will open HTML table but ofcourse while saving that file, it will change the format and make it valid excel file.
Please throw some ideas on how can I make it work? :/
Thank you ... I greatly appreciate your help.
I would like to suggest you PHPExcel library.
http://phpexcel.codeplex.com/
You can do import, export, pdf, etc. I think this is a great library.
**
EXPORTING PURPOSE
**
<?php
mysql_connect("localhost","root","");
mysql_select_db("school");
?>
<html>
<head>
<script type="text/javascript" src="../js/exp_stdsub.js"></script>
</head>
<hr />
<u><h3>Export your Data here</h3></u>
<form action="" method="post">
<select name="expstd" id="expstd" onclick="return expsubjs(this.value);">
<option>Select Standared</option>
<?php
$exe_sel_std = mysql_query("SELECT * from s_standared");
while($r_sel_std = mysql_fetch_array($exe_sel_std)){
$sel_stdid = $r_sel_std['std_id'];
$sel_std = $r_sel_std['std']; ?>
<option value="<?php echo $sel_stdid; ?>"><?php echo $sel_std; ?></option>
<?php } ?>
</select></td>
<input type="submit" class="btn btn-green" name="exp_stdque" value="Export Standardwise Question">
</form>
</table>
<?php
//EDIT YOUR MySQL Connection Info:
$DB_Server = "localhost"; //your MySQL Server
$DB_Username = "root"; //your MySQL User Name
$DB_Password = ""; //your MySQL Password
$DB_DBName = "school"; //your MySQL Database Name
$DB_TBLName = "s_question"; //your MySQL Table Name
if(isset($_POST['exp_stdque'])) {
$exstdid = $_POST['expstd'];
//$DB_TBLName, $DB_DBName, may also be commented out & passed to the browser
//as parameters in a query string, so that this code may be easily reused for
//any MySQL table or any MySQL database on your server
//DEFINE SQL QUERY:
//edit this to suit your needs
$sql = "Select * from $DB_TBLName WHERE std_id = $exstdid";
//Optional: print out title to top of Excel or Word file with Timestamp
//for when file was generated:
//set $Use_Titel = 1 to generate title, 0 not to use title
$Use_Title = 1;
//define date for title: EDIT this to create the time-format you need
$now_date = DATE('m-d-Y H:i');
//define title for .doc or .xls file: EDIT this if you want
$title = "Dump For Table $DB_TBLName from Database $DB_DBName on $now_date";
/*
Leave the connection info below as it is:
just edit the above.
(Editing of code past this point recommended only for advanced users.)
*/
//create MySQL connection
$Connect = #MYSQL_CONNECT($DB_Server, $DB_Username, $DB_Password)
or DIE("Couldn't connect to MySQL:<br>" . MYSQL_ERROR() . "<br>" . MYSQL_ERRNO());
//select database
$Db = #MYSQL_SELECT_DB($DB_DBName, $Connect)
or DIE("Couldn't select database:<br>" . MYSQL_ERROR(). "<br>" . MYSQL_ERRNO());
//execute query
$result = #MYSQL_QUERY($sql,$Connect)
or DIE("Couldn't execute query:<br>" . MYSQL_ERROR(). "<br>" . MYSQL_ERRNO());
//if this parameter is included ($w=1), file returned will be in word format ('.doc')
//if parameter is not included, file returned will be in excel format ('.xls')
IF (ISSET($w) && ($w==1))
{
$file_type = "msword";
$file_ending = "doc";
}ELSE {
$file_type = "vnd.ms-excel";
$file_ending = "xls";
}
//header info for browser: determines file type ('.doc' or '.xls')
HEADER("Content-Type: application/$file_type");
HEADER("Content-Disposition: attachment; filename=database_dump.$file_ending");
HEADER("Pragma: no-cache");
HEADER("Expires: 0");
/* Start of Formatting for Word or Excel */
IF (ISSET($w) && ($w==1)) //check for $w again
{
/* FORMATTING FOR WORD DOCUMENTS ('.doc') */
//create title with timestamp:
IF ($Use_Title == 1)
{
ECHO("$title\n\n");
}
//define separator (defines columns in excel & tabs in word)
$sep = "\n"; //new line character
WHILE($row = MYSQL_FETCH_ROW($result))
{
//set_time_limit(60); // HaRa
$schema_insert = "";
FOR($j=0; $j<mysql_num_fields($result);$j++)
{
//define field names
$field_name = MYSQL_FIELD_NAME($result,$j);
//will show name of fields
$schema_insert .= "$field_name:\t";
IF(!ISSET($row[$j])) {
$schema_insert .= "NULL".$sep;
}
ELSEIF ($row[$j] != "") {
$schema_insert .= "$row[$j]".$sep;
}
ELSE {
$schema_insert .= "".$sep;
}
}
$schema_insert = STR_REPLACE($sep."$", "", $schema_insert);
$schema_insert .= "\t";
PRINT(TRIM($schema_insert));
//end of each mysql row
//creates line to separate data from each MySQL table row
PRINT "\n----------------------------------------------------\n";
}
}ELSE{
/* FORMATTING FOR EXCEL DOCUMENTS ('.xls') */
//create title with timestamp:
IF ($Use_Title == 1)
{
ECHO("$title\n");
}
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
//start of printing column names as names of MySQL fields
FOR ($i = 0; $i < MYSQL_NUM_FIELDS($result); $i++)
{
ECHO MYSQL_FIELD_NAME($result,$i) . "\t";
}
PRINT("\n");
//end of printing column names
//start while loop to get data
WHILE($row = MYSQL_FETCH_ROW($result))
{
//set_time_limit(60); // HaRa
$schema_insert = "";
FOR($j=0; $j<mysql_num_fields($result);$j++)
{
IF(!ISSET($row[$j]))
$schema_insert .= "NULL".$sep;
ELSEIF ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
ELSE
$schema_insert .= "".$sep;
}
$schema_insert = STR_REPLACE($sep."$", "", $schema_insert);
//following fix suggested by Josue (thanks, Josue!)
//this corrects output in excel when table fields contain \n or \r
//these two characters are now replaced with a space
$schema_insert = PREG_REPLACE("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
PRINT(TRIM($schema_insert));
PRINT "\n";
}
}
}
?>
IMPORTING FROM EXCEL INTO MySQL USING PHP
<table>
<form enctype="multipart/form-data" action="" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
<tr>
<td><h5><b>Select Standared</b></h5></td>
<td><select name="chap_sel_std" id="chap_sel_std">
<option>Select Standared</option>
<?php
$exe_sel_std = mysql_query("SELECT * from s_standared");
while($r_sel_std = mysql_fetch_array($exe_sel_std)){
$sel_stdid = $r_sel_std['std_id'];
$sel_std = $r_sel_std['std'];?>
<option value="<?php echo $sel_stdid; ?>"><?php echo $sel_std;?></option>
<?php } ?>
</select></td>
</tr>
<tr>
<td><h5><b>Select Font</b></h5></td>
<td><select name="sel_f_gn_que">
<option>Select Font</option>
<?php
$xf = mysql_query("SELECT * from s_font");
while($rquef = mysql_fetch_array($xf)){
$f_id = $rquef['f_id'];
$f_name = $rquef['f_name']; ?>
<option value="<?php echo $f_id; ?>"><?php echo $f_name; }?> </option>
</select></td>
</tr>
<tr>
<td><h5><b>Upload Question<h5><b></td>
<td>
<input type="file" name="file" id="file" class="btn">
</td>
</tr>
<tr>
<td></td>
<td colspan="2"><input type="submit" class="btn btn-green big" name="add_que" value="Add Questions"></td>
<td><input type="submit" name="saveandexit" class="" value="Finish" onclick="close();"></td>
</tr>
</form>
</table>
</div>
<?php
$data = array();
//$db =& DB::connect("mysql://root#localhost/names", array());
//if (PEAR::isError($db)) { die($db->getMessage()); }
//quetype difficulty standard subject chap que marks
function add_person($quetype,$dif, $subject,$chap_name,$que,$marks)
{
global $data, $db;
//$sth = $db->prepare( "INSERT INTO names VALUES( 0, ?, ?, ?, ? )" );
// $db->execute( $sth, array( $first, $middle, $last, $email ) );
$data []= array(
'quetype' => $quetype,
'difficulty' => $dif,
'subject' => $subject,
'chap' => $chap_name,
'que' => $que,
//'ans' => $ans,
'marks' => $marks
);
}
if(!isset($_FILES['file']['tmp_name'])){
echo "";
}elseif($_FILES['file']['tmp_name'])
{
$dom = DOMDocument::load( $_FILES['file']['tmp_name'] );
$rows = $dom->getElementsByTagName( 'Row' );
$first_row = true;
foreach ($rows as $row)
{
if ( !$first_row )
{
$quetype = "";
$dif = "";
$subject = "";
$chap_name = "";
$que = "";
//$ans = "";
$marks = "";
$index = 1;
$cells = $row->getElementsByTagName( 'Cell' );
foreach( $cells as $cell )
{
$ind = $cell->getAttribute( 'Index' );
if ( $ind != null ) $index = $ind;
if ( $index == 1 ) $quetype = $cell->nodeValue;
if ( $index == 2 ) $dif = $cell->nodeValue;
if ( $index == 4 ) $subject = $cell->nodeValue;
if ( $index == 6 ) $chap_name = $cell->nodeValue;
if ( $index == 8) $que = $cell->nodeValue;
//if ( $index == 9) $ans = $cell->nodeValue;
if ( $index == 9) $marks = $cell->nodeValue;
$index += 1;
}
add_person($quetype,$dif, $subject,$chap_name,$que,$marks);
if(isset($_POST['add_que'])){
$chap_sel_std = $_POST['chap_sel_std'];
echo $simquefnt = $_POST['sel_f_gn_que'];
//que_id quetype_id chap_id sub_id std_id que dif_id marks que_cdate
//$chap_sel_std = $_POST['chap_sel_std']; //que_id quetype_id chap_id sub_id std_id que dif_id marks que_cdate
mysql_query("INSERT INTO
s_question
VALUES (null,'$quetype','$chap_name','$subject','$chap_sel_std','$que','NO IMAGE','$dif','$marks','$simquefnt','$current')");
// header("location:../admin/quetionaris.php#tabs-que");
echo "Successfully Added";
}
}
$first_row = false;
}
}
?>

need help fetching the id from mysql table with php

I have several forms, with different fields and purposes.
So i tought "hey, i'll build a generic insert.php page to input data to my database".
Ok, so far so good.
But now i need to link files to each record, so my form has a <input type="file"> field.
What i really want to do is to allow the user to select several files (pictures, videos), create a directory named like the table plus the id of the record that is being inserted (upload/$tablename/$id/), store the files and add the path to the database.
Something like:
ID | NAME | WEBPAGE | FILES
01 | john | john.com | /upload/tblWebpages/01/
02 | mike | mike.net | /upload/tblWebpages/02/
19 | jimy | jimy.org | /upload/tblWebpages/19/
Because i don't know how many files will be inserted or their names, and later i intend to fetch all images in that directory and display it.
Is it possible to know the record ID from the table at the time the upload is being processed?
Because, as explained above, i'd like to store the files under a directory called $ID.
How should i add it to my query?
Alright, to the code:
insert.php
include('classes/class.upload.php');
$server = "localhost";
$user = "root";
$password = "xxxxx";
$database = "myDB";
$tabela = $_POST['tabela'];
$diretorio = "upload/".$tabela."/";
mysql_connect($server,$user,$password);
mysql_select_db($database) or die("Unable to select database" . mysql_error());
// create an array to hold your filnames
$images = array();
$files = array();
foreach ($_FILES['imagem'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
foreach ($files as $file) {
$handle = new Upload($file);
if ($handle->uploaded) {
$handle->Process($diretorio);
if ($handle->processed) {
echo 'OK ';
// add the filename to the array
$images[] = $handle->file_dst_pathname;
}
else { echo 'Upload error: ' . $handle->error; }
}
else { echo 'Upload error: ' . $handle->error; }
unset($handle);
}
foreach ($_POST as $field => $value) {
if (!preg_match("/$value/i", $tabela)) {
if (preg_match("/$field/i", 'data')) {$value = date('Y-m-d', strtotime($value));}
else {$value = mysql_real_escape_string($value);}
$campo .= $field . ',';
$valor .= '\'' . $value . '\'' . ',';
$query = "INSERT INTO $tabela ($campo) VALUES ($valor)";
$query = str_replace(",)",")",$query);
//echo " inside foreach RESULT = $result and QUERY = $query <br>";
}
}
$result = mysql_query($query);
echo " outside foreach RESULT = $result and QUERY = $query <br>";
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
mysql_close();
form.php (simplified)
<form method="POST" action="insert.php" class="classeform" enctype="multipart/form-data">
<label for="namee" class="lbl-d-input">Name: </label>
<input type="text" name="namee" id="namee" class="field">
<label for="webpage" class="lbl-d-input">Webpage: </label>
<input type="text" name="webpage" id="webpage" class="field">
<label for="files" class="lbl-d-input">Files: </label>
<input type="file" name="files[]" id="files" class="field-img">
<input type="hidden" name="tabela" value="mytbl">
<input type="submit" value="Enviar" class="btn-enviar">
</form>
Got it to work with mysql_insert_id()
Do you see your echo'd values?
I would start by writing out some debug code
For example:
After this line of code
if (!preg_match("/$value/i", $tabela)) {
I would put
print("Value Matched");
That way you know your getting into your for loop. Also I noticed your not appending to your $query variable inside the loop so the db entry is never being added?

Categories