Insert into csv file with a new line each - php

I try to insert data from a form into a csv file the insert work fine but i have a problem with the new line i did different search and have different solution but nothing work for me
this is the code
$file = fopen('contacts.csv', 'a+');
// open the file and check for a character
if( fread($file, 1) != "" ){
// file has data, write new line
fwrite($file, "\n");
}else{
// file doesnt have data, no new line needed
}
$csv=array();
$csv[] = $_POST['txt_number'];
$csv[] = $_POST['txt_stage'];
$csv[] = $_POST['txt_category'];
$csv[] = $_POST['txt_description'];
$csv[] = $_POST['txt_division'];
$csv[] = $_POST['txt_notapprove'];
$csv[] = $_POST['txt_approve'];
$csv[] = $_POST['txt_notexist'];
$csv[] = $_POST['txt_priority'];
$csv[] = $_POST['txt_frequency'];
$csv[] = $_POST['startdate'];
$csv[] = $_POST['enddate'];
$csv[] = $_POST['duration'];
$csv[] = $_POST['txt_asd'];
$csv[] = $_POST['txt_add'];
$csv[] = $_POST['txt_aduration'];
$csv[] = $_POST['txt_transferredto'];
$csv[] = $_POST['txt_wo'];
$csv[] = $_POST['txt_percentage'];
$csv[] = $_POST['txt_note'];
// put data stored in $csv into file
fputcsv($file,$csv);
fclose($file);
the out put i want in the file is like this example
,,,test,test,,,,,, new line for a new date
,,,test2,test2,,,,,
i used different thing "\n","\r","\n\r"
but this solution didn't work
once it give me the result with new line without cama "," and that what i don't want
than how to solve this problem to a new line in a csv file in the look i want ?
<div class="form-group">
<label class="col-sm-3 control-label" for="textinput">Description</label>
<div class="col-sm-3">
<input id="textinput" name="txt_description" type="text" placeholder="Description" class="form-control input-md">
</div>
<label class="col-sm-3 control-label" for="textinput">Division</label>
<div class="col-sm-3">
<input id="textinput" name="txt_division" type="text" placeholder="Division" class="form-control input-md" >
</div></div>
<div class="form-group">
<label class="col-sm-3 control-label" for="textinput">Stage</label>
<div class="col-sm-3">
<input id="textinput" name="txt_stage" type="text" placeholder="Stage" class="form-control input-md" >
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="textinput">Category</label>
<div class="col-sm-3">
<input id="textinput" name="txt_category" type="text" placeholder="Category" class="form-control input-md" >
</div>
<label class="col-md-3 control-label" for="radios">Priority</label>
<div class="col-sm-3">
<select id="selectbasic" name="txt_priority" class="form-control">
<option value=""></option>
<option value="Low Priority">Low Priority</option>
<option value="Routine">Routine</option>
<option value="Urgent">Urgent</option>
<option value="Important">Important</option>
</select>
</div>
</div>
<label class="col-sm-3 control-label" for="textinput">Frequency</label>
<div class="col-sm-3">
<select id="selectbasic" name="txt_frequency" class="form-control">
<option value=""></option>
<option value="Once">Once</option>
<option value="Daily">Daily</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
<option value="Semiannual">Semiannual</option>
</select>
</div>
<label class="col-sm-3 control-label" for="textinput">Transferred To</label>
<div class="col-sm-3">
<?php
$q=mysqli_query($conn,"SELECT concat(db_fname,' ' , db_lname) as fname from tbl_user where db_level!='4'
UNION
SELECT db_CompanyName as scn from tbl_supplier
UNION
SELECT db_CompanyName as sucn from tbl_subcontractor
")or die(mysqli_error($conn));
echo'<select name="txt_transferredto" class="form-control inpu-md" >';
echo"<option value=''></option>";
while($row=mysqli_fetch_array($q)){
$fname=$row['fname'];
$companyname=$row['scn'];
$subcompanyname=$row['sucn'];
if($fname!=""){
echo"<option value='$fname'>";echo $fname;echo"</option>";}
else if($subcompanyname!=""){
echo"<option value='$subcompanyname'>";echo $subcompanyname;echo"</option>";}
else if($companyname!=""){
echo"<option value='$companyname'>";echo $companyname;echo"</option>";}
}
echo'</select>';
?>
</div>
<label class="col-sm-3 control-label" for="textinput">WO</label>
<div class="col-sm-3">
<input id="textinput" name="txt_wo" type="text" placeholder="WO" class="form-control input-md">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="checkbox">Not Approve</label>
<div class="col-sm-3">
<input type = 'Radio' Name ='exist' value= 'Not Approve' >
</div>
<label class="col-sm-4 control-label" for="checkbox">Approve</label>
<div class="col-sm-3">
<input type = 'Radio' Name ='exist' value= 'Approve'>
</div>
<label class="col-sm-4 control-label" for="checkbox">Not Exist</label>
<div class="col-sm-3">
<input type = 'Radio' Name ='exist' value= 'Not Exist' >
</div>
<label class="col-sm-3 control-label" for="textinput">Percentage</label>
<div class="col-sm-3">
<input id="textinput" name="txt_percentage" type="text" placeholder="Percentage" class="form-control input-md">
</div>
</div>
<!--Planing Date-->
<div class="form-group">
<label class="col-sm-3 control-label" for="textinput">Planing Start Date</label>
<div class="col-sm-3">
<input id="basic_example_1" name="startdate" type="text" placeholder="planing Date" class="form-control input-md" onfocus="(this.type='date')" onblur="(this.type='text')" onChange="onDateChange()" onchange="cal()">
</div>
<label class="col-sm-3 control-label" for="textinput">Planing DUE Date</label>
<div class="col-sm-3">
<input id="basic_example_2" name="enddate" type="text" placeholder="planing Date" class="form-control input-md" onfocus="(this.type='date')" onblur="(this.type='text')" onchange="cal()" >
</div>
<label class="col-sm-3 control-label" for="textinput" >Duration</label>
<div class="col-sm-3">
<input id="duration" name="duration" type="text" placeholder="Duration" class="form-control input-md" onChange="onDateChange()" >
</div>
</div>
<!--Actual Date -->
<div class="form-group">
<label class="col-sm-3 control-label" for="textinput">Actual Start Date</label>
<div class="col-sm-3">
<input id="basic_example_3" name="txt_asd" type="text" placeholder="Actual Date" class="form-control input-md" onfocus="(this.type='date')" onblur="(this.type='text')" onChange="onDateChange()" onchange="call()" >
</div>
<label class="col-sm-3 control-label" for="textinput">Actual DUE Date</label>
<div class="col-sm-3">
<input id="basic_example_4" name="txt_add" type="text" placeholder="Actual Date" class="form-control input-md" onfocus="(this.type='date')" onblur="(this.type='text')" onchange="call()" >
</div>
<label class="col-sm-3 control-label" for="textinput" >Duration</label>
<div class="col-sm-3">
<input id="aduration" name="txt_aduration" type="text" placeholder="Duration" class="form-control input-md" onChange="onDateChange()" >
</div>
</div>
<!--progress Bar-->
<!-- Textarea -->
<div class="form-group">
<label class="col-md-3 control-label" for="textarea">Notes</label>
<div class="col-md-9">
<textarea class="form-control" id="textarea" name="txt_note" ></textarea>
</div>
</div>
<!-- Button (Double) -->
<div class="form-group">
<label class="col-md-3 control-label" for="button1id"></label>
<div class="col-md-8">
<input type="submit" name="submit" value="Save" class="btn btn-success">
</div>

Format your CSV as multi-dimensional array. First level index means row index, second level index means column index.
$csv = [
[
'test',
'test',
'test',
],
[
'test2',
'test2',
'test2',
]
];
To write to CSV use loop and write line by line:
$file = fopen('contacts.csv', 'a+');
foreach ($csv as $row) {
fputcsv($file, $row);
}
fclose($file);
Than you will get output as
test,test,test
test2,test2,test2

Unless you are needing the fields in a different order in the csv than they appear in the form or I have missed the point here then the following works - every time the form is submitted it writes a new line with the $_POST data.
$filename = __DIR__ . '/contacts.csv';
$file = fopen( $filename, 'a+' );
fputcsv( $file, $_POST );
fclose( $file );
To test that each entry is on a new line, after the above code try adding:
$lines=file( $filename );
foreach( $lines as $line )echo $line.'<br />';
That shows each line being rendered with a br tag afterwards so you can assume that the line endings are being recognised correctly and that you should therefore be able to use that to enter to the db.
An alternative method that generates each $_POST on a new line that DOES appear correctly in Notepad.
$filename=__DIR__.'/contacts.csv';
file_put_contents( $filename, '"' . implode( '","', $_POST ). '"' . PHP_EOL, FILE_APPEND | FILE_TEXT );

the solution is this code work don't use notepad to see the result if you want you can also use PHP_EOL it work on notepad and other editor thanks for all for your response or can you use without PHP_EOL or \n

Related

I am have been trying to write the input of a form into a textfile but it doesn't work [duplicate]

This question already has answers here:
How can I get useful error messages in PHP?
(41 answers)
Closed 2 years ago.
I have this assignment I am trying to solve, I have a piece of code I am trying to run to save my class details on a textfile but the form doesnt write to the text file .. below is the code, i'm a beginner please try enlighten me thank you..
<?php
if(isset($_POST['submit']))
{
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];
$sex = $_POST['sex'];
$address = $_POST['address'];
$city = $_POST['city'];
$zip = $_POST['zip'];
$grade = $_POST['grade'];
$email = $_POST['email'];
$file = fopen("schooldetails.txt","a") or die("file not open");
$s = $fname.",".$lname.$age.$sex.$address.$city.$zip.$grade.$email."\n";
fputs($file,$s) or die ("cannot write data");
fclose($file);
}
?>
This above is the php code, while this below is the html code, please help me out on what I might be missing, thank you..
<form action="success.php" method="post">
<fieldset>
<!-- Form Name -->
<legend>Form Name</legend>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="fname">First Name </label>
<div class="col-md-4">
<input id="fname" name="fname" type="text" placeholder="" class="form-control input-md" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="lname">Last Name</label>
<div class="col-md-4">
<input id="lname" name="lname" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="age">Age</label>
<div class="col-md-4">
<input id="age" name="age" type="text" placeholder="" class="form-control input-md" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="sex">Sex</label>
<div class="col-md-4">
<input id="sex" name="sex" type="text" placeholder="" class="form-control input-md" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="address">Address</label>
<div class="col-md-4">
<input id="address" name="address" type="text" placeholder="" class="form-control input-md" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="city">City</label>
<div class="col-md-4">
<input id="city" name="city" type="text" placeholder="" class="form-control input-md" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="email">Email Address</label>
<div class="col-md-4">
<input id="email" name="email" type="text" placeholder="" class="form-control input-md" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="zip">Zip</label>
<div class="col-md-4">
<input id="zip" name="zip" type="text" placeholder="" class="form-control input-md" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="grade">Grade</label>
<div class="col-md-4">
<input id="grade" name="grade" type="text" placeholder="" class="form-control input-md" required="">
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit"></label>
<div class="col-md-4">
<button id="submit" name="submit" class="btn btn-primary">submit</button>
</div>
</div>
</fieldset>
</form>
Your POST data probably doesn't contain POST[submit'], try changing
if(isset($_POST['submit']))
to
if(isset($_POST))

