i was working on a mini project that imports csv file to the database through ajax and it's working fine.
here are my files
<?php
// creating database connection , executing queries and storing results
$connect = mysqli_connect("localhost","root", "", "dbname" );
$query = "SELECT * FROM csv ORDER BY id desc ";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Marks Statistics</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
</head>
<body>
<br/><br/>
<div class="container", style="width: 1000px;">
<h3 align="center">CSV DATABASE</h3><br/>
<!-- creating upload form -->
<form id="upload_csv" method="post" enctype="multipart/form-data">
<div class="col-md-3">
<label>Upload More Files</label>
</div>
<div class="col-md-4">
<input type="file" name="marks_file" />
</div>
<div class="col-md-5" >
<input type="submit" name="upload" id="upload" value="upload" class="btn btn-info">
</div>
<div style= "clear:both"></div>
</form>
<br/><br/><br/>
<!-- HTML table to display contents of the csv file -->
<div class="table-responsive" id="marks_table">
<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>
<?php
while ($row = mysqli_fetch_array($result))
{
?>
<!-- append row data into table -->
<tr>
<td><?php echo $row["name"]; ?> </td>
<td><?php echo $row["Physics"]; ?> </td>
<td><?php echo $row["Maths"]; ?> </td>
<td><?php echo $row["Chemistry"]; ?> </td>
<td><?php echo $row["Biology"]; ?> </td>
<td><?php echo $row["SST"]; ?> </td>
<?php
}
?>
</table>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#upload_csv').on("submit", function(e){
e.preventDefault(); //form will not submitted
$.ajax({
url:"export.php",
method:"POST",
data:new FormData(this),
contentType:false, // The content type used when sending data to the server.
cache:false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data){
if(data=='errorx')
{
alert("Invalid File");
}
else if(data == "errory")
{
alert("Please Select File");
}
else
{
$('#marks_table').html(data);
}
}
})
});
});
</script>
And
//export.php
<?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've tried multiple escape functions but none works, and it gets difficult to remove the fields line also.
For this:
csv files inserts null values in the tables
,,,,,,,,
,,,,,,,,
Check empty Like this (after filtering the array):
while($row = fgetcsv($file_data)) //['','','','','']
{
if(empty(array_filter($row))) continue; //[] after array_filter
///...
}
For the Fields one you do essentially the same thing, except in the condition look for something like
while($row = fgetcsv($file_data)) //['','','','','']
{
if(empty(array_filter($row)) || $row[3]=='Fields') continue; //[] after array_filter
///...
}
You can just look for empty($row[3]) but that is only telling you that column is empty, not the whole row.
UPDATE
I figured it out , it was a silly indexing error in my code considering the type of csv files i have.
If you want Associate arrays, with the keys from the header it can be very easy to do: If the headers are correct and the rows have the correct number of columns, and the names of the headers are unique:
$headers = fgetcsv($file_data); //['header1','header2']
while($data = fgetcsv($file_data)) //['data1','data2']
{
$row = array_combine($headers,$data); //['header1'=>'data1','header2'=>'data2']
Array combine Must have the same number of keys as values to work (both arrays must be the same length). In a typical CSV this "should" always be the case, in my experience it's not. However, when it's not that row is suspect to having it's data shifted to the wrong columns (under normal circumstances, without array combine). So you have to ask yourself if your ok with that.
Anyway hope it helps.
I figured it out , it was a silly indexing error in my code considering the type of csv files i have.
i added
if ($row[3]=='Fields' || $row[3]=='') continue;
and it worked.
Trying to solve my problem with deleting rows from generated table.I have a page called report.php that shows all the rows from database and there is option 'delete row'. My problem is when I click on delete nothing happens and it should go on delete.php file. For now couldnt solve this by myself, maybe you see something that I dont. I dont get any errors so I am a little bit confused. Thank you.
report.php
<!DOCTYPE>
<html>
<head>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<head>
<body>
<?php
require_once '../include/functions.php';
require_once '../include/db.php';
$htmltable = "";
$htmltable .= "<table>
<tr>
<th>ID</th>
<th>Ime</th>
<th>Ime slavljenika</th>
<th>Datum</th>
<th>Poruka</th>
<th>Vreme prijave</th>
<th>Obrisi</th>
</tr>";
$prep = $db->prepare("SELECT * from prijavljeni");
$prep->execute();
$prijavljeni = $prep->fetchAll();
foreach($prijavljeni as $prijavljen => $row) {
$htmltable.= '<tr>
<td>'.$row['prijavljeni_id'].'</td>
<td>'.$row['ime'].' </td>
<td>'.$row['ime_slavljenika'].' </td>
<td>'.$row['datum'] .'</td>
<td>'.$row['poruka'].' </td>
<td>'.$row['vreme'].'</td>
<td><a href="delete.php?prijavljeni_id=<?php echo $prijavljeni["prijavljeni_id"]; ?>Delete</a></td>
</tr>';
}
$htmltable.='</table>';
echo $htmltable;
?>
<div>
<button onclick="return email()">Posalji</button>
<div id="emailporuka">
</div><br><br>
</div>
<p align="center">Logout</p>
<script>
function email(){
$.ajax({
type:"post",
url: "email.php",
success: function(data){
//window.alert(data);
document.getElementById("emailporuka").innerHTML = data;
},
error: function (req, status, err) {
console.log('Something went wrong', status, err);
}
})
return false;
}
</script>
</body>
</html>
delete.php
<?php
include('../include/db.php');
$prijavljeni_id=$_GET['prijavljeni_id'];
$result = $db->prepare("DELETE FROM prijavljeni WHERE prijavljeni_id= :prijavljeni_id");
$result->bindParam(':prijavljeni_id', $prijavljeni_id);
$result->execute();
header("location: izvestaj.php");
?>
You just need to change this in your $htmltable. (there was an error in appending strings in last block).
$htmltable.= '<tr>
<td>'.$row['prijavljeni_id'].'</td>
<td>'.$row['ime'].' </td>
<td>'.$row['ime_slavljenika'].' </td>
<td>'.$row['datum'] .'</td>
<td>'.$row['poruka'].' </td>
<td>'.$row['vreme'].'</td>
<td>Delete</td>
</tr>';
Update your code
$result->bindParam(':prijavljeni_id', $prijavljeni_id);
To
$result->bindParam('prijavljeni_id', $prijavljeni_id);
Remember one thing always avoid : before on bindParam method but we using : on prepareQuery to indicate replaceable value.
I am fetching data from database in a table.Now i want to edit particular field in a row of the table and save that value into MySQL.
This is my complete code for displaying data in table and editing. Here i want to edit the status. It is editable but after editing how to get the value from the table and update that value to MySQL.
<?php
include "config.php";
$sql = "select * from d_jobs where Status ='drafted' ";
$result = mysqli_query($conn,$sql);
$count = mysqli_num_rows($result);
//echo $count;
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script>
$("document").ready(function(){
$('#sdata').click(function(){
var myTxt = $(('.status')+[i]).html();
console.log(myTxt);
var id = $(('.status')+[i]).attr('id');
console.log(id);
}
/* $.ajax({
type: 'post',
url: 'job_field_edit.php',
data: 'varname=' +myTxt
}); */
});
});
</script>
</head>
<body>
<table border="2" align="center">
<thead>
<tr>
<th>Job Name</th>
<th>Builder</th>
<th>Job Type</th>
<th>Status</th>
<th>Effective Date Start</th>
<th>Estimated completion date</th>
<th>Job Gal Glag</th>
<th>Take List Flag</th>
<th>Planner</th>
<th>Project Manager</th>
<th>Hand Over</th>
<th>Other Comments</th>
</tr>
</thead>
<tbody>
<?php
if( $count ==0 ){
echo '<tr><td colspan="4">No Rows Returned</td></tr>';
}else{
while( $row = mysqli_fetch_array($result)){
echo "<tr><td>{$row['JOB_NAME']}</td>
<td>{$row['BUILDER']}</td>
<td>{$row['JOB_TYPE']}</td>
<td contenteditable='true' id='{$row['JOB_ID']}' class='status[{$row['JOB_ID']}]'>{$row['status']}</td>
<td>{$row['EFFECTIVE_START_DATE']}</td>
<td>{$row['ESTIMATED_COMPLETION_DATE']}</td>
<td>{$row['JOB_GAL_FLAG']}</td>
<td>{$row['JOB_TAKE_LIST_FLAG']}</td>
<td>{$row['Planner']}</td>
<td>{$row['Project_Manager']}</td>
<td>{$row['Handover']}</td>
<td>{$row['Comments']}</td>
<td><input name='need_delete[{$row['JOB_ID']}]' type='checkbox' id='checkbox[{$row['JOB_ID']}]' value='{$row['JOB_ID']}'></td>
</tr>\n";
}
}
?>
</tbody>
</table>
<input id="sdata" type="button" value="Send Data" />
</body>
</html>
<?php
mysqli_close($conn);
?>
There's a number of ways to approach this. One is to dispense with the manual Send Data button and allow javascript to respond automatically to users' contenteditable edits.
Unfortunately, contenteditable elements don't fire a change event but they do fire a blur event, from which a change event can be triggered.
First, build your contenteditable elements like this :
<td contenteditable=\"true\" class=\"status\" data-job-id=\"{$row['JOB_ID']}\">{$row['status']}</td>
Then, for each contenteditable element, attach a blur handler, and initialize a data-value attribute equal to innerText.
$('[contenteditable]').on('blur', function(e) {
var self = $(this);
if(self.text() !== self.data('value')) {
self.trigger('change');
}
self.data('value', self.text());
}).each(function() {
$(this).data('value', $(this).text()); // equivaluent to data-value="{$row['status']}".
});
Thus you can have contenteditable elements that mimic, at least in part, HTML input elements.
So now you can attach a change handler as you would for a standard HTML input element.
$(".status").on('change', function(e) {
var job_id = $(this).data('jobId');
var old value = $(this).data('value');
var current value = $(this).text(); // in this regard, <input> is not mimicked. For a genuine <input> we would write `$(this).val()`.
// here, perform ajax to keep server-side up to date.
});
DEMO
Note: This approach is slightly over-the-top when [contenteditable] and .status are virtual synonyms for each other. However, in the general case where there might be several different classes of contenteditable element, then you would likely avoid much repetition of code.