I`m trying to insert data into a database, from an excel file but starting from column 2 because the first column is being used for the name of the row in the table.
This is my form to input the file, this code reads from the first column, I want to start reading from column 2.
<h2>Import Excel File into MySQL Database using PHP</h2>
<div class="outer-container">
<form action="import.php" method="post"
name="frmExcelImport" id="frmExcelImport" enctype="multipart/form-data">
<div>
<label>Choose Excel
File</label> <input type="file" name="file"
id="file" accept=".xls,.xlsx">
<button type="submit" id="submit" name="import"
class="btn-submit">Import</button>
</div>
</form>
</div>
<div id="response" class="<?php if(!empty($type)) { echo $type . " display-block"; } ?>"><?php if(!empty($message)) { echo $message; } ?></div>
and this is the action file:
<?php
include 'koneksi/koneksi.php';
require_once('vendor/php-excel-reader/excel_reader2.php');
require_once('vendor/SpreadsheetReader.php');
if (isset($_POST["import"]))
{
$allowedFileType = ['application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
if(in_array($_FILES["file"]["type"],$allowedFileType)){
$targetPath = 'uploads/'.$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $targetPath);
$Reader = new SpreadsheetReader($targetPath);
$sheetCount = count($Reader->sheets());
for($i=0;$i<$sheetCount;$i++)
{
$Reader->ChangeSheet($i);
foreach ($Reader as $Row )
{
$id_koperasi = "";
if(isset($Row[0])) {
$id_koperasi = mysqli_real_escape_string($con,$Row[0]);
}
$nama_koperasi = "";
if(isset($Row[1])) {
$nama_koperasi = mysqli_real_escape_string($con,$Row[1]);
}
$alamat = "";
if(isset($Row[2])) {
$alamat = mysqli_real_escape_string($con,$Row[2]);
}
$telp = "";
if(isset($Row[3])) {
$telp = mysqli_real_escape_string($con,$Row[3]);
}
$hp = "";
if(isset($Row[4])) {
$hp = mysqli_real_escape_string($con,$Row[4]);
}
$nama_cp = "";
if(isset($Row[5])) {
$nama_cp = mysqli_real_escape_string($con,$Row[5]);
}
$email = "";
if(isset($Row[6])) {
$email = mysqli_real_escape_string($con,$Row[6]);
}
$tanggal_fu = "";
if(isset($Row[7])) {
$tanggal_fu = mysqli_real_escape_string($con,$Row[7]);
}
$ket_fu = "";
if(isset($Row[8])) {
$ket_fu = mysqli_real_escape_string($con,$Row[8]);
}
$hasil_pembahasan = "";
if(isset($Row[9])) {
$hasil_pembahasan = mysqli_real_escape_string($con,$Row[9]);
}
$status = "";
if(isset($Row[10])) {
$status = mysqli_real_escape_string($con,$Row[10]);
}
$provinsi = "";
if(isset($Row[11])) {
$provinsi = mysqli_real_escape_string($con,$Row[11]);
}
$kota = "";
if(isset($Row[12])) {
$kota = mysqli_real_escape_string($con,$Row[12]);
}
$kec = "";
if(isset($Row[13])) {
$kec = mysqli_real_escape_string($con,$Row[13]);
}
$kel = "";
if(isset($Row[14])) {
$kel = mysqli_real_escape_string($con,$Row[14]);
}
$rt = "";
if(isset($Row[15])) {
$rt = mysqli_real_escape_string($con,$Row[15]);
}
$rw = "";
if(isset($Row[16])) {
$rw = mysqli_real_escape_string($con,$Row[16]);
}
$jln = "";
if(isset($Row[17])) {
$jln = mysqli_real_escape_string($con,$Row[17]);
}
$kodep = "";
if(isset($Row[18])) {
$kodep = mysqli_real_escape_string($con,$Row[18]);
}
if (!empty($id_koperasi) || !empty($nama_koperasi) || !empty($alamat) || !empty($telp) || !empty($hp) || !empty($nama_cp) || !empty($email) || !empty($tanggal_fu) || !empty($ket_fu) || !empty($hasil_pembahasan) || !empty($status) || !empty($provinsi) || !empty($kota) || !empty($kec) || !empty($kel) || !empty($rt) || !empty($rw) || !empty($jln) || !empty($kodep) ) {
$query = "INSERT INTO t_koperasi(id,id_koperasi,nama_koperasi,alamat,telp,hp,nama_cp,email,tanggal_fu,ket_fu,hasil_pembahasan,status,provinsi,kota,kec,kel,rt,rw,jln,kodep) VALUES ('',
'$id_koperasi',
'$nama_koperasi',
'$alamat',
'$telp',
'$hp',
'$nama_cp',
'$email',
'$tanggal_fu',
'$ket_fu',
'$hasil_pembahasan',
'$status',
'$provinsi',
'$kota',
'$kec',
'$kel',
'$rt',
'$rw',
'$jln',
'$kodep')" or die(mysqli_error($con));
;
$result = mysqli_query($con, $query);
if (! empty($result)) {
$type = "success";
$message = "SUKSES";
} else {
$type = "error";
$message = "Problem in Importing Excel Data";
}
}
}
}
}
else
{
$type = "error";
$message = "Invalid File Type. Upload Excel File.";
}
}
include 'views/v_import.php'
?>
I already tried to put $col = 1 but it still wont work, I tried using the for=i but it still will not work.
a possible solution with an extra counter
$Reader->ChangeSheet($i);
$number = 0;
foreach ($Reader as $Row )
{
if ($number!=0) {
......
}
$number++;
}
Related
This question already has answers here:
mysql update - skip blank fields?
(3 answers)
Closed 1 year ago.
Is there a way to update one or more field ignoring the empty fields in MySQL and PHP?
These are values that I need to enter in a HTML form:
<input type='text' placeholder='ID' name='ID' value='' id='ID'>
<input type='text' placeholder='Product name' name='prod_name' value=''>
<input type='text' placeholder='Description' name='prod_desc' value=''>
<input type='text' placeholder='Solde price' name='prod_s_price' value=''>
<input type='text' placeholder='Reg. price' name='prod_r_price' value=''>
<input type='text' placeholder='Product model' name='prod_mod' value=''>
When I submit the values, they are stored in those variables:
$prod_id = $_POST['ID']; //Int ID
$prod_name = $_POST['prod_name']; //String
$prod_desc = $_POST["prod_desc"]; //String
$prod_s_price = $_POST["prod_s_price"]; //Float
$prod_r_price = $_POST["prod_r_price"]; //Float
$prod_mod = $_POST["prod_mod"]; //String
When we send the POST request, it goes in a MySQL query:
if ($_POST['ID'] == null) {
header('Location: ../index.php?update=error_undefined');
} else {
$sql = "UPDATE app SET app_name='$prod_name', app_desc='$prod_desc', app_s_price=$prod_s_price, app_r_price=$prod_r_price, app_mod='$prod_mod' WHERE app_id=$prod_id;";
$result = mysqli_query($conn, $sql);
header('Location: ../index.php?update=succes');
}
Use the following, it will not arise any sort of issue.
if ($_POST['ID'] == null) {
header('Location: ../index.php?update=error_undefined');
} else {
$update_any = false;
$sql = "UPDATE app SET ";
$prod1 = null;
if (!empty($prod_name)) {
$prod1 = "app_name='$prod_name', ";
$update_any = true;
}
$prod2 = null;
if (!empty($prod_desc)) {
$prod2 = "app_desc='$prod_desc', ";
$update_any = true;
}
$prod3 = null;
if (!empty($prod_s_price)) {
$prod3 = "app_s_price='$prod_s_price', ";
$update_any = true;
}
$prod4 = null;
if (!empty($prod_r_price)) {
$prod4 = "app_r_price='$prod_r_price', ";
$update_any = true;
}
$prod5 = null;
if (!empty($prod_mod)) {
$prod5 = "app_mod='$prod_mod', ";
$update_any = true;
}
$notrimed_query = $prod1.$prod2.$prod3.$prod4.$prod5;
$trimed_query = rtrim($notrimed_query, ", ");
$query = $sql.$trimed_query." WHERE app_id=$prod_id;";
if ($update_any)
{
mysqli_query($conn, $query);
header('Location: ../index.php?update=succes');
}
else
{
echo "No Update Occur.";
}
}
Work juste fine that way! Just need to replace the PHP code to that! Thanks to me.
if ($_POST['ID'] == null) {
header('Location: ../index.php?update=error_undefined');
} else {
$sql = "UPDATE app SET ";
$prod1 = null;
if (!empty($prod_name)) {
$prod1 = "app_name='$prod_name', ";
}
$prod2 = null;
if (!empty($prod_desc)) {
$prod2 = "app_desc='$prod_desc', ";
}
$prod3 = null;
if (!empty($prod_s_price)) {
$prod3 = "app_s_price='$prod_s_price', ";
}
$prod4 = null;
if (!empty($prod_r_price)) {
$prod4 = "app_r_price='$prod_r_price', ";
}
$prod5 = null;
if (!empty($prod_mod)) {
$prod5 = "app_mod='$prod_mod', ";
}
$notrimed_query = $prod1.$prod2.$prod3.$prod4.$prod5;
$trimed_query = rtrim($notrimed_query, ", ");
$query = $sql.$trimed_query." WHERE app_id=$prod_id;";
mysqli_query($conn, $query);
header('Location: ../index.php?update=succes');
}
I am trying to upload an excel file using the HTML input tag, to MySQL database using PHP. But the result is a whole lot of characters in the database. the only time it works correctly is when I create a .csv file with notepad and upload it.
if(isset($_POST['submit_excel'])){
if(!is_uploaded_file($_FILES['file_excel']['tmp_name'])){
echo '<script type="text/javascript">function hideMsg(){
document.getElementById("popup_no_f").style.visibility = "hidden"; } document.getElementById("popup_no_f").style.visibility = "visible";
window.setTimeout("hideMsg()", 4000);
</script>';
} else {
$filename = $_FILES['file_excel']['name'];
$extension = pathinfo($filename, PATHINFO_EXTENSION);
if ($extension == 'xlsx' || $extension == 'csv' || $extension == 'xls') {
if($_FILES['file_excel']["size"] > 0)
{
$handle = fopen($_FILES['file_excel']['tmp_name'], "r");
$count = 0;
while (($data = fgetcsv($handle, 1024, ",")) !== FALSE)
{
$count++;
if ($count>1) {
if (empty(data[0]) && empty(data[1]) && empty(data[2]) && empty(data[3]) && empty(data[4]) ){
echo alert();
}else{
do{
$bookuniqueid = uniqueid();
$query = "SELECT book_unique_id FROM books_tbl WHERE book_unique_id= '$bookuniqueid' ";
$query_run = mysqli_query($link, $query);
$numRowsCheck = mysqli_num_rows($query_run);
} while ( $numRowsCheck > 0);
$import ="INSERT INTO books_tbl (book_name, book_authors, book_category, book_quantity, book_cd, book_unique_id, book_uploaded_admin, book_created_date, book_quant_stat) VALUES ('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]', '$bookuniqueid', '$adminname', current_date, '$data[3]' )";
mysqli_query($link, $import);
}
}
}
fclose($handle);
echo '<script type="text/javascript">function hideMsg(){
document.getElementById("popup").style.visibility = "hidden"; } document.getElementById("popup").style.visibility = "visible";
window.setTimeout("hideMsg()", 4000);
</script>';
}
} else {
echo '<script type="text/javascript">function hideMsg(){
document.getElementById("popup_ext").style.visibility = "hidden"; } document.getElementById("popup_ext").style.visibility = "visible";
window.setTimeout("hideMsg()", 4000);
</script>';
}
}
In my Yii web application I want to write a web service for mobile application. I create a url for access student details with GET method. That I want to change GET method to POST method or PUT method. My url is,
url/index.php/user/login/studentdetails/?username=demo
I am getting this username from client side and giving the response from server side to client side in json format.
My code is,
public function actionStudentdetails() {
if (isset($_GET['username'])) {
$user = Users::model()->findByAttributes(array('username' => $_GET['username']));
$usertypeid = $user->usertypeid;
if ($usertypeid === '1') {
$studentid = $user->userid;
} else if ($usertypeid === '3') {
$guardianid = $user->userid;
$studentid = $_GET['studentid'];
} else {
$employeemasterid = $user->userid;
}
$student = Student::model()->findByPk($studentid);
header('Content-type: application/json');
$response["student_admissionno"] = $student->student_admissionno;
$response["student_firstname"] = $student->student_firstname;
$response["student_middlename"] = $student->student_middlename;
$response["student_lastname"] = $student->student_lastname;
$response["student_admissiondate"] = $student->student_admissiondate;
$response["student_dob"] = $student->student_dob;
$response["student_gender"] = $student->student_gender;
$response["student_religion"] = $student->student_religion;
$response["student_caste"] = $student->student_caste;
$response["student_address1"] = $student->student_address1;
$response["student_address2"] = $student->student_address2;
$response["student_city"] = $student->student_city;
$response["student_state"] = $student->student_state;
$response["success"] = 1;
$response["message"] = "success";
echo json_encode($response);
}
}
}
Please help me.
you can try this code for webserivce. you can used any method GET or POST Method of data posting in server side.
StudentController.php
public function actionStudentdetails() {
$json_data = array();
$params = isset($_REQUEST) ? $_REQUEST: "";
if (!empty($params)) {
$username = $params['username'];
if($username == "") {
$json_data['success'] = false;
$json_data['message'] = 'Username are required.';
} else {
$user = Users::model()->findByAttributes(array('username' => $params['username']));
$usertypeid = $user->usertypeid;
if ($usertypeid === '1') {
$studentid = $user->userid;
} else if ($usertypeid === '3') {
$guardianid = $user->userid;
$studentid = $_GET['studentid'];
} else {
$employeemasterid = $user->userid;
}
$student = Student::model()->findByPk($studentid);
header('Content-type: application/json');
$json_data["student_admissionno"] = $student->student_admissionno;
$json_data["student_firstname"] = $student->student_firstname;
$json_data["student_middlename"] = $student->student_middlename;
$json_data["student_lastname"] = $student->student_lastname;
$json_data["student_admissiondate"] = $student->student_admissiondate;
$json_data["student_dob"] = $student->student_dob;
$json_data["student_gender"] = $student->student_gender;
$json_data["student_religion"] = $student->student_religion;
$json_data["student_caste"] = $student->student_caste;
$json_data["student_address1"] = $student->student_address1;
$json_data["student_address2"] = $student->student_address2;
$json_data["student_city"] = $student->student_city;
$json_data["student_state"] = $student->student_state;
$json_data['success'] = true;
$json_data['message'] = "Data found Successful.";
}
} else {
$json_data['success'] = false;
$json_data['message'] = "Please try again.";
}
echo json_encode($response);
}
I'm developing a simple PHP website. I have a form for updating values. When that form is accessed via PHP(website) , It should have previous values, But it hasn't. How to do that ?
Because, Otherwise, It shows all fields empty and when one or two are updated, Other gets updated as empty. Please help !
<?php
require_once('../includes/config.php');
require_once('../includes/functions.php');
require_once('../includes/session.php');
require_once('../includes/database.php');
require_once('../includes/user.php');
require_once('../includes/photograph.php');
if (!$session->is_logged_in()) { redirect_to("login.php"); }
?>
<?php
// START FORM PROCESSING
if (isset($_POST['submit'])) { // Form has been submitted.
$errors = array();
// perform validations on the form data
$required_fields = array('lives_in', 'belongs_to', 'college', 'works_at', 'grade', 'grade2', 'hobbies', 'zodiac', 'phone_no', 'facebook', 'company', 'bio');
$errors = array_merge($errors, check_required_fields($required_fields, $_POST));
$lives_in = trim($database->escape_value($_POST['lives_in']));
$belongs_to = trim($database->escape_value($_POST['belongs_to']));
$college = trim($database->escape_value($_POST['college']));
$works_at = trim($database->escape_value($_POST['works_at']));
$grade = trim($database->escape_value($_POST['grade']));
$grade2 = trim($database->escape_value($_POST['grade2']));
$hobbies = trim($database->escape_value($_POST['hobbies']));
$zodiac = trim($database->escape_value($_POST['zodiac']));
$phone_no = trim($database->escape_value($_POST['phone_no']));
$facebook = trim($database->escape_value($_POST['facebook']));
$company = trim($database->escape_value($_POST['company']));
$bio = trim($database->escape_value($_POST['bio']));
if (empty($errors) ) {
$query = "UPDATE users
SET lives_in = '{$lives_in}',
belongs_to = '{$belongs_to}',
college = '{$college}' ,
works_at = '{$works_at}',
grade = '{$grade}',
grade2 = '{$grade2}',
hobbies = '{$hobbies}',
zodiac = '{$zodiac}',
phone_no = '{$phone_no}',
facebook = '{$facebook}',
company = '{$company}',
bio = '{$bio}'
WHERE id = 23
LIMIT 1";
$result = mysql_query($query, $database->connection);
if ($result) {
$message = "Account Updated";
} else {
$message = mysql_error();
}
} else {
if (count($errors) == 1) {
$message = mysql_error();;
} else {
$message = "There were " . count($errors) . " errors in the form.";
}
}
} else { // Form has not been submitted.
$lives_in = "";
$belongs_to = "";
$college = "";
$works_at = "";
$grade = "";
$grade2 = "";
$hobbies = "";
$zodiac = "";
$phone_no = "";
$facebook = "";
$company = "";
$bio = "";
}
?>
It's very easy, just print out the previous values in the form when you create it with php.
For example:
<input type="text" name="field_name" value="<?php echo $previous_value;?>" />
Or, if it's a select, let's say:
<select name="field_name">
<?php foreach($posible_values as $value){ ?>
<option value="<?php echo $value;?>"
<?php echo ($value==$previous_value)?'selected="selected"':'';?> >
<?echo $value?>
</option>
<?php } ?>
</select>
I'm trying to insert status update into my database in table called blabbing, but it's not working.
my php code
$thisRandNum = rand(9999999999999,999999999999999999);
$_SESSION['wipit'] = base64_encode($thisRandNum); // Will always overwrite itself each time this script runs
// ------- POST NEW BLAB TO DATABASE ---------
$blab_outout_msg = "";
if (isset($_POST['status']) && $_POST['status'] != "" && $_POST['status'] != " "){
$blabWipit = $_POST['blabWipit'];
$sessWipit = base64_decode($_SESSION['wipit']);
if (!isset($_SESSION['wipit'])) {
} else if ($blabWipit == $sessWipit) {
// End Delete any blabs over 20 for this member
$status = $_POST['status'];
$status = stripslashes($status);
$status = strip_tags($status);
$status = mysql_real_escape_string($status);
$status = str_replace("'", "'", $status);
$sql = mysql_query("INSERT INTO blabbing (mem_id, profile_id, the_blab, blab_date) VALUES('$logOptions_id','$logOptions_id','$status', now())");
$blab_outout_msg = "";
}
}
my html code
<div style="background-color:#f2f2f2; border:#ebebeb 1px solid; padding:8px;">
<form action="home.php" method="post" enctype="multipart/form-data" name="blab_from">
<textarea name="status" id="status" rows="3" style="width:99%;"></textarea>
<input name="submit" type="submit" class="btn" value="Blab" /> Limit: <script>displaylimit("","status",255)</script>
<input name="blabWipit" type="hidden" value="<? print $thisRandNum;?>" />
</form>
</div>
any help appreciated
$thisRandNum = rand(9999999999999,999999999999999999);
$_SESSION['wipit'] = base64_encode($thisRandNum); // Will always overwrite itself each time this script runs
// ------- POST NEW BLAB TO DATABASE ---------
$blab_outout_msg = "";
if (isset($_POST['status']) && $_POST['status'] != "" && $_POST['status'] != " "){
$blabWipit = $_POST['blabWipit'];
$sessWipit = base64_decode($_SESSION['wipit']);
// if (!isset($_SESSION['wipit'])) {
//} else if ($blabWipit == $sessWipit) {
// End Delete any blabs over 20 for this member
$status = $_POST['status'];
$status = stripslashes($status);
$status = strip_tags($status);
$status = mysql_real_escape_string($status);
$status = str_replace("'", "'", $status);
$sql = mysql_query("INSERT INTO blabbing (mem_id, profile_id, the_blab, blab_date) VALUES('$logOptions_id','$logOptions_id','$status', now())");
$blab_outout_msg = "";
// }
}
Try this if it works then else if ($blabWipit == $sessWipit) { this condition is not true