Foreach loop inside for loop runs only once

I have got a foreach loop iterating over metalname array, which is nested inside a for loop, the foreach loop is coming from a seperate array, the issue is, during first iteration of for loop, the for each loop prints the values, but during next iteration of for loop, the foreach prints nothing.
whereas, for rest of the fields, there is no problem, they get printed on all iteratins.
$product = GetProduct();
$metal_name = get_metal();
$count = count($product);
<?php for($i=0;$i<$count;$i++) { ?>
<div class="form-group">
<label class="col-sm-2 control-label col-lg-2">Choose Metal</label>
<div class="col-lg-10">
<select class="form-control input-lg" name="metal_name[]">
<option value=''>Select Metal Name</option>
<?php
foreach ($metal_name as $r) { ?>
<option value="<?php echo $r['metal_id'];?>" <?php if($r['metal_id'] == $product[$i]['metal']){echo "selected='selected'";}?>><?php echo ucfirst($r['metal_name']);?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 col-sm-2 control-label">Product ID</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="product_id[]" value="<?php echo $product[$i]['id'];?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 col-sm-2 control-label">Charges Per Gram</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="gram_price[]" value="<?php echo $product[$i]['per_gram_price'];?>">
</div>
</div>
<?php } ?>
I found one thing on your forth line:
<?php for($i=0;$i<$count;$i++) { ?>
You didn't close out of PHP in your code above when you are getting your product and such. So this will give you some error.
In terms of your loop, a while loop is better for database work.
Here, I fixed it up for you. There were a few typos:
<?php
$product = GetProduct();
$metal_name = get_metal();
$count = count($product);
or($i=0;$i<$count;$i++) { ?>
<div class="form-group">
<label class="col-sm-2 control-label col-lg-2">Choose Metal</label>
<div class="col-lg-10">
<select class="form-control input-lg" name="metal_name[]">
<option value=''>Select Metal Name</option>
<?php
foreach ($metal_name as $r) {
?>
<option value="
<?php
echo $r['metal_id'];
if($r['metal_id'] == $product[$i]['metal']){
echo "selected='selected'";
echo ucfirst($r['metal_name']);
}
?>
</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 col-sm-2 control-label">Product ID</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="product_id[]" value="<?php echo $product[$i]['id'];?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 col-sm-2 control-label">Charges Per Gram</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="gram_price[]" value="<?php echo $product[$i]['per_gram_price']; ?>">
</div>
</div>
I fixed up your code a bit for you, try this out.

Unable to insert data into mysql but no error message shown

Was trying to make a student register page but the data won't insert into database and there was no error message shown so i'm not sure where the problem is. Any help is appreciated!
Here's the code:
<form onsubmit="return Add_Validate()" class="form-horizontal" action="AddStudent.php" method="POST">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title"><i class="fa fa-plus"></i> Add Student</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label class="col-sm-3 control-label">Student Name </label>
<label class="col-sm-1 control-label">: </label>
<div class="col-sm-8">
<input type="text" class="form-control" id="Add_Student_Name" placeholder="Student Name" name="Student_Name1" autocomplete="off" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Gender </label>
<label class="col-sm-1 control-label">: </label>
<div class="col-sm-8">
<select class="form-control" id="Add_Student_Gender" name="Student_Gender1" required>
<option value="">~~SELECT~~</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div></div>
<div class="form-group">
<label class="col-sm-3 control-label">Address </label>
<label class="col-sm-1 control-label">: </label>
<div class="col-sm-8">
<input type="text" class="form-control" id="Add_Student_Address" placeholder="Address" name="Student_Address1" autocomplete="off" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Contact Number </label>
<label class="col-sm-1 control-label">: </label>
<div class="col-sm-8">
<input type="text" class="form-control" id="Add_Contact_Number" placeholder="Contact Number" name="Contact_Number1" autocomplete="off" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Email </label>
<label class="col-sm-1 control-label">: </label>
<div class="col-sm-8">
<input type="text" class="form-control" id="Add_Student_Email" placeholder="Email" name="Student_Email1" autocomplete="off" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Faculty </label>
<label class="col-sm-1 control-label">: </label>
<div class="col-sm-8">
<select class="form-control" name="Add_Faculty1" id="FacultyName" required>
<option value="">~~SELECT~~</option>
<?php $query_faculty="SELECT FacultyName FROM `faculty`";
$result_faculty = mysqli_query($connect, $query_faculty) or die(mysqli_error($connect));
while($row_faculty=mysqli_fetch_array($result_faculty)) { ?>
<option value="<?php echo $row_faculty['FacultyName'] ?>"><?php echo $row_faculty['FacultyName'] ?></option>
<?php } ?></select></div></div>
<div class="form-group">
<label class="col-sm-3 control-label">Username </label>
<label class="col-sm-1 control-label">: </label>
<div class="col-sm-8">
<input type="text" class="form-control" id="Add_Student_Username" placeholder="Username" name="Student_Username1" autocomplete="off" required>
</div></div>
<div class="form-group">
<label class="col-sm-3 control-label">Password </label>
<label class="col-sm-1 control-label">: </label>
<div class="col-sm-8">
<input type="password" class="form-control" id="Add_Password" placeholder="Password" name="Student_Password1" autocomplete="off" required>
</div>
</div>
And SQL command:
<?php require 'php_action/db_connect.php';
if($_POST) {
$Student_Name= $_POST['Student_Name1'];
$Student_Gender= $_POST['Student_Gender1'];
$Student_Address= $_POST['Student_Address1'];
$Contact_Number= $_POST['Contact_Number1'];
$Student_Email= $_POST['Student_Email1'];
$FacultyName= $_POST['Add_Faculty1'];
$Student_Username= $_POST['Student_Username1'];
$Password= $_POST['Student_Password1'];
$sql = "INSERT INTO student (Student_Name,Student_Gender,Student_Address,Contact_Number,Student_Email,FacultyName,Student_Username,Password) VALUES ('$Student_Name', '$Student_Gender','$Student_Address','$Contact_Number','$Student_Email','$FacultyName','$Student_Username','$Password')";
if($connect->query($sql) === TRUE) {
echo "<SCRIPT>alert('Student successfully added!');document.location='Student_Register.php'</SCRIPT>";
}
else {
echo "<SCRIPT>alert('Student add unsuccessful!');document.location='Student_Register.php'</SCRIPT>";
}
}
$connect->close();
?>
Found the error, seems to be wrong column name, sorry the all the trouble.....
Admin please close my question.
You're not getting an error message because you never get the error message from MySQL and show it in your alert. $connect->error will contain the error message, and you can add that to your alert like this:
else {
echo "<SCRIPT>alert('Student add unsuccessful! Reason: ' + " . json_encode($connect->error) . ");document.location='Student_Register.php'</SCRIPT>";
}

Upload file and access $_FILES

I'm trying to upload a file on some directory. The directory is recorded in the database. However, the code cannot read $_FILES i get null value everytime i try to upload files,. but the other input data are recorded to the database,. what happen is I cannot record the name of the file in the database its just blank.
if(isset($_POST['btn-upload'])){
$record_title = $_POST['record_title'];
$record_recieved_date_time = $_POST['record_recieved_date_time'];
$record_checked_date_time = $_POST['record_checked_date_time'];
$record_approved_date_time = $_POST['record_approved_date_time'];
$record_status = $_POST['record_status'];
$record_remarks = $_POST['record_remarks'];
$record_type = $_POST['record_type'];
$file = $_FILES['file']['name'];
$sql = "INSERT INTO records (record_id , record_title , record_recieved_date_time , record_checked_date_time , record_approved_date_time , record_status ,record_remarks , file , record_type)
VALUES (NULL, '$record_title' , '$record_recieved_date_time','$record_checked_date_time','$record_approved_date_time' , '$record_status ' , '$record_remarks' , '$file' , '1')";
if (mysqli_query($dbconfig, $sql)) {
header('Location:memberAWP.php');
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($dbconfig);
}
}
here is the Form, im using modal with the help of bootstrap
<form method="post" action="" enctype="multipart/form-data name="loginform" class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="record_title"> TITLE </label>
<div class="col-sm-10">
<input type="text" class="form-control" id="record_title" name = "record_title" placeholder="Enter Title">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="record_recieved_date_time"> RECIEVED DATE / TIME </label>
<div class="col-sm-10">
<input type="datetime-local" class="form-control" id="record_recieved_date_time" name = "record_recieved_date_time" placeholder="Enter RECIEVED DATE / TIME">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="record_checked_date_time"> CHECKED DATE / TIME </label>
<div class="col-sm-10">
<input type="datetime-local" class="form-control" id="record_checked_date_time" name = "record_checked_date_time" placeholder="Enter CHECKED DATE / TIME">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="record_approved_date_time"> APPROVED DATE / TIME</label>
<div class="col-sm-10">
<input type="datetime-local" class="form-control" id="record_approved_date_time" name = "record_approved_date_time" placeholder="Enter APPROVED DATE / TIME">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="record_status"> STATUS </label>
<div class="col-sm-10">
<input type="text" class="form-control" id="record_status" name = "record_status" placeholder="Enter STATUS">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="record_remarks"> REMARKS </label>
<div class="col-sm-10">
<input type="text" class="form-control" id="record_remarks" name = "record_remarks" placeholder="Enter REMARKS">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="file"> ATTACHMENTS </label>
<div class="col-sm-10">
<input type="file" class="form-control" id="file" name="file" placeholder="Enter ATTACHMENTS">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" name="submit" value="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
if( isset( $_POST['btn-upload'], $_FILES['file'] ) ){
/*
The sql is vulnerable to sql injection as you directly embed variables within the sql
rather than using `prepared statements` so some extra care ought to be taken with the supplied
data, perhaps use:
filter_input( INPUT_POST, 'record_title', FILTER_SANITIZE_STRING );
*/
$record_title = $_POST['record_title'];
$record_recieved_date_time = $_POST['record_recieved_date_time'];
$record_checked_date_time = $_POST['record_checked_date_time'];
$record_approved_date_time = $_POST['record_approved_date_time'];
$record_status = $_POST['record_status'];
$record_remarks = $_POST['record_remarks'];
$record_type = $_POST['record_type'];
/*
Access the uploaded file as an object for simplicity
and use the values for saving the file etc
*/
$obj=(object)$_FILES['file'];
$file = $obj->name;
$size = $obj->size;
$tmp = $obj->tmp_name;
$type = $obj->type;
$error= $obj->error;
if( is_uploaded_file( $tmp ) && $error == UPLOAD_ERR_OK ){
/* determine the location the file should be saved to */
$destination = '/path/to/folder/' . $file;
/* Save the file */
$result = move_uploaded_file( $tmp, $destination );
/* Proceed with the sql command if the file was saved OK */
if( $result ){
$sql = "INSERT INTO records ( `record_title`, `record_recieved_date_time`, `record_checked_date_time`, `record_approved_date_time`, `record_status`, `record_remarks`, `file`, `record_type`)
VALUES ( '$record_title', '$record_recieved_date_time', '$record_checked_date_time', '$record_approved_date_time', '$record_status', '$record_remarks', '$file', '1' )";
$result = mysqli_query( $dbconfig, $sql );
if( $result )header('Location:memberAWP.php');
else echo "Error: " . $sql . "<br>" . mysqli_error($dbconfig);
}
}
}
As was pointed out in a comment, ensure that the form has the correct enctype attribute set - for file uploads it should be enctype='multipart/form-data'
Unless you use the move_uploaded_file() function the file will remain in the tmp directory for a limited time before garbage collection removes it and the reference to the file ( in the db ) will no longer be valid.
There are some basics thing you should know when working on file uploading.
1) You should define encryption type in your form for example
<form action="demo_post_enctype.asp" method="post" enctype="multipart/form-data">
2) Next you must use move_uploaded_file(source,destination) function in order to upload your file.
<form method="post" enctype="multipart/form-data" name="loginform" class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="record_title"> TITLE </label>
<div class="col-sm-10">
<input type="text" class="form-control" id="record_title" name = "record_title" placeholder="Enter Title">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="record_recieved_date_time"> RECIEVED DATE / TIME </label>
<div class="col-sm-10">
<input type="datetime-local" class="form-control" id="record_recieved_date_time" name = "record_recieved_date_time" placeholder="Enter RECIEVED DATE / TIME">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="record_checked_date_time"> CHECKED DATE / TIME </label>
<div class="col-sm-10">
<input type="datetime-local" class="form-control" id="record_checked_date_time" name = "record_checked_date_time" placeholder="Enter CHECKED DATE / TIME">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="record_approved_date_time"> APPROVED DATE / TIME</label>
<div class="col-sm-10">
<input type="datetime-local" class="form-control" id="record_approved_date_time" name = "record_approved_date_time" placeholder="Enter APPROVED DATE / TIME">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="record_status"> STATUS </label>
<div class="col-sm-10">
<input type="text" class="form-control" id="record_status" name = "record_status" placeholder="Enter STATUS">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="record_remarks"> REMARKS </label>
<div class="col-sm-10">
<input type="text" class="form-control" id="record_remarks" name = "record_remarks" placeholder="Enter REMARKS">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="file"> ATTACHMENTS </label>
<div class="col-sm-10">
<input type="file" class="form-control" id="file" name="file" placeholder="Enter ATTACHMENTS">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" name="btn-upload" value="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
change html code after try this code
if(isset($_POST['btn-upload']))
{
$record_title = $_POST['record_title'];
$record_recieved_date_time = $_POST['record_recieved_date_time'];
$record_checked_date_time = $_POST['record_checked_date_time'];
$record_approved_date_time = $_POST['record_approved_date_time'];
$record_status = $_POST['record_status'];
$record_remarks = $_POST['record_remarks'];
// $record_type = $_POST['record_type'];
$file = $_FILES['file']['name'];
//echo $fileName= $_FILES["file"]["name"];
echo $sql = "INSERT INTO records (record_id , record_title , record_recieved_date_time , record_checked_date_time , record_approved_date_time , record_status ,record_remarks , file , record_type)
VALUES (NULL, '$record_title' , '$record_recieved_date_time','$record_checked_date_time','$record_approved_date_time' , '$record_status ' , '$record_remarks' , '$file' , '1')";
if (mysqli_query($dbconfig, $sql)) {
header('Location:memberAWP.php');
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($dbconfig);
}
}
try this code
First of go to your project folder and create a new folder with the name of "uploads". the try the following code. if file upload get successfully done you can write your query in the IF block where we used echo for success. but first try this. i hope it works for you.
<?php
if(isset($_POST['submit'])){
$record_title = $_POST['record_title'];
$record_recieved_date_time = $_POST['record_recieved_date_time'];
$record_checked_date_time = $_POST['record_checked_date_time'];
$record_approved_date_time = $_POST['record_approved_date_time'];
$record_status = $_POST['record_status'];
$record_remarks = $_POST['record_remarks'];
$record_type = $_POST['record_type'];
$file = $_FILES['file']['name'];
$target_dir = "uploads/";
$path = $target_dir.$file;
$tmp = $_FILES['file']['tmp_name'];
if(move_uploaded_file($tmp,$path))
{
echo "File successfully uploaded";
}
else
echo "file did not upload";
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="post" action="" enctype="multipart/form-data" name="loginform" class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="record_title"> TITLE </label>
<div class="col-sm-10">
<input type="text" class="form-control" id="record_title" name = "record_title" placeholder="Enter Title">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="record_recieved_date_time"> RECIEVED DATE / TIME </label>
<div class="col-sm-10">
<input type="datetime-local" class="form-control" id="record_recieved_date_time" name = "record_recieved_date_time" placeholder="Enter RECIEVED DATE / TIME">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="record_checked_date_time"> CHECKED DATE / TIME </label>
<div class="col-sm-10">
<input type="datetime-local" class="form-control" id="record_checked_date_time" name = "record_checked_date_time" placeholder="Enter CHECKED DATE / TIME">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="record_approved_date_time"> APPROVED DATE / TIME</label>
<div class="col-sm-10">
<input type="datetime-local" class="form-control" id="record_approved_date_time" name = "record_approved_date_time" placeholder="Enter APPROVED DATE / TIME">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="record_status"> STATUS </label>
<div class="col-sm-10">
<input type="text" class="form-control" id="record_status" name = "record_status" placeholder="Enter STATUS">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="record_remarks"> REMARKS </label>
<div class="col-sm-10">
<input type="text" class="form-control" id="record_remarks" name = "record_remarks" placeholder="Enter REMARKS">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="file"> ATTACHMENTS </label>
<div class="col-sm-10">
<input type="file" class="form-control" id="file" name="file" placeholder="Enter ATTACHMENTS">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" name="submit" value="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</body>
</html>

Update Database tables with values input by user in CodeIgniter using PHP

I'm trying to update one of my user tables in the Database with values taken from the the user. But for some reason it's not updating anything.
HTML Form
<form class="form-horizontal" method = "post">
<fieldset>
<!-- Form Name -->
<legend>User Details</legend>
<div>
<?php echo $this->session->flashdata('msg'); ?>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="name">Full Name</label>
<div class="col-md-8">
<input id="name" name="name" type="text" placeholder="something" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="dob">Date of Birth</label>
<div class="col-md-4">
<input id="dob" name="dob" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Multiple Radios -->
<div class="form-group">
<label class="col-md-4 control-label" for="gender">Gender</label>
<div class="col-md-2">
<select id="gender" name="gender" class="form-control">
<option value="1">Male</option>
<option value="2">Female</option>
</select>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="degree">Degree</label>
<div class="col-md-8">
<input id="degree" name="degree" type="text" placeholder="degree" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="specialization">Specialization</label>
<div class="col-md-8">
<input id="specialization" name="specialization" type="text" placeholder="specialization" class="form-control input-md">
</div>
</div>
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="year">Degree Year</label>
<div class="col-md-2">
<select id="year" name="year" class="form-control">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
</div>
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="semester">Semester</label>
<div class="col-md-2">
<select id="semester" name="semester" class="form-control">
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
</div>
<!-- File Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="filebutton">Upload Profile Picture</label>
<div class="col-md-4">
<input id="filebutton" name="filebutton" class="input-file" type="file">
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit"></label>
<div class="col-md-4">
<a href="<?php echo base_url("/index.php/studentDashboardController/saveUserDetails"); ?>" >
<button id="submit" name="submit" class="btn btn-primary">Save Changes</button>
</a>
</div>
</div>
</fieldset>
studentDashboardController
public function saveUserDetails()
{
$this->load->model('userModel');
if (isset($this->session->userdata['logged_in']))
{
$username = ($this->session->userdata['logged_in']['username']);
}
$user = $this-> userModel-> getUserUid($username); //Gets the uid of the current user
$this->userModel->saveUserDetails($user);
$this->session->set_flashdata('msg', '<div class="alert alert-success text-center">Successfully Inserted Data</div>');
$this->load->view('studentDashboard/common',$data);
redirect(base_url('index.php/studentDashboard/editProfile',$data1));
}
userModel
public function saveUserDetails($uid)
{
$data = array(
'name' => $this->input->post('name')
);
$this->db->where("uid",$uid);
$this->db->update("sysuser",$data);
}
The sysuser has the uid and name fields.I' not sure what I'm doing wrong here. Any help in this regard will be appreciated
You dont send your post data to controller. Change $this->userModel->saveUserDetails($user); as
$this->userModel->saveUserDetails($user,$this->input->post('name'));
Now Model should be like
public function saveUserDetails($uid,$name)
{
$data = array(
'name' => $name
);
$this->db->where("uid",$uid);
$this->db->update("sysuser",$data);
}
and make sure you have set correctly form action like
<form class="form-horizontal" method="post" action="<?php echo site_url('studentDashboardController/saveUserDetails');?>">

Categories