How to update specific column using fgetcsv - php

I'm trying to update a specific column through fgetcsv. But the problem is all the data are the same. Can someone help me about this? I don't know how to make the use of grade_id here because there are no grade_id in csv only in the database. And im doing it with only just file uploading.
Here's the csv. I just only want the midterm grade to be updated. But only the value 64 is inserted.
here's the result. The output should be 75,80,64 not 64,64,64
here's my database structure
here's my code
if(isset($_POST["Import"])){
$term = $_POST['term'];
$fac_code = $_POST['fac_code'];
$sch_year = $_POST['schoolyear'];
$section = $_POST['sec'];
$semester = $_POST['semester'];
$sub = $_POST['sub'];
echo $filename=$_FILES["file"]["tmp_name"];
$heading = true;
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
if($heading) {
// unset the heading flag
$heading = false;
// skip the loop
continue;
}
//to get the last column
$last = end($emapData);
$sql1 ="SELECT * FROM grade WHERE subj_descr ='$sub' AND section = '$section'";
$result = mysqli_query($con, $sql1);
while($row = mysqli_fetch_array($result)){
$gradeid = $row['grade_id'];
$sql = "UPDATE grade SET midterm_grade = '$last' WHERE grade_id = '$grade_id'";
$result = mysqli_query( $con, $sql );
}
}
fclose($file);
//throws a message if data successfully imported to mysql database from excel file
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"homefaculty.php\"
</script>";
//close of connection
mysqli_close($con);
}
}

Your loop for updating in mysql is done just after your fetch your last value
In means in your code you do 3 loops for updating all value
$sql1 ="SELECT * FROM grade WHERE subj_descr ='$sub' AND section = '$section'";
This loop which fetch always the same result is called 3 times.
"UPDATE grade SET midterm_grade = '$last' WHERE grade_id = '$grade_id'";
In this query the grade_id comes from all the resultset
Basically you are doing this
1- get the last value of the line of CSV
2- select all records
3- update all of them with the value of 1-
4- next line
Instead of looping in all you mysql database for the SELECT, you should be able to SELECT just the record you need. I don't know if your CSV is full but do you have the grade_id in a column ? Otherwise how can you match a row of your CSV to a record in your database ?
EDIT
after discussion you said you have a unique key on section, term and subject
(You have to identify a relation between a row in CSV and a row in your database)
$last = end($emapData); //to get the last column
$section = $emapData[0]; // assuming section is the first column of CSV
$term = $emapData[1]; // assuming term is the 2nd column of CSV
$subject = $emapData[2]; // assuming subject is the 3rd column of CSV
$sql = "UPDATE grade SET midterm_grade = '$last' WHERE section = '$section' AND term = '$term' AND subject = '$subject'";
$result = mysqli_query( $con, $sql );

Related

Uploading csv files to a MySQL database without inserting row by row [duplicate]

This question already has answers here:
Import data in MySQL from a CSV file using LOAD DATA INFILE
(13 answers)
Closed 3 years ago.
I have a website where users can upload a csv file. Each file might have a different number of columns and rows and I use the following to handle the upload of a csv file and then write this data into a new table. This all works but it can be slow if the csv file is large. Writing the data row by row is slow and I wonder if there is a way of writing the whole csv file ($matrix - see below) into the newly created SQL table in one go?
//Handling the csv file and reading data into $matrix
$file = $_FILES['csv1']['tmp_name'];
$handle = fopen($file,"r");
$colsMax=0;
$matrix = array();
while (($row = fgetcsv($handle, 10000, ",")) !== FALSE) {
$matrix[] = $row;
}
$rows = count($matrix);
$cols = count($matrix[$row]);
I then create a table in the database with the correct number of columns (with field names A1, A2 etc. which are changed later):
//create importDataTable table for all the data
$sql = "CREATE TABLE $tblImportedData (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY";
for ($colloop=0; $colloop<$cols; $colloop++) {
$sql = $sql . ", A$colloop VARCHAR(80)";
}
$sql = $sql . ");";
mysqli_query($connect, $sql);
The data is then inserted into the table row by row:
for ($rowloop=0; $rowloop < $rows; $rowloop++) { //loops through each row
$dataToWrite = $matrix[$rowloop][0];
$sql = "INSERT INTO $tblImportedData SET ";
for ($colloop=0; $colloop < $cols; $colloop++) { //loops through each column
$dataToWrite = isset($matrix[$rowloop][$colloop]) ? $matrix[$rowloop][$colloop] : '';
$sql = $sql . ", A$colloop = '" . $dataToWrite . "'";
}
$sql = $sql . ";";
mysqli_query($connect, $sql);
}
As #tadman suggested in his comment, you should use the LOAD DATA INFILE functionality that come out of the box with mysql.

I want to check my database when adding new10 rows entry for 24 hours limit not to repeat. How can I achieve it through Php & MySql?

