PHP/MYSQL - Upload Excel/CSV to MySql table - php

I recently built a web app which allows teachers to give grades to students and a lot of other stuff. Right now I'm adding a feature that gives the teacher the option to upload an excel/csv file with all the grades to the different students. My code seems fine however there are some issues with it and I can't figure out why. What happens is I get a bunch of blank records on my 'avaliacoes' table when I should only be getting 2 records.
How my excel looks :
1 (row) : naluno, uc, tipo, nota
2 (row) : r2011251, BD, exame, 15
3 (row) : r2011223, BD, exame, 16
(the first row isn't accounted for when inserting into the table)
My HTML code for the form (inside Diretor-Curso.php) :
<form class="form-group" action="lancarnota3.php" method="post" enctype="multipart/form-data">
<label class="control-label" for="uc">Enviar Ficheiro Excel/CSV com notas</label>
<br>
<input id="fileSelect" type="file" name="file" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
<br>
<input type="submit" class="btn btn-default botao2" name="Submeter" value="Submeter"></button>
</form>
My PHP page (lancarnota3.php) which handles the upload :
<?php
if(isset($_POST["Submeter"]))
{
$conn = mysqli_connect("localhost", "root", "", "teste");
$conn->set_charset("utf8");
// Check connection
if($conn === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
//$filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($_FILES["file"]["tmp_name"], "r");
$count = 0;
while (($emapData = fgetcsv($file, 1000, ",")) !== FALSE)
{
$count++;
if($count>1){
$sql = "INSERT into avaliacoes (naluno, uc, tipo, nota) values ('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')";
mysqli_query($conn, $sql);
}
}
fclose($file);
include 'Diretor-Curso.php';
echo "<script> replace('lancarnotas2'); </script>";
}
else
{
include 'Diretor-Curso.php';
echo "<script> replace('lancarnotas6'); </script>";
}
}
// close connection
mysqli_close($conn);
?>
Any idea how to make it work?

Are you sure that your data file doesn't contain empty line? Check the MySQL general log to see which queries were executed. I expect you will see the queries inserting the blank records in the log.
You could simply add a condition before the INSERT to check that you are trying to insert "non-empty" data, or perform additional validation to ensure that the data is indeed complete.

This was a silly one, so basically I had to change the comma (",") to a semi colon (";") because the csv was separating everything like that for some reason. and now it works perfectly. oh well hope this helps anyone :)

Related

SQL Statement fails to insert values into database, but only appends an ID?

** EDIT: I resolved the issue on my own. Thanks for all your help. **
I'm trying to insert image files to my database for testing, and found that my code stopped working (it was able to do what it did before).
When I submit the image to the database it appends the image id, but not the 'username' and 'img_name'(filename) fields - these two fields just show up as empty strings. Can you tell me what's wrong with my code and how I can fix this? Your help is very appreciated
This is a summary of my database:
Database Name: photos
Table Name: images
Row Names: id[primary key], username, img_name
And my HTML and PHP codes for uploading image file to the database:
<form method="post" action="uploadindex5.php" enctype="multipart/form-data">
<input type="file" name="membimg">
<input type="submit" name="membupload">
</form>
if (isset($_POST['membupload'])) {
$username = $_SESSION['username'];
$membupload = $_POST['membupload'];
$membimg = $_POST['membimg']['name'];
$membtarg = "images/".basename($_FILES['membimg']['name']);
$membmuf = move_uploaded_file($_FILES['membimg']['tmp_name'], $membtarg);
$servername = "localhost";
$sroot = "root";
$password = "";
$dbname = "photos";
$conn = mysqli_connect($servername,$sroot,$password,$dbname);
if (mysqli_connect_errno()) {
throw new Exception(mysqli_connect_error(), mysqli_connect_errno());
}
$sql = "INSERT INTO images (username, img_name) VALUES ('$username', '$membimg')";
$result = mysqli_query($conn, $sql);
if ($membmuf) {
$msg = "Image uploaded";
} else {
$msg = "Upload failed";
}
}
I'd put dummy values in for the session and post values just hard code it and see if the PHP code is working and then determine if those variables are even set once i verified my php code works properly. Once you hard code those questionable variables then you can run the PHP page without submiting it with the form or ajax or however you are calling it. The PHP page will report the errors if you have PHP error reporting on. Javascript console may even tell you if there is a 500 internal server error which indicates the PHP script isn't working.

TRUNCATE table on button click

