import csv in mysql db using ajax and php - php

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.

Related

How can i apply the datatable filters to my php code?

I am getting some data and displaying on the table which i have created in my php code however i want to apply the data table filters but i cannot seem to find a solution. I know in html i can assign an id to the table and then call it from a js script using the following code var table = $('#myTable').DataTable({"dom":"ftip"}); however this doesn't seem to work in my code. Perhaps because i am wrapping the html code in php?
Thanks
<script>
$(document).ready(function(){
var table = $('#myTable').DataTable({"dom":"ftip"});
});
</script>
<?php
$conn = mysqli_connect('localhost', 'root', '""', 'calendar');
extract($_POST);
if(isset($_POST['readrecords'])){
$data = '<table class="table table-bordered table-striped" id="myTable">
<tr class="bg-dark text-white">
<th>No.</th>
<th>Title</th>
<th>Driver</th>
<th>Date</th>
</tr>';
$displayquery = "SELECT id,title, driver, start FROM `events` ";
$result = mysqli_query($conn,$displayquery);
if(mysqli_num_rows($result) > 0){
$number = 1;
while ($row = mysqli_fetch_array($result)) {
$data .= '<tr>
<td>'.$number.'</td>
<td>'.$row['title'].'</td>
<td>'.$row['driver'].'</td>
<td>'.$row['start'].'</td>
<td>
<button onclick="GetUserDetails('.$row['id'].')" class="btn btn-success">Edit</button>
</td>
<td>
<button onclick="DeleteUser('.$row['id'].')" class="btn btn-danger">Delete</button>
</td>
</tr>';
$number++;
}
}
$data .= '</table>';
echo $data;
}
?>
function readRecords(){
var readrecords = "readrecords";
$.ajax({
url:"backend.php",
type:"POST",
data:{readrecords:readrecords},
success:function(data,status){
$('#records_content').html(data);
},
});
}

Deleting record from database with button in PHP