I have a database and I want to avoid repeating any data (say by phone number) for a 24 hour limit when adding 10 rows together. I have saved the time of arrival also by now function but I want to know how to achieve it?
<?php
if (($getdata = fopen($target_file, "r")) !== FALSE) {
fgetcsv($getdata);
while (($data = fgetcsv($getdata)) !== FALSE) {
$fieldCount = count($data);
for ($c = 0; $c < $fieldCount; $c++) {
$columnData[$c] = $data[$c];
}
$mobile = mysqli_real_escape_string($connect, $columnData[0]);
$value = mysqli_real_escape_string($connect, $columnData[1]);
$import_data[] = "('" . $mobile . "','" . $value . "',NOW())";
}
$import_data = implode(",", $import_data);
$query = "INSERT INTO master(name,value,whenadded) VALUES $import_data ;";
$result = mysqli_query($connect, $query);
$message .= "Data imported successfully.";
fclose($getdata);
}
?>
Although the sample code is not clear. I think the main question is to prevent adding duplicate columns within time period 24 hours.
The steps to do so is as following:
There should be a column od DATETIME to track the creation date of the record in the DB. It may have the default value CURRENT_TIMESTAMP. Let's assume is called CREATED.
Before inserting your data, make sure to check that there is no duplicate within 24 hours using the following SQL:
Please note that you can put on any column that requires being unique.
SELECT COUNT(*) AS CONT
FROM MY_TABLE
WHERE TIMESTAMPDIFF(HOUR,CREATED,NOW())<=24 AND (PHONE = ? OR EMAIL=? OR NAME=? ......)
If the query returns any number greater than 0 then you should return an error the user.
Update
As requested in the asker comment below, please check this question about removing duplicate entries keeping only one

Prevent Form from inserting data multiple times into database

