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!
Related
I have this code where i write comment in a textarea field and select a picture and sumbit to mysqli database through php, but the problem im having is when i only select a picture to upload or when i write a comment/texts in the textarea and select a picture to upload it works but then when i only write comment/texts in the textarea field and submit it doesn't work.
And also i want to create a comment reply "quote" , like to click reply on a comment then quote and reply the comment.
// My compose form
<form method="post" action="process.php" enctype='multipart/form-data'>
<textarea class="text-area" cols="75" name="comment" type="text" rows="5" placeholder="write message"></textarea><br>
<input type='file' style="width:257px" name='fileToUpload' ><br>
<input class="submitButton" type='submit' value='Send'>
</form>
// My process.php code
<?php
// start username session
session_start();
//connect to database
require_once ("dtb.php");
$commentSenderName = $_SESSION['username'];
$date = date('Y-m-d H:i:s');
$comment = isset($_POST['comment']) ? htmlspecialchars($_POST['comment']) : "";
//Directory where to upload file
$name = $_FILES['fileToUpload']['name'];
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
//Select file type
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
//Valid file extensions
$extensions_arr = array("jpg","jpeg","png","gif","NULL");
//Check extension
if( in_array($imageFileType,$extensions_arr) ){
//Upload file
move_uploaded_file($_FILES['fileToUpload']['tmp_name'],$target_dir.$name);
//Insert data into tables
$sql = "INSERT INTO tblcomment(comment,comment_sender_name,date,image) VALUES ('". $comment . "','" . $commentSenderName . "','" . $date . "','".$name."')";
$result = mysqli_query($conn, $sql);
if (! $result) {
$result = mysqli_error($conn);
}
echo "<p style='padding-left:22px;padding-top:10px;font-family:verdana;font-size:20px'> Post entered... </p>";
header("Refresh: 3; url=mysite.com");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
// This is the code that fetches and display data from mysql database
$sql = "SELECT comment_sender_name,date,comment,image FROM tblcomment";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
//output data of each row
while($row = mysqli_fetch_assoc($result)) {
$name = $row['comment_sender_name'];
$time = $row['date'];
$msg = $row['comment'];
$img = $row['image'];
$now = array("<span><b style='font-size:25px'> $name </b></span>","<span style='font-size:14px;color:#474747;padding-left:40px;'><i>$time</i></span>");
$message = "<p style='color:#232323;font-size:20px;font-weight:bold'> $msg </p>";
$image_src = "<a href='#'><img src='upload/$img' style='width:550px;height:320px;border-radius:5px'></img></a>";
echo '<table border="0" style="padding-left:25px;box-sizing;height:450px;width:400px;">
<tr>
<td>' .$now[0] .$now[1] .$message .$image_src. "<br/><br/><br/><br/>". '</td>
</tr>';
}
} else {
echo "<p style='padding-left:22px'> 0 results </p>";
}
//Free result set
mysqli_free_result($result);
?>
Im not getting any kind of error.
Aside from my comment above with the many, many vulnerabilities in your code, the issue looks like you assume you always have a $_FILES. If you didn't upload a file, $_FILES['fileToUpload']['name']; is not going to exist. Check for it with if (isset($_FILES['fileToUpload'])) { and act on that information appropriately. You probably did get an error, or more specifically a warning, but it is in your web servers log file.
I have been Trying to check if selected row is last in MYSQL data records, if it is last then go back to first record.
Here is what I have done so far:
$fps = #fopen('number.txt', "r+");
$somay = fread($fps, filesize('number.txt'));
fclose($fps);
$num = ($somay+1);
$file = "number.txt";
$fh = fopen($file,'w+') or die("cant open file");
fwrite($fh,$num);
fclose($fh);
$sql = "SELECT #last_id := MAX(id),token FROM `token` where `id` = '".$somay."'";
if (!$result = $mysqli->query($sql)) {
echo "Sorry, the website is experiencing problems.";
echo "Error: Our query failed to execute and here is why: \n";
echo "Query: " . $sql . "\n";
echo "Errno: " . $mysqli->errno . "\n";
echo "Error: " . $mysqli->error . "\n";
exit;
}
if ($result->num_rows === 0) {
echo "We could not find a match for ID, sorry about that. Please try again.";
exit;
}
while ($tokennek = $result->fetch_assoc()) {
$token = $tokennek[token];
$tokenid = $tokennek[last_id];
}
if($somay == $tokenid){
$file = "number.txt";
$fh = fopen($file,'w+') or die("cant open file");
fwrite($fh,1);
fclose($fh);
}
Let me make it more clear here what I am doing is saving a file named number.txt to keep record of token which is already been used and go to next token/row.
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>
How to Validate Employee Id in Importing File in .CSV format to SQL?
*a code that check if the data is already exist.
-->sample: if the Employee Id already exist it promts "Employee ID already Exist"..
if the rows in csv, you can make a array of csv rows.
$list =array();
$id = array();
while( ($rows= getcsv($hande)) !== false)
{
array_push($list, $rows);
array_push($id, $rows['emplyee_id']);
}
then check mysql or database
$check_id = implode(",", $id);
$que = "select employ_id from table where employ_id in ($check_id)";
at this time you can find employ_ids from database.
if you make employee_id column unique, your code would be like this
$result=mysqli_query($db_con", "insert into table (employ_id) values ('$empoy_id')";
if($result == false) // if employ_id alreay exists in table $result is false
{
}
but as i know, the best way using index is checking key is exists before inserting data not after inserting query failed.
This is my code:
`<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
$a=$_FILES["file"]["tmp_name"];
echo $a;
$connect = mysql_connect('localhost','root','');
if (!$connect) {
die('Could not connect to MySQL: ' . mysql_error());
}
//your database name
$cid =mysql_select_db('cgi_warehouse',$connect);
// path where your CSV file is located
//define('CSV_PATH','C:/xampp/htdocs/');
//<!-- C:\\xampp\\htdocs -->
// Name of your CSV file
$csv_file = $a;
if (($getfile = fopen($csv_file, "r")) !== FALSE) {
$data = fgetcsv($getfile, 1000, ",");
while (($data = fgetcsv($getfile, 1000, ",")) !== FALSE) {
//$num = count($data);
//echo $num;
//for ($c=0; $c < $num; $c++) {
$result = $data;
$str = implode(",", $result);
$slice = explode(",", $str);
$col1 = $slice[0];
$col2 = $slice[1];
$col3 = $slice[2];
$col4 = $slice[3];
$col5 = $slice[4];
$col6 = $slice[5];
$col7 = $slice[6];
$col8 = $slice[7];
$col9 = $slice[8];
$col10 = $slice[9];
$col11 = $slice[10];
$col12 = $slice[11];
$col13 = $slice[12];
$col14 = $slice[13];
$col15 = $slice[14];
$col16 = $slice[15];
$query = "INSERT INTO tools(tools_id, item_description, category_id, sn, qty, price, supplier, frm, location, ref_no, sender, receiver, date_receive, date_added, status, remarks) VALUES('".$col1."','".$col2."','".$col3."','".$col4."','".$col5."','".$col6."','".$col7."','".$col8."','".$col9."','".$col10."','".$col11."','".$col12."','".$col13."','".$col14."','".$col15."','".$col16."')";
$s=mysql_query($query, $connect );
}
}
echo "<script>alert('Record successfully uploaded.');window.location.href='#';</script>";
mysql_close($connect);
}
?>`
Hi guys i have an php excel issue.
The problem is that i have an excel file that has several rows and columns, the deal is that i want to import only from specific row position for example A11 or C12. How can i tell this in php?
Here is the column selection code:
$csv_file = $a;
if (($getfile = fopen($csv_file, "r")) !== FALSE) {
while(! feof($getfile))
{
$data = fgetcsv($getfile, NULL,"\t");
$col1 = $data[0];
$col2 = $data[1];
$col3 = $data[2];
$col4 = $data[3];
$col5 = $data[4];
$col6 = $data[5];
$col7 = $data[6];
$col8 = $data[7];
$query = "INSERT INTO $tableName(cod, den_material, furnizor, cant_reper ,lg, cod_furnizor, obs, data) VALUES('".$col1."','".$col2."','".$col3."','".$col4."','".$col5."','".$col6."','".$col7."','".$col8."')";
$s=mysql_query($query);
}
Here is the full code:
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 10240) . " Kb<br>";
//echo "Stored in: " . $_FILES["file"]["tmp_name"];
$a=$_FILES["file"]["tmp_name"];
//echo $a;
$tableName = str_replace('.txt','',$_FILES["file"]["name"]);
$connect = mysql_connect('localhost','root','password');
if (!$connect) {
die('Could not connect to MySQL: ' . mysql_error());
}
//your database name
$cid =mysql_select_db('database_test',$connect);
if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$tableName."'"))!=1){
$table = mysql_query("CREATE TABLE `$tableName` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`cod` TEXT NOT NULL,
`den_material` TEXT NOT NULL,
`furnizor` VARCHAR(255) NOT NULL,
`cant_reper` VARCHAR(255) NOT NULL,
`lg` VARCHAR(255) NOT NULL,
`cod_furnizor` VARCHAR(255) NOT NULL,
`obs` TEXT(255) NOT NULL,
`data` DATE ,
PRIMARY KEY (`id`)
);");
if(!$table){
die("Upload failed");
}
}
// path where your CSV file is located
//define('CSV_PATH','C:/xampp/htdocs/');
//<!-- C:\xampp\htdocs -->
// Name of your CSV file
$csv_file = $a;
if (($getfile = fopen($csv_file, "r")) !== FALSE) {
while(! feof($getfile))
{
$data = fgetcsv($getfile, NULL,"\t");
$col1 = $data[0];
$col2 = $data[1];
$col3 = $data[2];
$col4 = $data[3];
$col5 = $data[4];
$col6 = $data[5];
$col7 = $data[6];
$col8 = $data[7];
$query = "INSERT INTO $tableName(cod, den_material, furnizor, cant_reper ,lg, cod_furnizor, obs, data) VALUES('".$col1."','".$col2."','".$col3."','".$col4."','".$col5."','".$col6."','".$col7."','".$col8."')";
$s=mysql_query($query);
}
}
echo "<script>alert('Data succesfully added!');window.location.href='index.php';</script>";
//echo "File data successfully imported to database!!";
}
?>
Hope you cand help me, thanks in advance! :)
Fair warning: I have never used fgetcsv for anything however I understand the principle.
However working from the manual on php.net I have created a loop that starts reading only at the row and col that are specified. I picked random values but you can make them whatever you want. A=0, B=1 and so forth. So I have said something like all data from row 5 and from col C.
<?php
$row = 1;
$mydata = array();
$wantrow = 4;
$wantcol = 2;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data); // number of fields in the line
$row++;
for ($c=0; $c < $num; $c++) {
if($c<$wantcol){
// this is what we do not want
}elseif($row<$wantrow){
// also we do not want this
}else{
// ah-ha, we do want this
$mydata[$row][$c] = $data[$c];
}
}
}
fclose($handle);
}
?>
You would then have a two dimensional array of the values in that section. I have chosen to be a little clumsy looking so you can easily understand the logic of what I am trying to demonstrate.
Actually you could make it fair more readable like this:
if( ($c>=3) && ($row>=5) ){
$mydata[$row][$c] = $data[$c];
}
You could apply further limits with the if statements and set an upper limit too but I am sure you know how to do that.
if( ($c>=3) && ($c<=22) && ($row>=5) && ($row<=6) ){
$mydata[$row][$c] = $data[$c];
}
This would give you square inside of C6 to E23 only.
Also in you application you probably want to do something more useful than just shoving the data into an array. I imagine you probably want to embed the data into SQL or something like that.
YYMV. I have not tested this code but it would be roughly like that.
http://php.net/manual/en/function.fgetcsv.php