I have to delete a record from database using a button but my delete query does not work. Records are entered in database successfully with insertion query. I followed exact tutorial for php code available on YouTube "How to delete records from database with PHP & MySQL" by "kanpurwebD". The code in tutorial works fine but my code still does not delete record. (I have 2 records entered in database).
My code is as follows:
<div class="container">
<div class="row">
<form action='add_record.php' method='get'><button type='submit' name='id' value='submit' class='btn btn-default'>ADD RECORD</button><br />
</form>
<table class="table table-hover table-responsive">
<thead>
<tr>
<th>Topic #</th>
<th>Name</th>
<th>Admin ID</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
echo '<br />';
$query = "SELECT * FROM tb_topic";
$result = $con->query($query);
if(isset($_POST['submitDeleteBtn'])){
$key = $_POST['keyToDelete'];
$check = "Select * from tb_topic where topic_id = '$key'";
if(mysqli_num_rows($con, $check)>0){
$query_delete = mysqli_query($con,"Delete from tb_topic where topic_id = '$key'");
echo 'record deleted';
}
}
while($query_row = mysqli_fetch_array($result)) {?>
<tr>
<td><?php echo $query_row['topic_id'];?></td>
<td><?php echo $query_row['topic_name'];?></td>
<td><?php echo $query_row['aid'];?></td>
<td><input type = 'checkbox' name = 'keyToDelete' value = "<?php echo $query_row['topic_id'];?>" required></td>
<td><input type="submit" name="submitDeleteBtn" class="btn btn-danger"></td>
</tr>
<?php }
?>
</html>
I got it resolved by using following statement:
if(isset($_GET['delete'])) {
$page = filter_input(INPUT_GET, 'delete', FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
$sql = "DELETE FROM tb_topic WHERE topic_id = $page";
}
$_GET() was not taking id as int so I tried typecasting it and it worked for me.

how to search date field using php - mysqli

I'm having trouble searching the date field of mysql database.. I have a html form..that allows the user to choose 3 different ways to search the database.. field 1 is student_id, field 2 is lastname, field 3 is date. Well when i run the program and choose student id, I get the proper result back, when i do the same using last name I get the proper result back, but when i use date..I do not get any return. I happen to know what the result should be because i see it in the database..and besides that its the same data record as the student id, and last name. I think it might have something to do with format, but I can't figure it out..
I do not know aJax so please don't suggest ajax code right now.
here is the html code.
[code]
-- start javascript -->
<script type="text/javascript">
/*<![CDATA[ */
function check(){
if(document.lastname.last.value == "" || document.lastname.last.value == null)
{
alert("no last name entered");
return false;
}
}
function checkdate() {
var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/ ;
if(!(date_regex.test(testDate)))
{
return false;
}
}
function fieldSwap(image){
var sb = document.getElementById('sb');
if(sb.value == ""){
sb.style.background = "url(images/"+image+") no-repeat";
}
}
function buttonSwap(image){
var sb = document.getElementById('sb');
sb.src = "images/"+image;
}
function validate(){
var x = document.information.search.value;
if (x.length<10 || x.length>10){
alert("student id is incorrect");
return false;
}
}
/*]]> */
</script>
<!-- end javascript -->
</head>
<body>
<div id="form_wrap"><!-- start form wrap -->
<div id="form_header">
</div>
<div id="form_body">
<p>Search for a certification request (Enter one of the following):</p>
<form action="search.php" method="POST" name="information" id="information" onsubmit="return(validate()or return(checkdate())">
<div class="field">
<select name="type">
<option value="student_id">Student ID</option>
<option value="last_name">Last name</option>
<option value="examDate">Exam date</option>
</select>
<input name="typeValue" value="" />
<input type="submit" value="Search" />
</form>
</div>
</div>
</div><!-- end form wrap -->
</body>
</html>
<form action = "" method = "POST">
<div class="field">
<label for = "first_name"> first_name</label>
<input type = "text" name = "first_name" id = "first_name">
</div>
<div class = "field">
<label for = "last_name"> last_name </label>
<input type ="text" name = "last_name" id = "last_name">
</div>
<div class = "field">
<label for = "bio"> bio </label>
<textarea name = "bio" id = "bio"></textarea>
</div>
<input type = "submit" value = "Insert">
</form>
[/code]
Here is the PHP code
[code]
$records = array();
$typeValue = $_REQUEST['typeValue'];
//If they did not enter a search term we give them an error
if ($typeValue == "")
{
echo "<p>You forgot to enter a search term!!!";
exit;
}
// We perform a bit of filtering
//$typevalue = strtoupper($search);
$typeValue = strip_tags($typeValue);
$typeValue = trim ($typeValue);
$value = $_POST['typeValue'];
if($_POST['type'] == "student_id")
{
//Query with $value on student_id
if($result = $db->query("SELECT * FROM records WHERE student_id LIKE '$typeValue'" )){
if($result->num_rows){
while($row = $result->fetch_object()){
$records[] = $row;
}
$result->free();
}
}
}
elseif($_POST['type'] == "last_name")
{
//Query with $value on last_name
if($result = $db->query("SELECT * FROM records WHERE last_name LIKE '$typeValue'" )){
if($result->num_rows){
while($row = $result->fetch_object()){
$records[] = $row;
}
$result->free();
}
}
}
elseif($_POST['type'] == "examDate")
{
//Query with $value on date
if($result = $db->query("SELECT * FROM records WHERE examDate LIKE '$typeValue'" )){
if($result->num_rows){
while($row = $result->fetch_object()){
$records[] = $row;
}
$result->free();
}
}
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
//$anymatches=$result;
//if ($anymatches == 0 )
//{
//echo "Sorry, but we can not find an entry to match your query...<br><br>";
//}
//And we remind them what they searched for
//echo "<b>Results For:</b> " .$typeValue;
//}
?>
<!DOCTYPE html>
<html>
<style type="text/css">
th{text-align: left;}
table, th, td{ border: 1px solid black;}
</style>
<head>
<title>Search Result</title>
</head>
<body>
<h3> Results for <?php echo $typeValue ?> </h3>
<?php
if(!count($records)) {
echo 'No records';
} else {
?>
<table style="width:100%">>
<th>
<tr>
<th>student_id</th>
<th>First name</th>
<th>Last name</th>
<th>email</th>
<th>Major</th>
<th>Exam Name</th>
<th>Taken class</th>
<th>Prepare</th>
<th>MeasureUp Key</th>
<th>Exam Date</th>
<th>Request Made On</th>
</tr>
</thead>
<tbody>
<?php
foreach($records as $r){
?>
<tr>
<td><?php echo $r->student_id; ?></td>
<td><?php echo $r->first_name; ?></td>
<td><?php echo $r->last_name; ?></td>
<td><?php echo $r->email; ?></td>
<td><?php echo $r->major; ?></td>
<td><?php echo $r->examName?></td>
<td><?php echo $r->taken_class; ?></td>
<td><?php echo $r->prepare; ?></td>
<td><?php echo $r->measureUpKey; ?></td>
<td><?php echo $r->examDate; ?></td>
<td><?php echo $r->request_made; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
?>
</html>
<html>
<head></head>
<body>
<br/>
Return to Search
</body>
</html>
[/code]
I Believe you are using like to get the Exam Dates for that session or month so you can use this
Using DATE_FORMAT function
SELECT * FROM records WHERE DATE_FORMAT(examDate, '%Y %m') = DATE_FORMAT('$typeValue', '%Y %m') ORDER BY examDate
or may be you are looking for a specific date than
SELECT * FROM records WHERE examDate = '$typeValue'

Adding a loader to load a table with data jQuery or ajax

Here is the description of my issue:
I have a db connection here:
$host = 'some host credentials';
$dbh = 'My database';
Here is my statement:
$qry = "SELECT some_data FROM some_table LIMIT 1000";
$result = some code here;
Here is my while loop:
echo '<table class="table table-striped table-hover table-bordered" id="example">
<thead>
<tr class="test">
<th style="border: 1px solid #333;">PRODUCTPRICE</th>
<th>PRODUCTNAME</th>
<th>PRODUCTCODE</th>
<th>PRODUCTSALE</th>
<th>PRODUCTPRICE</th>
</tr>
</thead>
<tbody>';
while ($row = mysql_fetch_assoc($result)){
$PRODUCTID = intval($row["PRODUCTID"]);
$PRODUCTNAME = $row["PRODUCTNAME_1"];
$PRODUCTCODE = $row["PRODUCTCODE"];
$PRODUCTSALE = $row["PRODUCTSALE_"];
$PRODUCTPRICE = $row["PRODUCTPRICE"];
echo '<tr class="odd gradeX">
<td>'.$PRODUCTID.'</td>
<td>'.$PRODUCTNAME.'</td>
<td>'.$PRODUCTCODE.'</td>
<td class="center">'.$PRODUCTSALE.'</td>
<td class="center">'.$PRODUCTPRICE.'</td>
</tr>';
}
echo '</tbody>
</table></div>
</div>
</body>
</html>';
I want to make a loader before this content table display because there are more than 50,000 products. Something kind of processing or a circle showing that a content is loading, just a simple one, maybe jQuery or ajax. I have tried many tutorials till now but no success.
here is a scheme for that :
<div id="content"></div>
$.ajax({
url : 'the-above-script.php',
beforeSend : function() {
$("#content").html('<img src="ajax-icon-from-www.ajaxload.info">');
},
success : function(html) {
$("#content").html(html);
}
});

JQuery Barcode Only Generates One Barcode From Query Results

I have finally got a barcode to appear in my table that is generated from a Query. But now I am having an issue getting a code on each of the results from $row[1]. I tried to use PHP-BARCODE but it require too much memory to create all the barcodes. Jquery looks like it uses less memory to create them. Hence why I chose that method.
Any help on this would be AWESOME
My script is mainly PHP with an odd splash from JQUERY.
JQUERY for screen refresh and Barcode Generation. With soon more once i get past this hurdle.
<?php
include('inc/database.php');
// MSSQL Query
$sql = "SELECT warehouse, pick_order_number, order_status, pick_order_type, customer_order_number
FROM pick_order_header
WHERE warehouse = 'XDGM'
AND order_status <> 'Complete'
AND order_status <> 'Closed'
AND pick_order_type <> 'Backorder'
AND customer_order_number LIKE '%1 hr%'";
?>
<!DOCTYPE HTML>
<link rel="stylesheet" type="text/css" href="css/master.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="js/jquery-barcode.js"></script>
<script>
setTimeout(function(){
window.location.reload(1);
}, 5000);
</script>
<html>
<title>Current Orders</title>
<body>
<table>
<?php
// SQLSRV Query
$results = sqlsrv_query( $conn, $sql );
if( $results === false) {
die( print_r( sqlsrv_errors(), true) );
}
echo "
<table border=1>
<tr>
<th>Order Number</th>
<th>Order Status</th>
<th>Order Type</th>
<th>Customer Order</th>
<th>Barcode</th>
</tr>";
while ($row = sqlsrv_fetch_array($results))
{
$odrnum = $row[1];
$odrstatus = $row[2];
$odrtype = $row[3];
$custorder = $row[4];
$barcode = $row[1];
echo "
<tr>
<td>$odrnum</td>
<td>$odrstatus</td>
<td>$odrtype</td>
<td>$custorder</td>
<td>
<div id="bcTarget_'.$odrnum.'"><input type="button" id="bc" name="bc" value="Click Here" /></div>
</td>
<script>
$("#bc").click(function(){$("#bcTarget_'.$odrnum.'").barcode("'.$row[1].'", "code39",{barWidth:2.5, barHeight:30, showHRI: true, bgColor: "#DEF3CA"});});</script>
</tr>';
}
echo "</table>";
?>
</table>
</body>
</html>
I am a complete noob at this, so if you do find a solution could you explain it to me as well so I can learn?
Thanks a bunch
The problem is that you have more then one of the same ids bcTarget and jquery will select the first found within the DOM.
Try to make your ids for the selector unique:
echo '
<tr>
<td>'.$odrnum.'</td>
<td>'.$odrstatus.'</td>
<td>'.$odrtype.'</td>
<td>'.$custorder.'</td>
<td>
<div id="bcTarget_'.$odrnum.'"></div>
</td>
<script>
$(function(){$("#bcTarget_'.$odrnum.'").barcode("'.$row[1].'", "code39",{barWidth:2, barHeight:30});});</script>
</tr>';
u can use this code
<div class="bcTarget" rel="4874214545"></div>
//rel= 'barcode digits'
javascript
$(document).ready(function() {
$(".bcTarget").each(function() {
var bcdigits = $(this).attr('rel');
$(this).barcode(bcdigits, "code39",{barWidth:2, barHeight:30});
});
});

Categories