Trying to insert form data into mysql database, my issues is as the user submits the form the data gets inserted twice into database. I know that I am doing something wrong with my 2nd query $query_file = "INSERT INTO upperbit_files... statment as when I remove the whole if loop if(mysqli_query($dbc, $query_info)){...} the form gets submitted once as expected.
Basically I need to insert data into 2 tables. One is for general product info and the other one is to store photos relating to that product both the table are connected via a global variable $advert_id. I am using 2 separate queries
Table1: advert_sell_category1, is for general product info
Table2: upperbit_files, is to store details of the images uploaded
But for some reason the 1st query relating to general product info is getting inserted twice into database and the irony is both the time the $advert_id is the same. Below is my code and a screenshot of the database for your understanding,
if(isset($_POST['postad'])){
$adtype = $_POST['offering_type'];
$manufacturer = mysqli_real_escape_string($dbc, $_POST['manufaturer']);
$mediafile = mysqli_real_escape_string($dbc,$_POST['mediafile']);
$GLOBALS['advrt_post_id'] = crypto_rand_secure(10, 100000);
$query_info = "INSERT INTO advert_sell_category1(advert_id,manufacturer,image_file)
VALUES('$advrt_post_id','$manufacturer','$mediafile')";
$result = mysqli_query($dbc, $query_info) or die(mysqli_error($dbc));
if(mysqli_query($dbc, $query_info)){
$last_id = mysqli_insert_id($dbc);
$query_link_id = "SELECT advert_id FROM advert_sell_category1 WHERE id = '$last_id' ";
$result_id = mysqli_query($dbc, $query_link_id);
while ($row = mysqli_fetch_assoc($result_id)) {
$link_id = $row['advert_id'];
if(!empty($mediafile)){
$media_file = explode(",", mysqli_real_escape_string($dbc,$_POST['mediafile']));
$media_file = array_filter($media_file);
$media_file_size = explode(",", mysqli_real_escape_string($dbc,$_POST['mediafilesize']));
$media_file_size = array_filter($media_file_size);
$media_file_type = explode(",", mysqli_real_escape_string($dbc,$_POST['mediafiletype']));
$media_file_type = array_filter($media_file_type);
for ($var = 0; $var < sizeof($media_file); $var++){
$query_file = "INSERT INTO upperbit_files(file,size,type,link_id) VALUES ('$media_file[$var]','$media_file_size[$var]','$media_file_type[$var]','$link_id')";
$result_file = mysqli_query($dbc, $query_file) or die(mysqli_error($dbc));
}
}
}
}
/********** Your Code ************/
$result = mysqli_query($dbc, $query_info) or die(mysqli_error($dbc));
if(mysqli_query($dbc, $query_info)){
/**********************/
See here in if statement you are calling mysqli_query() second time so same data is inserted twice. Use following code to solve your problem
/********** Suggested Code ************/
$result = mysqli_query($dbc, $query_info) or die(mysqli_error($dbc));
if(mysqli_affected_rows()>0){
/**********************/

PHP fputcsv not Outputting First Row From SQL Query (Outputs all Other Rows After the First Row)

I am using the very simple code below to export a CSV of all of my MySQL table's data, "members". However, there is a total of 560 rows in the MySQL table, but the CSV only shows 559 of the MySQL table's rows (it does not display the very first database's table's row). Does anyone know why this is, or perhaps what I can change in my code in order to fix this issue?
// BEGIN EXPORT ALL FROM EDITOR
if(isset($_POST['export_csv'])) {
$today_date = date('Y-m-d_h-i-s-a', time());
$FileName = "download/report_mailing_list_export_".$today_date.".csv";
$file = fopen($FileName,"w");
$sql = mysqli_query($dbc, "SELECT * FROM member WHERE memberid != 1 AND deleted=0 AND website = 0 ORDER BY last_name, first_name DESC");
$row = mysqli_fetch_assoc($sql);
// Save headings alon
$HeadingsArray=array();
foreach($row as $name => $value){
$HeadingsArray[]=$name;
}
fputcsv($file,$HeadingsArray);
// Save all records without headings
while($row = mysqli_fetch_assoc($sql)){
$valuesArray=array();
foreach($row as $name => $value){
$valuesArray[]=$value;
}
fputcsv($file,$valuesArray);
}
fclose($file);
header("Location: $FileName");
}
// END EXPORT
You calling mysqli_fetch_assoc($sql); before while loop, which iterates over first row. You may change it to something like this:
// BEGIN EXPORT ALL FROM EDITOR
if(isset($_POST['export_csv'])) {
$today_date = date('Y-m-d_h-i-s-a', time());
$FileName = "download/report_mailing_list_export_".$today_date.".csv";
$file = fopen($FileName,"w");
$sql = mysqli_query($dbc, "SELECT * FROM member WHERE memberid != 1 AND deleted=0 AND website = 0 ORDER BY last_name, first_name DESC");
$row = mysqli_fetch_assoc($sql);
// Save headings alon
$HeadingsArray=array();
foreach($row as $name => $value){
$HeadingsArray[]=$name;
}
fputcsv($file,$HeadingsArray);
// Save all records without headings
do {
$valuesArray=array();
foreach($row as $name => $value){
$valuesArray[]=$value;
}
fputcsv($file,$valuesArray);
} while($row = mysqli_fetch_assoc($sql));
fclose($file);
header("Location: $FileName");
}
// END EXPORT
In this case, you will reuse $row from first iteration.

How to Unlink a File from Website's Folder when MSSQL Table Row is Deleted Using PHP

I am trying to make the link <a href='{$_SERVER['PHP_SELF']}?del=true&orderid={$row['orderid']}' style='color:black;' onclick='return show_confirm();'>Delete</a>
delete the specific row from the MSSQL table using the while function. Currently, the bottom code works fine and deletes the specific row from the table, but I would now like it to unlink a file from the sharedstorage folder. The file that gets unlinked has it's filename stored in the name column for that table row. Each table row has a name column that contains a unique file's name from the file that is located in the sharedstorage folder.
My problem in simple terms is when a table row gets deleted, the file for that row in my website's sharedstorage folder remains and does not get deleted with the row.
Here is the code for when the delete link is hit for that specific row:
// delete from table
if ($_GET['del'] == 'true') {
// cast id as int for security
$id = (int) $_GET['orderid'];
// delete row from table
$sql = "DELETE FROM shareddrive WHERE orderid = '$id'";
$result = mssql_query($sql, $conn) or die(mssql_get_last_message());
// select the info, ordering by usort
$sql = "SELECT orderid, name, type FROM shareddrive ORDER BY orderid";
$result = mssql_query($sql, $conn) or die(mssql_get_last_message());
// initialize a counter for rewriting usort
$job_pos_sortt = 1;
// while there is info to be fetched...
while ($r = mssql_fetch_assoc($result)) {
$job_poss = $r['orderid'];
// update the usort number to the one in the next number
$sql = "update shareddrive SET orderid = '$job_pos_sortt' WHERE name = '$job_poss'";
$update = mssql_query($sql, $conn) or die(mssql_get_last_message());
// inc to next avail number
$job_pos_sortt++;
} // end while // end if del
}
All help is greatly appreciated.
// delete from table
if ($_GET['del'] == 'true') {
// cast id as int for security
$id = (int) $_GET['orderid'];
// delete row from table
$file = mssql_fetch_array(mssql_query("select name from shareddrive where orderid = $id"));
unlink($file[0]);
$sql = "DELETE FROM shareddrive WHERE orderid = '$id'";
$result = mssql_query($sql, $conn) or die(mssql_get_last_message());
// select the info, ordering by usort
$sql = "SELECT orderid, name, type FROM shareddrive ORDER BY orderid";
$result = mssql_query($sql, $conn) or die(mssql_get_last_message());
// initialize a counter for rewriting usort
$job_pos_sortt = 1;
// while there is info to be fetched...
while ($r = mssql_fetch_assoc($result)) {
$job_poss = $r['orderid'];
// update the usort number to the one in the next number
$sql = "update shareddrive SET orderid = '$job_pos_sortt' WHERE name = '$job_poss'";
$update = mssql_query($sql, $conn) or die(mssql_get_last_message());
// inc to next avail number
$job_pos_sortt++;
} // end while // end if del
}

Categories