Somehow my query is not working when I click the button. What I'm trying to do is to TRUNCATE the table when the user click the button.
if(isset($_POST['extract'])){
#mysql_query("TRUNCATE TABLE temp");
}
I also tried this:
if(isset($_POST['extract'])){
$myquery = mysql_query("TRUNCATE TABLE temp");
}
Why is it not executing?
This is the html code:
<input type="submit" value="Extract CSV file" name="extract">
So here is how would approach to debugging this problem:
1) Check if the form is actually submitted. Put this on the top of your PHP file (note: for debugging only)
echo "I have reached my destination";
die();
2) Check if you are submitting via POST or GET. Or easier, replace $_POST with $_REQUEST, which contains both $_POST and $_GET.
if(isset($_REQUEST['extract'])){
3) Ensure the connection to the database is opened.
4) Provide your script the means to tell you if the query executed successfully
$myquery = mysql_query("TRUNCATE TABLE temp") or die("Error: ".mysql_error());
5) Ensure you are looking at the right place for the changes
You would be surprised how easy it is to get confused with multiple databases opened.
Double check the ip address of your DB server, your DB and table name and contents.
One of the above 5 steps will tell you what went wrong.
Please follow the following code. This will help you.
<?php
mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed");
mysql_select_db("DataBase Name")or die("Connection Failed");
$temptable = $_POST['temptable'];
$query = "truncate table $temptable";
if(mysql_query($query)){
echo "table empty";
} else{
echo "fail";
} ?>

Cannot store picture in database(no error messages appear)

Hello I am here yet again with another problem.
As I followed a tutorial I tried to save images to my database. It all worked fine and dandy with no error messages but for some reason the image refuse the get stored. Nothing show up at all!
<html>
<body>
<form action="test.php" method="POST" enctype="multipart/form-data">
<input type="file" name="image"><input type="submit" name="submit" value="Upload" />
</form>
<?php
if(isset($_POST['submit'])) {
mysql_connect("localhost","root","") or die("Could not find database!");
mysql_select_db("Image") or die("Could not find database!");
$imageName = mysql_real_escape_string($_FILES["image"]["name"]);
$imageData = mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["image"]["type"]);
if(substr($imageType,0,5) == "image") {
mysql_query("INSERT INTO 'blob' VALUES ('','$imageName','$imageData')");
echo "File uploaded!";
}
else
{
echo "Only images are allowed!";
}
}
?>
</body>
</html>
Database:
id, name, image:
int(Auto increment), varchar(40), mediumblob(because of the size)
The only odd thing about this is that "file_get_contents" is blacked out(I use notepad++).
Otherwise I don't see whats wrong, I have checked guides and whatnot but the thing is that I need to use this method in another form that have a large amount of information stored(15 fields including a description). I am still very new to this and its hard to know what to keep and how to write the best way. But anyway if you can help me it would be awesome.
If you have any questions regardning anything or just some tips just comment.
Your table name blob should be surrounded by back-ticks, not apostrophes.
However, I recommend that you change the name of this table to something that is not a reserved word in MySQL.

Error while displaying images from mysql php using blob datatype

I am trying to display images from my mysql database using php. The image is not getting displayed fully. It gets cut while trying to display an image more than 200 kb (determined from trials , but not too sure).
HTML Code:
<form enctype="multipart/form-data" action="insertimage.php" method="post" name="changer">
<input name="MAX_FILE_SIZE" value="10240000" type="hidden">
<input name="image" accept="image/jpeg|image/jpg|image|JPG|image/png|image/gif" type="file">
<input value="Submit" type="submit">
PHP Code:
<?php
require('myconnect.php');
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
// Create the query and insert
// into our database.
$query = "Update whyangry.posts set Photo='$data' where Pid=2";
$results = mysql_query($query, $con);
// Print results
print "Thank you, your file has been uploaded.";
$sql = "SELECT * FROM helpme.posts WHERE Pid=2";
$res = mysql_query($sql,$con);
while ($res1=mysql_fetch_assoc($res))
{
$content = $res1['Photo'];
$id=$res1['Pid'];
}
echo '<img src="data:image/png|image/jpeg|image/gif;base64,' . base64_encode( $content ) . '" />';
echo 'Hello world.';
}
else {
print "No image selected/uploaded";
}
?>
Also i am getting the below error while uploading file in phpmyadmin to a blob datatype
UPDATE `helpme`.`posts` SET `Photo` = 0xffd8ffe000104a46494600010201006000600000ffe10f074578696600004d4d002a0000000800060132000200000014000000564746000300000001000300004749000300000001003200009c9d00010000000e00000000ea1c0007000007f40000000087690004000000010000006a000000d4323030393a30333a31322031333a34373a34330000059003000200000014000000ac9004000200000014000000c0929100020000000335340000929200020000000335340000ea1c0007000007b40000000000000000323030383a30333a31342031333a35393a323600323030383a30333a31342031333a35393a3236000005010300030000000100060000011a00050000000100000116011b0005000000010000011e020100040000000100000126020200040000000100000dd90000000000000048000000010000004800000001ffd8ffe000104a46494600010100000100010000ffdb004300100b0c0e0c0a100e0d0e1211101318281a181616183123251d283a333d3c3933383740485c4e404457453738506d51575f626768673e4d71797064785c656763ffdb0043011112121815182f1a1a2f634238426363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363[...]
MySQL said:
2006 - MySQL server has gone away
Please let me know how to fix the issue. The issue is while displaying images. Whether some size issue is there i dont know please help here.
Using addslashes is nowhere near the correct way to do a SQL query. It will not always work correctly with binary data. I don't know what resource you're using, but it's teaching you very bad habits.
Please DO NOT USE mysql_query in new applications. This is a legacy interface from the 1990s that is in the process of being retired because of the hazards involved in using it incorrectly, something all too easy to do. It's best to use either mysqli or PDO in new projects.
Your query should look like this:
Update whyangry.posts set Photo=? where Pid=?
You can bind to those placeholders when executing the query and avoid having encoding problems. There are many examples on how to do this correctly.

