split Import CSV to mysql database restricted - php

I have a php script that ask the user to upload a csv, then it display the result before importing and ask the user to map the fields corresponding to the database tables. It work fine.
My problem is that it seems that the server restrict the number of post or insert that can be made. So I can insert like 75 lines. But I have something like 600 lines. How could I split those like maybe in different files or maybe INFILE function.
I'm a little bit loss on that one. Because also, the user can select wich record he wants to be inserted with checkboxes.
<?php
setlocale(LC_ALL,"en_US.UTF-8");
ob_start();
if(!isset($_SESSION))
{
session_start();
}
//variables
$upload_file='';
$err='';
$msg='';
include "config.php";
if(isset($_POST['frm_type'])) // Insert Records
{
if(isset($_POST['frm_type']) && $_POST['frm_type']=='custom')
{
if(count($_POST["chk"])>0)
{
$count_cols=$_POST["h_cols"];
foreach($_POST["chk"] as $index)
{
$query="";
$dyn_query="";
$select_where="";
$date_reg=date('Y-m-d');
//STATIC COLUMN
$query = "cat_id='".$_POST["cat_id".$index]."'";
$query .= ",date_reg='".$date_reg."'";
$query .= ",user_id='".$_SESSION['user_id']."'";
$query .= ",type_client='".$_SESSION['cltype']."'";
$query .= ",birthday_switch='1',";
//DYNAMIC COLUMN
for($s=0; $s<$count_cols;$s++)
{
if(isset($_POST["colum_".$s]) && $_POST["colum_".$s]!='')
{
$value=Add_Slashes($_POST["row_".$s."_".$index]);
$dyn_query[]="".$_POST["colum_".$s]."='".$value."'";
}
if($_POST["colum_".$s]=="full_name")
{
$value=trim($_POST["row_".$s."_".$index]);
if($value!="")
{
$allow=1;
}
else
{
$allow=0;
}
}
}
if($dyn_query)
{
if($allow==1)
{
$query .=implode(',',$dyn_query);
$select_where[]="cat_id='".$_POST["cat_id".$index]."'";
$select_where[]="user_id='".$_SESSION['user_id']."'";
$select_where[]="type_client='".$_SESSION['cltype']."'";
for($t=0; $t<$count_cols;$t++)
{
if(isset($_POST["colum_".$t]) && $_POST["colum_".$t]!='')
{
$value=Add_Slashes($_POST["row_".$t."_".$index]);
$select_where[]="".$_POST["colum_".$t]."='".$value."'";
}
}
$select_where_query=implode(' AND ', $select_where);
$re = mysql_query("Select cat_id From clients Where $select_where_query");
if(mysql_num_rows($re)==0)
{
mysql_query("Insert Into clients Set $query");
$msg = "<span class='error' style=\"color:green;\"><b>Data Successfully Imported Into The Database</b></span>";
}
else
{
$msg = "<span class='error' style=\"color:red;\"><b>Data Already Existed in Database</b></span>";
}
}
}
else
{
$msg = "<span class='error' style=\"color:red;\"><b>Please select fields!</b></span>";
}
}
if(file_exists($_SESSION["FILENAME"]))
unlink($_SESSION["FILENAME"]);
}
}
}
if(isset($_POST['submt']))
{
if($_FILES['filename']["name"]=="")
$err = "<span class='error'>".IMPORT_PLEASE."</span>";
elseif(substr(strrev($_FILES['filename']["name"]),0,3)!="vsc")
$err = "<span class='error'>".IMPORT_INVALID."</span>";
else
{
$_SESSION['cltype']=$_POST['cltype'];
set_time_limit(0);
if(file_exists($Upload_Path.$_FILES['filename']["name"]))
$filename = GetRandomString(6).$_FILES['filename']["name"];
else
$filename = $_FILES['filename']["name"];
if(move_uploaded_file($_FILES['filename']["tmp_name"],$Upload_Path.$filename))
{
$upload_file = $Upload_Path.$filename;
$_SESSION["FILENAME"] = $upload_file;
}
else
$err = "<span class='error'>".IMPORT_FAIL."</span>";
set_time_limit(30);
}
}
?>
<script>
function Check_All2(obj,arr)
{
if(obj.checked)
{
var i=document.cfrm.elements.length;
var j;
for(j=0;j<i;j++)
{
if(document.cfrm.elements[j].name==arr)
document.cfrm.elements[j].checked=true;
}
}
else
{
var k=document.cfrm.elements.length;
var l;
for(l=0;l<k;l++)
{
if(document.cfrm.elements[l].name==arr)
document.cfrm.elements[l].checked=false;
}
}
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<script>
jQuery(document).ready(function(){
jQuery('#cfrm').submit(function(event) {
colums = jQuery('select.colum');
var arr = new Array();
var h_status=false;
colums.each(function()
{
var el=jQuery(this).val();
if(el!='')
{
h_status=true;
if(jQuery.inArray(el,arr)>-1)
{
event.preventDefault();
jQuery(this).css("border","2px solid red");
alert("Duplicated Fields!");
jQuery(this).focus();
return false;
}
else
{
arr.push(el);
jQuery(this).css("border","");
}
}
});
chks = jQuery('.chk');
chks.each(function()
{
if (jQuery(this).is(':checked'))
{
h_cols=jQuery('#h_cols').val();
var mand=1;
for(var k=0; k<=h_cols; k++)
{
colum_id='#colum_'+k;
colum_value=jQuery(colum_id).val();
flel_object=jQuery('#row_'+k+'_'+jQuery(this).val());
flel_value=jQuery('#row_'+k+'_'+jQuery(this).val()).val();
if(colum_value=='full_name')
{
if(flel_value=='')
{
event.preventDefault();
alert('Enter Full Name');
flel_object.focus();
return false;
}
}
else if(colum_value=='aaa')
{
if(flel_value=='')
{
event.preventDefault();
alert('Enter Email');
flel_object.focus();
return false;
}
}
}
}
});
if(!h_status)
{
event.preventDefault();
alert('Select Any Field To Insert!');
return false;
}
});
});
</script>
<script type="text/javascript" src="ajaxsublistgenerator.js"></script>
<table class="sub" height="20px" width="100%" border="0" cellpadding="0" cellspacing="0" align="center"></table>
<table width="99%" border="0" cellpadding="0" cellspacing="0" align="center">
<tr>
<td>
<fieldset>
<?
if($upload_file=="")
{
?>
<legend style="font-size:12px; font-weight:bold"><?=IMPORT_CSV;?></legend>
<form name="frm" action="" method="post" enctype="multipart/form-data">
<table width="45%" border="0" cellpadding="4" cellspacing="4" align="center">
<?
if($err!="" || $msg!="")
{
?>
<tr><td colspan="2"><?=($err!="") ? $err : $msg?></td></tr>
<?
}
?>
<tr>
<td width="30%" align="left" valign="middle"><b><?=IMPORT_FILE;?></b></td>
<td width="70%" align="left" valign="middle">
<input name="filename" id="filename" type="file" size="25" />
</td>
</tr>
<tr>
<td width="30%" align="left" valign="middle"><b><?=IMPORT_SECTION;?></b></td>
<td width="70%" align="left" valign="middle">
<select name="cltype" id="cltype">
<option value="Client">Clients</option>
<option value="prospect">Leads</option>
<option value="Contacts">Contacts</option>
</select>
</td>
</tr>
<tr>
<td> </td>
<td align="left" valign="middle">
<input name="submt" type="submit" value="<?=IMPORT_UPLOAD;?>">
</td>
</tr>
</table>
</form>
<script>document.getElementById("filename").focus();</script>
<?
}
else
{
?>
<legend style="font-size:12px; font-weight:bold"><?=IMPORT_CONTENT;?></legend>
<form name="cfrm" id="cfrm" action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="frm_type" id="frm_type" value="custom">
<div style="overflow:auto;width:100%;">
<table border="0" cellspacing="4" cellpadding="4" align="center" width="100%">
<tr>
<td width="5%" align="center">
<input onClick="javascript:Check_All2(this,'chk[]')" type="checkbox" checked="checked">
</td>
<td width="10%" align="center"><b><?=IMPORT_CAT;?></b></td>
<?php
$fd_header = fopen ($upload_file, "r");
$buffer_header = fgetcsv($fd_header, 100000, ',');
//print_r(count($buffer_header));
for($r=0; $r<count($buffer_header);$r++)
{
?>
<td width="10%" align="center">
<select class="colum" name="colum_<?php echo $r;?>" id="colum_<?php echo $r;?>">
<option value="">--Select Field--</option>
<option value="full_name">Name</option>
<option value="address">Address</option>
<option value="city">City</option>
<option value="state">Province</option>
<option value="zip">Code Postal</option>
<option value="country">Country</option>
<option value="home_phone">Tel(Home)</option>
<option value="work_phone">Tel(Work)</option>
<option value="cell_phone">Tel(Mobile)</option>
<option value="email">Email</option>
<option value="conjoint">Joint</option>
<option value="notes">Notes</option>
<option value="birthday">Birthday</option>
</select><input type="hidden" id="h_cols" name="h_cols" value="<?php echo count($buffer_header); ?>" />
</td>
<?php } ?>
</tr>
<?
$fd = fopen ($upload_file, "r");
$i=1;
while (!feof ($fd))
{
$buffer_header = fgetcsv($fd, 100000, ',');
?>
<tr>
<td align="center"><input class="chk" type="checkbox" value="<?=$i?>" name="chk[]" checked="checked" /></td>
<td align="left" ><?php $sql_cat_names = mysql_query("select * from clients_cat where user_id='".$_SESSION['user_id']."' order by cat_name") ;?>
<select class="ann_select" name="cat_id<?=$i?>" id="cat_id<?=$i?>">
<?php while($row_cat_names = mysql_fetch_array($sql_cat_names)){?>
<option value="<?=$row_cat_names['id']?>"><?=$row_cat_names['cat_name']?></option>
<?php } ?>
</select>
</td>
<?php
for($v=0; $v<count($buffer_header);$v++)
{
?>
<td align="center">
<input type="text" value="<?=$buffer_header[$v]?>" name="row_<?=$v?>_<?=$i?>" id="row_<?=$v?>_<?=$i?>" />
</td>
<?php } ?>
</tr>
<?php
$i++;
unset($buffer_header);
}
fclose ($fd);
?>
<tr>
<td colspan="7" align="center">
<input name="Submit" id="Submit" type="submit" value="Submit" />
</td>
</tr>
</table>
</div>
</form>
<?php
}
?>
</fieldset>
</td>
</tr>
</table>

You may insert multiple values in an only insert, and reduce the DDBB load.
In your PHP code, you receive the values, and make a foreach to insert each row one by one. What you should have to do is change your one by one insert to a multiple to one insert.
You're doing:
INSERT INTO table (field1, field2) VALUES ( 'value1', value2');
INSERT INTO table (field1, field2) VALUES ( 'value3', value4');
INSERT INTO table (field1, field2) VALUES ( 'value5', value6');
That gives you 3 connection to database, 3 inserts. Your query should be:
INSERT INTO table (field1, field2) VALUES ( 'value1', value2'), ('value3, 'value4'), ('value5', 'value6');
That gives you 1 connection to database, 3 inserts. Same result, less load.
UPDATE
To accomplish it in your code, you must create a string inside of your foreach with the data you want to insert: Validate the fields, create the string, and then insert them into the DDBB with an insert sentence that is out of your foreach. It's going to be a mess if I try to do it without running the script to check everything goes well, so I can only point you in the way to do the job.

Related

How to get and count post variable (array) in CodeIgniter?

I have form in view (i'm using codeigniter), in the form there's an element (array) like this code below:
<table class="table table-stripped table-bordered" id="tbl-obat">
<colgroup>
<col class="con0">
<col class="con1">
<col class="con0">
<col class="con1">
<col class="con0">
</colgroup>
<thead>
<tr>
<th>No.</th>
<th>Obat</th>
<th>Dosis</th>
<th>Satuan</th>
<th>Jumlah</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div id="1">1</div>
<input type="hidden" name="kd_obat_1" id="kd_obat_1" class="kd_obat" value="02">
</td>
<td>
<input type="text" name="nama_obat_1" id="nama_obat_1" class="nama_obat input-large ui-autocomplete-input valid" autocomplete="off"><span role="status" aria-live="polite" class="ui-helper-hidden-accessible"></span>
</td>
<td>
<input type="text" name="dosis_1" id="dosis_1" class="dosis input-small valid">
</td>
<td>
<select name="satuan_1" id="satuan_1" class="satuan uniformselect valid" style="width:100px;">
<option name="-">Pilih Satuan</option>
<option value="KSKO-01">AMPUL</option>
<option value="KSKO-02">BUAH</option>
<option value="KSKO-03">BOTOL</option>
<option value="KSKO-04">BUNGKUS</option>
<option value="KSKO-05">KAPLET</option>
</select>
</td>
<td>
<input type="text" name="jumlah_1" id="jumlah_1" class="jumlah input-large valid">
</td>
</tr>
<tr>
<td>
<div id="2">2</div>
<input type="hidden" name="kd_obat_2" id="kd_obat_2" class="kd_obat" value="01">
</td>
<td>
<input type="text" name="nama_obat_2" id="nama_obat_2" class="nama_obat input-large ui-autocomplete-input valid" autocomplete="off"><span role="status" aria-live="polite" class="ui-helper-hidden-accessible"></span>
</td>
<td>
<input type="text" name="dosis_2" id="dosis_2" class="dosis input-small valid">
</td>
<td>
<select name="satuan_2" id="satuan_2" class="satuan uniformselect valid" style="width:100px;">
<option name="-">Pilih Satuan</option>
<option value="KSKO-01">AMPUL</option>
<option value="KSKO-02">BUAH</option>
<option value="KSKO-03">BOTOL</option>
<option value="KSKO-04">BUNGKUS</option>
<option value="KSKO-05">KAPLET</option>
</select>
</td>
<td>
<input type="text" name="jumlah_2" id="jumlah_2" class="jumlah input-large valid">
</td>
</tr>
</tbody>
</table>
How can i count an array and get post values in controller codeigniter? i try this code doesnt work :
foreach ($_POST as $key=>$val) {
$$key = $val;
}
$obat = array();
$i = 1;
while(${"nama_obat_".$i}) {
if(isset(${"nama_obat_".$i}) or !empty(${"nama_obat_".$i}) or ${"nama_obat_".$i} !== "")
{
$obat[$i]['kd_trans_pelayanan'] = $trans_id;
$obat[$i]['nama_obat'] = ${"nama_obat_".$i};
$obat[$i]['dosis'] = ${"dosis_".$i};
$obat[$i]['kd_sat_kecil_obat'] = ${"satuan_".$i};
$obat[$i]['qty'] = ${"jumlah_".$i};
$i++;
} else {
exit(1);
}
}
echo '<pre>';
print_r($obat);
Thanks in advance!
EDIT :
i need to count field with name 'kd_obat_x' where x = 1 to n, based on user input. i need algorithm to get how many variables posted based on user input and so on get the data. here's my complete code:
view.php
<h4>Step 3: Obat</h4>
<p>
<table class="table table-stripped table-bordered" id="tbl-obat">
<colgroup>
<col class="con0" />
<col class="con1" />
<col class="con0" />
<col class="con1" />
<col class="con0" />
</colgroup>
<thead>
<tr>
<th>No.</th>
<th>Obat</th>
<th>Dosis</th>
<th>Satuan</th>
<th>Jumlah</th>
</thead>
<tbody></tbody>
</table>
</p>
<p>
<i class="icon-plus icon-white"></i> Tambah
<i class="icon-trash icon-white"></i> Hapus
</p>
my.js
<script type="text/javascript">
// Autocomplete Obat
jQuery(function() {
var counter3 = 1;
var options = {
source: '<?php echo base_url(); ?>admin/autoCompleteObat',
minLength: 2,
focus: function( event, ui ) {
jQuery('#nama_obat_'+counter3).val(ui.item.value);
jQuery(this).closest('tr').find('input.kd_obat').val(ui.item.kd_obat);
},
select: function( event, ui ) {
//event.preventDefault();
jQuery('#nama_obat_'+counter3).val(ui.item.value);
jQuery(this).closest('tr').find('input.kd_obat').val(ui.item.kd_obat);
},
messages: {
noResults: ''
}
};
jQuery('input.nama_obat').live("keydown.autocomplete", function() {
jQuery(this).autocomplete(options);
});
var addInput = function() {
if (counter3 > 1){
jQuery('a#removeObat').removeAttr('disabled');
}
var inputHTML = '<tr><td><div id="'+counter3+'">'+counter3+'</div><input type="hidden" name="kd_obat_'+counter3+'" id="kd_obat_'+counter3+'" class="kd_obat" /></td><td><input type="text" name="nama_obat_'+counter3+'" id="nama_obat_'+counter3+'" class="nama_obat input-large" /></td><td><input type="text" name="dosis_'+counter3+'" id="dosis_'+counter3+'" class="dosis input-small" /></td><td><select name="satuan_'+counter3+'" id="satuan_'+counter3+'" class="satuan uniformselect" style="width:100px;"><option name="-">Pilih Satuan</option><?php foreach($list_satuan_kecil as $lsk) : ?><option value="<?php echo $lsk['kd_sat_kecil_obat']; ?>"><?php echo $lsk['sat_kecil_obat']; ?></option><?php endforeach; ?></select></td><td><input type="text" name="jumlah_'+counter3+'" id="jumlah_'+counter3+'" class="jumlah input-large" /></td></tr>';
jQuery(inputHTML).appendTo("table#tbl-obat tbody");
jQuery("input.nama_obat:last").focus();
jQuery('html, body').animate({
scrollTop: jQuery("input.nama_obat:last").offset().top
}, 2000);
counter3++;
};
var removeInput = function() {
counter3--;
if(counter3 == 1){
jQuery('a#removeObat').attr('disabled','disabled');
//alert("Minimal sisa 1!");
counter3++;
//console.log('Jika Counter == 1 :' + counter3);
}else{
jQuery("table#tbl-obat tbody tr:last").remove();
//console.log('Jika Counter != 1 :' + counter3);
}
jQuery("input.nama_obat:last").focus();
jQuery('html, body').animate({
scrollTop: jQuery("input.nama_obat:last").offset().top
}, 2000);
};
if (!jQuery("table#tbl-obat tbody").find("input.nama_obat").length) {
addInput();
}
jQuery("a#addObat").click(addInput);
jQuery("a#removeObat").click(removeInput);
});
</script>
admin.php (controller)
function autoCompleteObat()
{
if (isset($_REQUEST['term'])){
$q = strtolower($_GET['term']);
$output = $this->m_crud->get_obat($q);
$this->output->set_content_type('application/json')->set_output(json_encode($output));
}
}
/***MASTER PELAYANAN***/
function pelayanan($par1 = '', $par2 = '', $par3 = '')
{
if (!$this->session->userdata('logged_in') == true)
{
redirect('login');
}
if ($par1 == 'tambah') {
$trans_id = $this->m_crud->generate_transaksi();
$pelayanan['kd_trans_pelayanan'] = $trans_id;
$pelayanan['kd_rekam_medis'] = $this->input->post('kd_rekam_medis');
$pelayanan['tgl_pelayanan'] = $this->functions->convert_date_sql($this->input->post('tgl_pelayanan'));
$pelayanan['kd_jenis_layanan'] = $this->input->post('kd_jenis_layanan');
$pelayanan['kd_unit_pelayanan'] = $this->input->post('kd_unit_pelayanan');
$pelayanan['kd_puskesmas'] = 'P3271010101'; //$this->session->userdata('kd_puskesmas'); // harusnya diambil dari session
$pelayanan['kd_dokter'] = $this->input->post('kd_dokter');
$pelayanan['kd_petugas'] = $this->input->post('kd_petugas');
$pelayanan['kd_status_pasien'] = $this->input->post('kd_status_pasien'); // blm
$pelayanan['anamnesa'] = $this->input->post('anamnesa');
$pelayanan['cat_fisik'] = $this->input->post('cat_fisik');
$pelayanan['cat_dokter'] = $this->input->post('cat_dokter');
$pelayanan['kd_bed'] = $this->input->post('kd_bed');
$pelayanan['no_rujukan'] = $this->input->post('no_rujukan');
$pelayanan['tempat_rujukan'] = $this->input->post('tempat_rujukan');
// Pelayanan Obat
$obat = array();
$i = 1;
while(${"nama_obat_".$i}) {
if(isset(${"nama_obat_".$i}) or !empty(${"nama_obat_".$i}) or ${"nama_obat_".$i} !== ""){
$obat[$i]['kd_trans_pelayanan'] = $trans_id;
$obat[$i]['nama_obat'] = ${"nama_obat_".$i};
$obat[$i]['dosis'] = ${"dosis_".$i};
$obat[$i]['kd_sat_kecil_obat'] = ${"satuan_".$i};
$obat[$i]['qty'] = ${"jumlah_".$i};
/* insert db here */
$i++;
} else {
exit(1);
}
}
echo '<pre>';
print_r($obat);
}
}
and finally my model m_crud.php
function get_obat($q){
$this->db->select('kd_obat,nama_obat');
$this->db->like('nama_obat', $q);
$this->db->or_like('kd_obat', $q);
$query = $this->db->get('obat');
$results = array();
if($query->num_rows > 0){
$i = 1;
foreach ($query->result_array() as $row){
$results[$i]['label'] = $row['kd_obat'].' - '.$row['nama_obat']; //build an array
$results[$i]['value'] = htmlentities(stripslashes($row['nama_obat']));
$results[$i]['kd_obat'] = htmlentities(stripslashes($row['kd_obat']));
$i++;
}
}
return $results;
}
You can count all element with 'kd_obat_' using this code:
$count=0;
foreach($arr as $key=>$value){
$pos = strpos($key,'kd_obat_');
if($pos!==false){
$count++;
}else{
continue;
}
}
echo $count;
You can use following snippet for post values:
$this->input->post();
Count Array tuples:
$elements = count($this->input->post());
You can use input library for getting 'POST' data in codeIgniter Framework,
Please add following code in your code and you will get array in post type.
$postData = $this->input->post(); print_r($postData);exit;
Hope this will work for you.
Assuming that you want the values of nama_obat_1, nama_obat_2, nama_obat_3, etc
First of all you need to indicate an array in your name fields as follows
nama_obat[] for the first field, nama_obat[] for the second field and so on
optionally you can do it like this
nama_obat[1] for the first field, nama_obat[2] for the second field and so on
Then in your Controller if you var_dump() this $this->input->post('nama_obat')
will outputs an array of your values.
Then for the counting part, you can use PHP count() function.
If your $this->input->post('nama_obat'); is a one level array then you can use
count($this->input->post('nama_obat')); // or store it in a variable then count it
and if your array is a multilevel array like
array(
'foo' => 'bar',
'myfoo' => array('mybar'=> 'myfoo')
)
Then you can use
count($this->input->post('nama_obat'), COUNT_RECURSIVE); // or store it in a variable then count it

Cannot find validation in html page

<head>
<title> Add User page</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<form name='f2' action="insert_ac.php" method="post" >
<script src="validation.js" type="javascript/text"></script>
</head>
<body onload="firstfocus();">
<table align="center" border="0" cellpadding="3" cellspacing="1">
<tr>
<td> First Name</td><td > : </td>
<td> <input type='text' name='fname' id='fid' size="50" style="background-color:#abcddd; height:18px;" value='' maxlength="100" onblur="fname_validation(5,12);"> </td>
</tr>
<tr>
<td> Last Name</td><td> : </td>
<td> <input type='text' name='lname' id='lid' size="50" style="background-color:#abcddd; height:18px; "value='' maxlength="100" onblur="lname_validation(5,12);"> </td>
</tr>
<tr>
<td> Gender</td><td> : </td>
<td> <input type='radio' name='gend' id='m' value='M' checked>Male <input type='radio' name='gend' id='f' value='F'>Female</td>
</tr>
<tr>
<td> Phone Number</td><td> : </td>
<td> <input type='number_format' name='phone' id='phno'size="50" style="background-color:#abcddd; height:18px; " value=''onblur="allnumeric();"></td>
</tr>
<tr>
<td> Work Experiance</td><td> : </td>
<td><select name="exp" onblur="expselect();">
<option > Select One</option>
<option selected="" value="Default"> Select One </option>
<option value="F"> Fresher </option>
<option value="E"> Experiance</option>
</select></td>
</tr>
<tr>
<td>User Name</td><td>:</td><td> <input type='txt' name='uname' id='uid'size="50" style="background-color:#abcddd; height:18px; " value=''onblur="userid_validation(5,10);"> </td>
</tr>
<tr>
<td>Password</td><td>:</td><td> <input type='password' name='pwd' id='pid' size="50" style="background-color:#abcddd; height:18px; " value=''onblur="passid_validation(7,12);"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td width="84"><input name="enter" class="btn_login" type="submit" value="Submit" onsubmit="alert('Data stored successfully');"/> <input name="cancle" class="btn_login" type="reset" value="Cancle" /></td>
</tr>
</table>
</form>
</body>
</html>
I included the external javascript file using script tag but the validations are not working.
This is my external javascript code which was saved as validation.js and i am unable to find errors in it please help me.
// After form loads focus will go to first name field.
function firstfocus()
{
var fname = document.f2.fname.focus();
return true;
}
// This function will validate First name
function fname_validation(mx,my)
{
var fname = document.f2.fname;
var fname_len = fname.value.length;
var letters = /^[A-Za-z]+$/;
if (fname_len == 0 || fname_len >= my || fname_len < mx)
{
alert("First Name should not be empty / length be between "+mx+" to "+my);
fname.focus();
return false;
if(fname.value.match(letters))
{
// Focus goes to next field i.e.Last Name
document.f2.lname.focus();
return true;
}
}
}
// This function will validate Last name
function lname_validation(mx,my)
{
var lname = document.f2.lname;
var lname_len = lname.value.length;
var letters = /^[A-Za-z]+$/;
if (lname_len == 0 || lname_len >= my || lname_len < mx)
{
alert("Last Name should not be empty / length be between "+mx+" to "+my);
lname.focus();
return false;
if(fname.value.match(letters))
{
// Focus goes to next field i.e.Phone Number
document.f2.phone.focus();
return true;
}
}
}
// This function will validate Phone Number.
function allnumeric()
{
var phone = document.f2.phone;
var numbers = /^[0-9]+$/;
if(phone.value.match(numbers))
{
// Focus goes to next field i.e. Experiance.
document.f2.exp.focus();
return true;
}
else
{
alert('Phone Number must have numeric characters only');
phone.focus();
return false;
}
}
// This function will select Experiance.
function expselect()
{
var exp = document.f2.exp;
if(exp.value == "Default")
{
alert('Select your Experiance from the list');
exp.focus();
return false;
}
else
{
// Focus goes to next field i.e. Username Code.
document.f2.uname.focus();
return true;
}
}
// This function will validate User Name.
function allLetter()
{
var uname = document.f2.uname;
var letters = /^[A-Za-z]+$/;
if(uname.value.match(letters))
{
// Focus goes to next field i.e. Password.
document.f2.pwd.focus();
return true;
}
else
{
alert('Username must have alphabet characters only');
uname.focus();
return false;
}
}
// This function will validate Password.
function passid_validation(mx,my)
{
var passid = document.registration.passid;
var passid_len = passid.value.length;
if (passid_len == 0 ||passid_len >= my || passid_len < mx)
{
alert("Password should not be empty / length be between "+mx+" to "+my);
passid.focus();
return false;
}
}
try to change <script type="javascript/text"> to <script type="text/javascript">
and double check the reference of your js file. Also, put an alert check to determine if it is really going through the firstFocus() function.
You have to reference the .js if its not in the same folder as html
EDIT
function fname_validation(mx,my)
{
is missing a closing bracket!
I changed the java script file and now i can find validations in my form...
Thanks for your help..
here i am sharing my code...
HTML code
<form name='f1' action="insert_ac.php" method="post" onSubmit="return validateForm();" >
<tr>
<td height="25" height="25" colspan="2" bgcolor="#EC6921" class="form_heading">Add User Form</td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt"> First Name:</td>
<td bgcolor="#FFFFFF"> <input type='text' name='fname' id='fid' size="50" style="height:18px;" value='' maxlength="100" ></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt"> Last Name:</td>
<td bgcolor="#FFFFFF" > <input type='text' name='lname' id='lid' size="50" style=" height:18px; "value='' maxlength="100" ></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt"> Gender:</td>
<td bgcolor="#FFFFFF" > <input type='radio' name='gend' id='m' value='M' checked>Male <input type='radio' name='gend' id='f' value='F'>Female</td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt"> Phone Number:</td>
<td bgcolor="#FFFFFF" > <input type='number_format' name='phone' id='phno'size="50" style=" height:18px; " value=''></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt"> Work Experiance:</td>
<td bgcolor="#FFFFFF" ><select name="exp" >
<option selected="" value="Default"> Select One </option>
<option value="Fresher"> Fresher </option>
<option value="Experiance"> Experiance</option>
</select></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt">User Name:</td><td bgcolor="#FFFFFF"> <input type='txt' name='uname' id='uid'size="50" style=" height:18px; " value=''></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt">Password:</td><td bgcolor="#FFFFFF"> <input type='password' name='pwd' id='pid' size="50" style=" height:18px; " value=''></td>
</tr>
</table>
<table align="center">
<tr>
<td ><input name="enter" class="btn_login" type="submit" value="Submit" align="center"><input name="cancle" class="btn_login" type="reset" value="Cancle" valign="right" /></td>
</tr>
</table>
</div>
</div>
</div>
</form>
</body>
</html>
Here is my java script file which is working fine....
var RE = /^.+#.+\..{3}$/;
var RE1 = /^[a-zA-Z]+$/;
var RE2 = /^[0-9]{10}$/;
var RE3 = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
function validateForm()
{
if (document.f1.fname.value == "")
{
window.alert("first name should NOT BE empty");
document.f1.fname.focus();
return false;
}
else
if (RE1.test(document.f1.fname.value) == false)
{
alert("Invalid first name\n\
");
return false;
}
else
if (document.f1.fname.value.length < 3)
{
window.alert("Firstname must have atleast Three characters");
document.f1.fname.focus();
return false;
}
else
if (document.f1.lname.value == "")
{
window.alert("Lastname should not be empty");
document.f1.lname.focus();
return false;
}
else
if (RE1.test(document.f1.lname.value) == false)
{
alert("Invalid last name");
return false;
}
else
if (document.f1.lname.value.length < 4)
{
window.alert("Lastname must have atleast four characters");
document.f1.lname.focus();
return false;
}
else
if (document.f1.lname.value == "")
{
window.alert("Last name should not be empty");
document.f1.lname.focus();
return false;
}
else
if (document.f1.phone.value == "")
{
window.alert("phne no should NOT BE empty");
document.f1.phone.focus();
return false;
} else
if (RE3.test(document.f1.phone.value) == false)
{
alert("Invalid phone number");
document.f1.phone.focus();
return false;
}
else
if (document.f1.exp.selectedIndex == 0)
{
window.alert("please select work experiance ");
return false;
}
else
if (document.f1.uname.value == "")
{
window.alert("UserName should not be empty");
document.f1.uname.focus();
return false;
}
else
if (RE1.test(document.f1.uname.value) == false)
{
window.alert("Invalid userName ");
document.f1.uname.focus();
return false;
}
else
if (document.f1.pwd.value == "")
{
window.alert("password should not be empty");
document.f1.pwd.focus();
return false;
}
else
if (document.f1.pwd.value.length < 6)
{
window.alert("password must have atleast six characters");
document.f1.pwd.focus();
return false;
}
else
{
window.alert("User has been added successfully.");
return true;
}
}

Javascript add MySQL data when checkbox is ticked

I am currently using this javscript and PHP code
<script>
function add(total)
{
form2.thetotal.value = document.forms["form1" + total].total.value;
}
</script>
<form name="form2">
<table width="800" border="0" cellspacing="0" cellpadding="10" style="position:fixed; z-index:-999; background-color:#FFF;">
<tr bgcolor="#eeeeee">
<td> </td>
<td colspan="2" width="50%"><strong>Total: </strong><input type="text" name="thetotal" id="thetotal" size="20" value="0" /></td>
<td colspan="2" width="50%"><strong>VAT:</strong> </td>
</tr>
<tr bgcolor="#eeeeee">
<td width="5%"> </td>
<td width="20%"><strong>Invoice Number</strong></td>
<td width="35%"><strong>Company</strong></td>
<td width="20%"><strong>Date</strong></td>
<td width="20%"><strong>Total</strong></td>
</tr>
</table>
</form>
<form name="form1">
<table width="800" border="0" cellspacing="0" cellpadding="10">
<?php
$sql="SELECT * from billing_pdf_archive order by invoice_number ASC ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
while($result=mysql_fetch_array($rs))
{
$counter++;
$sql2="SELECT * from customer where sequence = '".$result["customer_sequence"]."' ";
$rs2=mysql_query($sql2,$conn) or die(mysql_error());
$result2=mysql_fetch_array($rs2);
$sql3="SELECT * from reseller where sequence = '".$result["reseller_sequence"]."' ";
$rs3=mysql_query($sql3,$conn) or die(mysql_error());
$result3=mysql_fetch_array($rs3);
if($result["customer_sequence"] != '0')
{
$company = $result2["company"];
}
elseif($result["reseller_sequence"] != '0')
{
$company = '<strong>Reseller: </strong>'.$result3["company"];
}
$total = $result["total"];
echo '<tr>
<td width="5%"><input type="checkbox" name="check" id="check" onclick=\'add('.$total.');\' /></td>
<td width="20%">'.$result["invoice_number"].'</td>
<td width="35%">'.$company.'</td>
<td width="20%">'.$result["datetime"].'</td>
<td width="20%">£'.$result["total"].'</td>
</tr>';
}
?>
</table>
</form>
so as you can see it is selecting from the MySQL database and i am trying to make it so when one of the checkboxes is ticked it adds the total into the "thetotal" text field (in form 2) but it is just leaving that box as zero - any ideas on what i could do?
You did not specify the total field for form 1, then it raised javascript error, it wont work.
Check it out
<script>
function add(total)
{
form2.thetotal.value = total + parseFloat(document.form1.formtotal.value);
}
</script>
<form name="form1">
<!-- replace field name formtotal with anything that you want-->
<!-- replace field value with anything that you get from your mysql result-->
<input type="text" name="formtotal" id="formtotal" value="10" />
</form>
Here is how you can do it (assuming total is int and not float):
<script>
function add(total, this_chk_bx)
{
//(if its float, use `parseFloat` instead of `parseInt`)
if(this_chk_bx.checked==true){
//add if its checked
var tot_1 = parseInt(form2.thetotal.value);
form2.thetotal.value = tot_1+parseInt(total);
}
else{
//subtract if its unchecked
}
}
</script>
.
in your php, you have to send the checkbox like this:
onclick=\'add('.$total.', this);\'
.

for update code in same page need ajax or else?

when i press on edit link on detail.php it will show me data.php page with data filled in form... now if i want to edit something then press edit button it would be update.. code of data.php is given as below
<?php if(isset($_GET['name']) && !empty($_GET['name'])):?>
<script>
window.onload=function()
{
document.getElementById("sbmt").style.visibility="hidden";
};
function editform()
{
i need code at this place _what should it be?? i guess i need ajax. when i press edit button it would be edit record i tried below something like below bt for that i need value name=??? how can i get that value _
<?php
$con=mysqli_connect("localhost","root","","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// mysqli_query($con,"UPDATE user_detail SET name=,address=,gender=,hoby=,country=,place=,
//WHERE name='$_GET['name']'");
mysqli_close($con);
?>
};
</script>
<?php
$con=mysqli_connect("localhost","root","","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$p= $_GET['name'];
//echo "$p";
$result = mysqli_query($con,"SELECT * FROM user_detail where name ='$p' ");
$data =mysqli_fetch_array($result);
mysqli_close($con);
?>
<?php else:?>
<script>
window.onload=function()
{
document.getElementById("edit").style.visibility="hidden";
};
</script>
<?php $data =array();?>
<?php endif;?>
<!DOCTYPE html>
<?php
session_start();
if (!isset($_SESSION['txt_user'])) {
header('Location: Login.php');
}
?>
<html>
<head>
<title> Form with Validation </title>
<script language="JavaScript">
var flag=0;
var file_selected = false;
var file_selected1 = false;
function validform()
{
var x=document.forms["form1"]["tname"].value;//Name
var y=document.forms["form1"]["address"].value;//Address
if (x==null || x=="")
{
flag = 1;
document.getElementById('tn').value="Please! Enter name ";
//alert("Please Enter Name:");
//return false;
}
else
{
flag=0;
}
if (y==null || y==" ")
{
flag=flag+1;
document.getElementById('ta').innerHTML="Please! Enter address ";
//alert("Please Enter Address");
//return false;
}
else
{
flag=0;
}
if ((form1.gender[0].checked == false) && (form1.gender[1].checked == false))
{
flag +=1;
document.getElementById('gne').innerHTML="Please! Select gender ";
//alert("Pleae Select Gender");
//return false;
}
else
{
flag =0;
document.getElementById('gne').innerHTML="";
}
if (form1.hobby.checked == false && form1.hobby.checked == false && form1.hobby.checked == false)
{
flag +=1;
document.getElementById('hbe').innerHTML="Please! Select hobby ";
//alert ('Please!!!, Select any hobby!');
//return false;
}
else
{
flag =0;
document.getElementById('hbe').innerHTML="";
}
var psel=document.getElementById('fp'); //Favourite place
var valid = false;
for(var i = 0; i < psel.options.length; i++) {
if(psel.options[i].selected) {
valid = true;
break;
}
}
if(valid==false)
{
flag +=1;
document.getElementById('fp_error').innerHTML="Please! Select Any Favourite Place ";
//return false;
// alert("Please! Select Any Favourite Place ");
}
else
{
flag =0;
document.getElementById('fp_error').innerHTML="";
}
if(!file_selected)
{
flag +=1;
document.getElementById('f_pic').innerHTML="Please! Select Any Picture ";
//alert('Please Select any Picture');
//return false;
}
else
{
flag =0;
document.getElementById('f_pic').innerHTML="";
}
if(!file_selected1)
{
flag +=1;
document.getElementById('f_doc').innerHTML="Please! Select Document";
//alert('Please Select any Document');
//return false;
}
else
{
flag =0;
}
if(flag ==0)
{
document.getElementById('data_form').action = "Data_con.php";
document.getElementById('data_form').submit();
}
else
{
return true;
}
return false;
}
function Logout()
{
document.getElementById('data_form').action = "Logout.php";
}
</script>
</head>
<body>
<!--onsubmit="return validform()"-->
<form id="data_form" name="form1" method="post" enctype="multipart/form-data" action="">
<table align="center" border="2">
<tr>
<td>Name:</td>
<td><input id="tn" type="text" name="tname" <?php if($data['name']):?>value="<?php echo $data['name'];?>" <?php endif;?>></td>
<!--<td id="tne"></td>-->
</tr>
<tr>
<td>Address:</td>
<td><textarea id= "ta" rows="3" cols="16" name="address" >
<?php echo $data['address'];?>
</textarea> </td>
<!--<td id="tae"></td>-->
</tr>
<tr>
<td>Gender:</td>
<?php
$x=$data['gender'];
?>
<td> <input type="radio" id="gn" name="gender" value="male" <?php if($x=='male'):?> checked<?php endif;?> > Male
<input type="radio" id="gn" name="gender" value="female" <?php if($x=='female'):?> checked<?php endif;?> > Female
</td>
<td id="gne"></td>
</tr>
<tr>
<td>Hobby:</td>
<?php
$y=$data['hoby'];
?>
<td>
<input type="checkbox" name="hobby" value="hockey" <?php if($y=='hockey'):?> checked='checked';<?php endif;?>> Hockey
<input type="checkbox" name="hobby" value="reading" <?php if($y=='reading'):?> checked='checked';<?php endif;?>> Reading<br>
<input type="checkbox" name="hobby" value="traveling" <?php if($y=='traveling'):?> checked='checked';<?php endif;?>> Traveling
<br>
</td>
<td id="hbe"></td>
</tr>
<tr>
<td>Country: </td>
<?php
$z=$data['country'];
?>
<td>
<select name="helo" id="hl">
<option value="germany"<?php if($z=='germany'):?> selected<?php endif;?> >Germany </option>
<option value="india" <?php if($z=='india'):?> selected <?php endif;?> >India </option>
<option value="japan" <?php if($z=='japan'):?> selected<?php endif;?> >Japan </option>
</select>
</td>
<td id="hle"></td>
</tr>
<tr>
<td>Favourite Place:</td>
<?php
$w =$data['place'];
?>
<td>
<select id="fp" name="place" multiple="multiple">
<option value="ahmedabad" <?php if($w=='ahmedabad'):?> selected<?php endif;?> >Ahmedabad</option>
<option value="nadiad" <?php if($w=='nadiad'):?> selected<?php endif;?> >Nadiad</option>
<option value="anand" <?php if($w=='anand'):?> selected<?php endif;?> >Anand</option>
<option value="vadodara" <?php if($w=='vadodara'):?> selected<?php endif;?> >Vadodara</option>
<option value="surat" <?php if($w=='surat'):?> selected<?php endif;?> >Surat</option>
</select>
</td>
<td id="fp_error"></td>
</tr>
<tr>
<td>Photo:</td>
<td><input type="file" onchange="file_selected=true;" name="pic" ></td>
<td id="f_pic"></td>
</tr>
<tr>
<td>Resume:</td>
<td><input type="file" onchange="file_selected1=true;" name="doc" ></td>
<td id="f_doc"></td>
</tr>
<tr>
<td colspan="2"><center>
<input type="Submit" id="edit" value="edit" Name="Edit" onclick="editform();">
<input type="button" id="sbmt" value="Submit" Name="Submit" onclick="validform();">
<input type="submit" value="Logout" Name="Submit" onclick="Logout();">
<center></td>
</tr>
</table>
</form>
</body>
</html>
Thanks friend...

Accessing Checkboxes Values And Using Functions in PHP

I am having problem in this situation, i searched alot and don't know what should i do with it....
I have got like 4 checkboxes, on each checkbox a certain function is being performed. I have this html code for checkboxes,
<form action="check.php" method="post">
<table border="1" width="200">
<tr>
<td>
<input type="checkbox" name="first[]" value="option1" />
</td>
<td width="500">
<strong>Option 1</strong>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="first[]" value="option2" />
</td>
<td width="500">
<strong>Option 2</strong>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="first[]" value="option3" />
</td>
<td width="500">
<strong>option 3</strong>
</td>
</tr>
</table>
<table border="1" width="200">
<tr>
<td>
<input type="text" name="entered_value"/>
</td>
</tr>
</table>
<table border="1" width="200">
<tr>
<td>
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form>
I am accessing these checkboxes using this code
<?php
if (isset($_POST['submit']))
{
if(isset($_POST['first']))
{
$get_data_checkboxes = $_POST['first'];
}
else
{
$get_data_checkboxes = "";
}
print_r($get_data_checkboxes);
exit();
}
?>
What i am facing problem is like i need to run a function on each checkbox ticked, e.g. if the person ticks Option 1 then i should be able to run function 1 and so on...
any help will be appreciated :)
If you want to select multiple checkboxes, you can try something like this:
for( $i = 0; $i < count( $_POST['first'] ); $i++ ) {
if( $_POST['first'][$i] == 'option1' ) {
echo "function1";
} else if( $_POST['first'][$i] == 'option2' ) {
echo "function2";
} else if( $_POST['first'][$i] == 'option3' ) {
echo "function3";
}
}
You don't need the line
if (isset($_POST['submit']))
Without that your code works fine, and you can use that to call your functions like this:
<?php
if(isset($_POST['first']))
{
$get_data_checkboxes = $_POST['first'];
foreach($get_data_checkboxes as $value){
//call functions named option1(), option2(), etc..
call_user_func($value);
}
}
else{
$get_data_checkboxes = "";
}
?>

Categories