Updating Images in MySQL with PHP

I am on my way to create the feature for users to upload their profile photo to the database. I manage to upload my photo to database in binary form (BLOB) but I am having problem while trying to display it.
upload form code:
<?php //get the posted image when the submit button is clicked
$username = "MentorMenteeData";
$password = "mentormenteedata";
$host = "localhost";
$database = "mentormenteesystem";
// Make the connect to MySQL or die
// and display an error.
$link = mysql_connect($host, $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Select your database
mysql_select_db ($database);
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$student_id=$row_student['student_id'];
// Create the query and insert
// into our database.
$query = "UPDATE student SET student_img='$data' WHERE student_id ='$student_id'";
$query .= "(image) VALUES ('$data')";
$results = mysql_query($query, $link);
// Print results
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
// Close our MySQL Link
mysql_close($link);
?>
<form action="" method="post" enctype="multipart/form-data" name="changer">
<strong style="color: #FFD700;">Upload your image:</strong><br />
<input name="MAX_FILE_SIZE" value="102400" type="hidden"><br /><br />
<input namge="image" accept="image/jpeg" type="file">
<input type="submit" value="Submit">
</form>
Code to display image:
<?php
$username = "MentorMenteeData";
$password = "mentormenteedata";
$host = "localhost";
$database = "mentormenteesystem";
mysql_connect($host, $username, $password) or die("Can not connect to database: ".mysql_error());
mysql_select_db($database) or die("Can not select the database: ".mysql_error());
$id = $_REQUEST['student_id'];
if(!isset($id) || empty($id) || !is_int($id)){
die("Please select your image!");
}else{
$query = mysql_query("SELECT * FROM student WHERE student_id='".$id."'");
$row = mysql_fetch_array($query);
$content = $row['image'];
}
header('Content-type: image/jpeg');
echo $content;
?>
I could see my database table for the image column containing some bits but I just cant seems to display it. Please advise.
Your code to retrieve and display the image looks like it is correct, however I'm guessing you are never getting to the query due to this filtering line:
$id = $_REQUEST['student_id'];
if(!isset($id) || empty($id) || !is_int($id)){
die("Please select your image!");
}
is_int() tests if the type of a value is an integer, and values coming from $_GET, $_POST, $_REQUEST are always strings. , so your condition is always false. You can test it instead with ctype_digit() or is_numeric(), or intval($id) == $id. Also, empty() calls isset() implicitly, so isset() isn't needed.
// ctype_digit() method...
if (empty($id) || !ctype_digit($id)) {
die("Please select your image!");
}
// intval() method...
if (empty($id) || (intva($id) != $id)) { 
die("Please select your image!"); 
}
Without any errors, it's hard to say, but if it's not the ID problem as suggested by Michael, it might [also] be corruption of your image data on upload. Have you tried downloading the directly (eg wget that URL) and opening it locally? Is the JPEG header there?
Some general comments:
Are you sure you want to store images in the database? It's
generally preferred to store filename / URL fragments, and leave the
binary data on disk, especially if they're larger images. See
php:Store image into Mysql blob, Good or bad?
for a discussion.
Either way that upload code is asking for trouble. addslashes() is
not sufficient to fix the escaping problem, use a specific one like
mysqli::real escape-string
to safeguard against SQL Injection
attacks - this post explores some differences.
If your MySQL DB is hosted on the same box as your webserver, you
could even save effort (and increase speed) by using the MySQL LOAD_FILE function, but this isn't very scalable in the long term.
Consider moving all your login details to a separate file, out of the webroot for security.

Categories