I have seen few posts in SO related to the same scenario as mine but did not find a proper resolution. So am posting question with my problem stuff.
I have an HTML form
<form method="post" id="myForm">
<label for="e_name">Name</label>
<input name="e_name" id="emp_name" value="" type="text" data-theme="a">
<label for="date">Date</label>
<input name="date" id="emp_dob" value="" data-theme="a">
<label for="gender">Gender</label>
<select name="gender" id="emp_gender" data-role="slider" data-theme="a" data-inline="true">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<label for="address">Address</label>
<textarea name="address" id="emp_address" value="" type="text" data-theme="a"></textarea><br><br>
<input type="button" id="insert" value="Submit">
</form>
<div id="someElement"></div>
And I have the following to perform my form elements submission to a PHP page-
$(document).ready(function(){
$("#insert").click(function(e) {
e.preventDefault();
alert("am in the Insert function now");
$.ajax({
cache: false,
type: 'POST',
url: 'insert.php',
data: $("#myForm").serialize(),
success: function(d) {
$("#someElement").html(d);
}
});
});
});
Here is my PHP -
<?php
$con=mysqli_connect("localhost","root","root","employee");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name =" ";
$dob =" ";
$gender =" ";
$address =" ";
if(isset($_POST['emp_name'])){ $name = $_POST['emp_name']; }
if(isset($_POST['emp_dob'])){ $dob = $_POST['emp_dob']; }
if(isset($_POST['emp_gender'])){ $gender = $_POST['emp_gender']; }
if(isset($_POST['emp_address'])){ $address = $_POST['emp_address']; }
echo $name;
echo $dob;
echo $gender;
echo $address;
$sql="INSERT INTO emp_details (emp_name, emp_gender, emp_address) VALUES ('$name', '$gender', '$address')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Now what happens is, when I enter some values in my form and click on Submit, action performs well and a new row inserts in the database. But all the rows are empty. They're just empty, not even "NULL".
I tried to echo my field values in the PHP but there is no output there. My "1 Record Added" has come-up well, but no form values appear here.
Kindly help me sorting this out.
Thanks in advance.
$_POST[] references to the name attribute of html-tag, not id.
For example, $_POST['emp_name'] should be $_POST['e_name']
Furthermore, don't encapsulate your variables with single quotes:
"INSERT INTO emp_details (emp_name, emp_gender, emp_address) VALUES ('$name', '$gender', '$address')";
Do this instead:
"INSERT INTO emp_details (emp_name, emp_gender, emp_address) VALUES ('" . $name . "', '" . $gender . "', '" . $address . "')";
Or use bind_param() from mysqli ofcourse!
Make the id and name of your input elements same
<form method="post" id="myForm">
<label for="e_name">Name</label>
<input name="emp_name" id="emp_name" value="" type="text" data-theme="a">
<label for="date">Date</label>
<input name="emp_dob" id="emp_dob" value="" data-theme="a">
<label for="gender">Gender</label>
<select name="emp_gender" id="emp_gender" data-role="slider" data-theme="a" data-inline="true">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<label for="address">Address</label>
<textarea name="emp_address" id="emp_address" value="" type="text" data-theme="a"></textarea><br><br>
<input type="button" id="insert" value="Submit">
</form>
Otherwise change your $_POST array keys.Because you will get the keys of $_POST array will be the name of input elements.But i recommend you to mak ethe name and id same
Related
Been trying to get this PHP to send to my database but for some reason it won't work but it isn't giving me any errors either. The code probably isn't the prettiest only been working on PHP for 6 months so any help is much appreciated.
<form method="POST">
<div class="form-group">
<label for="exampleFormControlSelect1">Send Message to: </label>
<select class="form-control" id="slectrecipient" name="recipient">
<?php
include("conn.php");
$info = "SELECT FirstName, SecondName, id FROM PT_accounts WHERE NOT id='$accountid'";
$result4 = $conn->query($info);
if(!$result4){
echo $conn->error;
}
while($row4 = $result4->fetch_assoc()){
$recipientfirst = $row4['FirstName'];
$recipientsecond = $row4['SecondName'];
$recipientid = $row4['id'];
echo "<option value='$recipientid'> $recipientfirst $recipientsecond</option>";
}
if(isset($_POST['messagetext'])){
$currentdate = date("Y-m-d H:i:s");
$messagetext = $_POST['messagetext'];
$recipid = $_POST['recipient'];
echo $currentdate;
echo $messagetext;
echo $recipid;
$messageinsert = "INSERT INTO PT_Messages (SenderID, RecipientID, Date, Message)
VALUES ('$accountid', '$recipid', '$currentdate', '$messagetext') ";
$result5 = $conn->query($messageinsert);
if(!$result5){
echo $conn->error;
}else{
echo "<p> $messageinsert</p>";
echo "<p>Message Sent!</p>";
}
}
?>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Message :</label>
<text class="form-control" id="messagetext" rows="3"></textarea>
</div>
<input type="submit" class="btn btn-primary btn-sm" value="Send">
</form>
I know there's two $row and $results but I've altered these in my actual to be different so I know that's not the issue. I'm unsure if it's the select tag with the option value that isn't written correctly. Or if I have to somehow set the dropdown menu selection as a PHP variable to then be sent to the database?
Thanks to user3783243
I didn't name the textarea but had set it as an id.
<input type="text" class="form-control" name="messagetext" id="messageid" rows="3">
I had it as id="messagetext"
I have a problem, to build INSERT PHP file with HTML form code. When I drop from HTML form, then this error pops out ""invalid input syntax for integer: "" LINE 2:""
in all code, I comment every single line and nothing.
There is my PHP script
`
$order_nr = pg_escape_string($_POST['order_nr']);
$date = pg_escape_string($_POST['date']);
$place = pg_escape_string($_POST['place']);
$service = pg_escape_string($_POST['service']);
$Vards = pg_escape_string($_POST['vards']);
$Uzvards = pg_escape_string($_POST['uzvards']);
$phone = pg_escape_string($_POST['phone']);
$email = pg_escape_string($_POST['email']);
$veids = pg_escape_string($_POST['veids']);
$passw = pg_escape_string($_POST['passw']);
$papildaprikojums = pg_escape_string($_POST['papildaprikojums']);
$save_info = pg_escape_string($_POST['save_info']);
$defekts = pg_escape_string($_POST['defekts']);
$query = " INSERT INTO serviss (order_nr, place, service, vards, uzvards, email, veids, passw, save_info, papildaprikojums, defekts)
VALUES ('$order_id', '$place', '$service', '$vards', '$uzvards', '$email', '$veids', '$passw', '$papildaprikojums', '$save_info', '$defekts') " ;
$result = pg_query($query);
if (!$result) {
$errormessage = pg_last_error();
echo "Error with query: " . $errormessage;
exit();
}
printf ("These values were inserted into the database - %s %s %s", $order_id);
pg_close();
There is my HTML form code
<form action="serviss.php" method="post" >
<div class="ievade">
Pasūtijuma numurs : <input type="text" size="5" name="order_id"> <br><br>
Pieņemšanas datums : <input type="date" data-date="" data-date-format="DD MMMM YYYY" value="2015-08-09" name="date"> <br><br>
Pieņemšanas vieta : <select name="place">
<option value="Ausekļa_iela_9"> Ausekļa iela 9 </option>
</select> <br><br>
Pieņēma : <select >
<option value="service" name="Maris"> Māris </option>
<option value="service name="Toms"> Toms </option>
</select> <br> <br>
Klienta vārds : <input type="text" name="vards" size="5"> <br><br>
Klienta uzvārds : <input type="text" name="uzvards" size="5"> <br><br>
Klienta tel.nr.: <input type="tel" id="phone" size="6"> <br><br>
Klienta e-pasts: <input type="text" value="example#test.net" name="email">
<br><br>
Iekārtas veids: <input type="text" value="iekārta" name="veids" size="5"> <br><br>
Parole: <input type="text" name="passw" size="5"> <br><br>
</div>
<div class="checkbox">
Garantija: <br>
Ir
<input type="radio" name="garantija" value="Ir"> <br>
Nav <input type="radio" name="garantija" value="Nav">
<br> <br>
</div>
<div class="ievade">
Papildaprīkojums: <input type="text" name="papildaprikojums" > <br><br>
Papildus informācija: <input type="text" name="informacija">
<br> <br>
Saglabājamā informācija: <input type="text" name="save_info">
<br> <br>
Defekta apraksts: <input type="text" name="defekts">
</div>
</div>
<input type="submit" value="Submit">
</form>
I hope you can help me.
I use PostgreSQL 10.10
It's like you have mixed up the 'order_id' with 'order_nr'.
The name value attribute is 'order_id' so when you try to get it it is
$_POST['order_id'] not `$_POST['order_nr']`
It means that either you should say
$order_nr = pg_escape_string($_POST['order_id']);
In order to use the variable into the insert statement and then
$query = " INSERT INTO serviss (order_nr, place, service, vards, uzvards, email, veids, passw, save_info, papildaprikojums, defekts)
VALUES ('$order_nr', '$place', '$service', '$vards', '$uzvards', '$email', '$veids', '$passw', '$papildaprikojums', '$save_info', '$defekts') " ;
or you shoud say
$order_id = pg_escape_string($_POST['order_id']);
And then
$query = " INSERT INTO serviss (order_nr, place, service, vards, uzvards, email, veids, passw, save_info, papildaprikojums, defekts)
VALUES ('$order_id', '$place', '$service', '$vards', '$uzvards', '$email', '$veids', '$passw', '$papildaprikojums', '$save_info', '$defekts') " ;
In the form below, students are selected from student table in my DB. For each student selected a checkbox is checked if the student is absent and left unchecked if the student is present. The form is later on submitted for it to be inserted in the exam_status table in my DB.
<form method="POST" action="action.php">
<?php
$query = "SELECT * from student ORDER BY student_name,student_surname";
$result=mysqli_query($conn,$query);
if(false===$result)
{
printf("error: %s \n",mysqli_error($conn));
}
while($row= $result->fetch_assoc())
{
$studentmatricule = $row['student_matricule'];
$studentname = $row['student_name'];
$studentsurname = $row['student_surname'];
?>
<div id="studentdiv">
<label>Matricule</label>
<input type="text" name="matricule[]" value="<?php echo "$studentmatricule)"; ?>" readonly>
<label>Name</label>
<input type="text" name="name[]" value="<?php echo "{$studentname} {$studentsurname}"; ?>" readonly>
<label > Absent
<input type="checkbox" name="absent[]" value="absent" />
</label>
</div> <br><br>
<?php
}
?>
<input type="submit" name="submit" value="submit">
</form>
and my action page "action.php" is as follows
$matricule = $_POST['matricule'];
$absent=$_POST['absent'];
for ($i=0; $i<sizeof($matricule); $i++)
{
if($absent[$i]=='absent')
{
$status='absent';
}else{
$status='present';
}
$query = "INSERT INTO exam_status (student_matricule,status) VALUES ('". $matricule[$i] . "','". $status . "')";
$result=mysqli_query($conn,$query);
}
Now the issue is it doesn't just work as i want. the result always gives the first student absent and the rest present. I have tried all i can and have really researched too but with no success at all. Please anyone around to help me out?
Thanks in advance!
<form method="POST" action="action.php">
<?php
$query = "SELECT * from student ORDER BY student_name,student_surname";
$result=mysqli_query($conn,$query);
if(false===$result)
{
printf("error: %s \n",mysqli_error($conn));
}
$index = 0;
while($row= $result->fetch_assoc())
{
$index++;
$studentmatricule = $row['student_matricule'];
$studentname = $row['student_name'];
$studentsurname = $row['student_surname'];
?>
<div id="studentdiv">
<label>Matricule</label>
<input type="text" name="studenInfo[<?php echo $index; ?>][matriculate]" value="<?php echo $studentmatricule; ?>" readonly>
<label>Name</label>
<input type="text" name="studenInfo[<?php echo $index; ?>][name]" value="<?php echo $studentname." ".$studentsurname; ?>" readonly>
<label > Absent
<input type="checkbox" name="studenInfo[<?php echo $index; ?>][status]" value="absent" />
</label>
</div> <br><br>
<?php
}
?>
<input type="submit" name="submit" value="submit">
Update your mail file like this. I have changed the form names into a single array. The reason is the checkbox values won't post to the page when the values are not checked. So its not possible to track which one was checked and which is not if you have same name.
And update your action.php like this,
<?php
$conn = mysqli_connect("localhost","username","password","db_name"); // update this values as per your configuration
$studenInfo = (!empty($_POST['studenInfo'])) ? $_POST['studenInfo'] : [];
foreach($studenInfo as $value ) {
$status = (isset($value['status'])) ? 'absent' : 'present';
$query = "INSERT INTO exam_status (student_name, student_matricule,status) VALUES ('". $value['name'] . "','". $value['matriculate'] . "','". $status . "')";
$result=mysqli_query($conn,$query);
}
?>
I have used my own table schema where i have added student_name in exam_status table for better tracking. Now you can see the values updating correctly. Also we can use bulk insert if we need to insert multiple data (Note : I haved used the bulk insert in this answer, i just followed the way you used)
i am trying to send some information to insert-event.php. Every piece of data comes through, except the options listed in my SELECT.
<form action="php/insert-event.php" method="post">
<select id="skoleDropdown" name="skole"><option hidden>Velg skole</option>"' . $skoleAttributter . '" </select>
<input type="text" name="Title" placeholder="Tittel" class="ico-title" required></input>
<input type="text" name="description" placeholder="Beskrivelse" class="ico-title" required></input>
<input type="text" name="pris" placeholder="Pris i NOK" class="ico-title" required></input>
<input type="date" name="date" class="ico-title" required></input>
<input type="text" name="img_url" placeholder="Bildelenke" class="ico-title" required></input>
<input type="text" name="type" placeholder="Type arrangement" class="ico-title" required></input>
<input type="submit" name="submit" value="LEGG TIL"></input>
</form>
</div>';
And then i have my insert-event.php:
<?php
$title = $_POST['Title'];
$pris = $_POST['pris'];
$date = $_POST['date'];
$url = $_POST['img_url'];
$description = $_POST['description'];
$school = $_POST['skole'];
$schoolId = '';
$type = $_POST['type'];
switch($school) {
case 'Campus Brennerviveien';
$schoolId == 1;
break;
case 'Campus Vulkan';
$schoolId == 2;
break;
case 'Campus Fjerdingen';
$schoolId == 3;
break;
}
// Connect and select DB
$connect = mysqli_connect('localhost', 'chris', 'chris');
if (!$connect) {
echo 'Not connected';
}
if (!mysqli_select_db($connect, 'eksamen')) {
echo 'Database not selected';
}
// Submit
$sql = "INSERT INTO events (id, title, description, pris, img_url, date, type, skole_id)
VALUES (NULL, '$title', '$description', '$pris', '$url', '$date', '$type', '$schoolId')";
if ($connect->query($sql) === TRUE) {
header("Location:../index.php");
exit;
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
$connect->close();
?>
I think maybe this speaks for itself.
Appreciate help.
Thanks!
proper method of select is
<select name="skole" id="skole">
<option value="test"> option one text here </option>
<option value="test2"> option two text here </option>
</select>
when your request to select like
$school = $_POST['skole']; ====> $school = 'test'
when select have selected then it will gives you the value of option other it can not give any value.
thanks
you have to use value attribute for select tag to send data on post page
<select id="skoleDropdown" name="skole">
<option hidden value="Velg skole">Velg skole</option>"' . $skoleAttributter . '"
</select>
then this should be like
<form action="php/insert-event.php" method="post">
<select id="skoleDropdown" name="skole"><option hidden value="Velg skole">Velg skole</option>"' . $skoleAttributter . '" </select>
<input type="text" name="Title" placeholder="Tittel" class="ico-title" required></input>
<input type="text" name="description" placeholder="Beskrivelse" class="ico-title" required></input>
<input type="text" name="pris" placeholder="Pris i NOK" class="ico-title" required></input>
<input type="date" name="date" class="ico-title" required></input>
<input type="text" name="img_url" placeholder="Bildelenke" class="ico-title" required></input>
<input type="text" name="type" placeholder="Type arrangement" class="ico-title" required></input>
<input type="submit" name="submit" value="LEGG TIL"></input>
</form>
</div>';
And then this will be like this
$skoleListe = Skole::all();
$skoleAttributter = '';
foreach($skoleListe as $skole)
{
$skoleAttributter.= '<option value="' .$skole['id'] . '">' . $skole['navn'] . '</option>';
}
you have added "" this double time remove one from option value attibute
Extra double quotes problem so values is setting empty
$skoleAttributter.= '<option value=""' .$skole['id'] . '">' . $skole['navn'] . '</option>';
^^^
change to
$skoleAttributter.= '<option value="' .$skole['id'] . '">' . $skole['navn'] . '</option>';
^^^^
1) And no need switch case because your setting id as a value attribute . so you can directly use it as schoolId
Try to use prepared statement or pdo to avoid sql injection .
hi i am having a contact form in my website where user can optionaly fill some of the fields and after click on submit button data save in to the database all of this worked fine until i decide to sanitize my code from sql injection as i mentioned at first before trying to sanitize it from sql injection it worked properly as i showed in below code
<form method="Post" action="">
<input type="text" name="name" />name
<select dir="rtl" style="width: 173px;" name="case" >
<option value="" disabled selected hidden>اplease choose</option>
<option value='rent'>rent</option>
<option value='sell'>sell</option>
</select >
<input type="checkbox" name="check1" value='a'>apartment<br>
<input type="submit" value="submit" />
</form>
<?php
include("config.php");
if(isset($_POST['submit'])){
$date_clicked = date('Y-m-d H:i:s');
}
//insert to database
$insert =mysqli_query($connect,"INSERT INTO $db_table VALUES (to simplify code i do not write this part)");
}
?>
now i have to fill all the dropdown lists and checkboxes otherwise it gives error "column '' can not be null". also i can not insert date and time into database it gives the same error. here is my code when i protect it fron sql injection:
<form method="Post" action="">
<input type="text" name="name" />name
<select dir="rtl" style="width: 173px;" name="case" >
<option value="" disabled selected hidden>اplease choose</option>
<option value='rent'>rent</option>
<option value='sell'>sell</option>
</select >
<input type="checkbox" name="check1" value='a'>apartment<br>
<input type="submit" value="submit" />
</form>
<?php
include("config.php");
if(isset($_POST['submit'])){
$date_clicked = date('Y-m-d H:i:s');
}
if(isset($_POST['submit'])){
//insert to database
$query = mysqli_prepare($connect, "INSERT INTO $db_table VALUES (?,?,?,?)");
/* bind parameters for markers */
mysqli_stmt_bind_param( $query, "ssss", $_POST[name],$_POST['check1'],$_POST['case'],$_POST['date_clicked']);
// execute query
if ( mysqli_stmt_execute($query) ) {
echo "Successfully inserted " . mysqli_affected_rows($connect) . " row";
} else {
echo "Error occurred: " . mysqli_error($connect);
}
}
?>
please help me
Make sure that your variables exist. This is necessary because your checkbox, for example, will be null if not checked and that could be a problem for the table you are using. You could set defaults and then insert it.
$name = !empty($_POST['name']) ? $_POST['name'] : '';
$check1 = !empty($_POST['check1']) ? $_POST['check1'] : '';
$case = !empty($_POST['case']) ? $_POST['case'] : '';
$date_clicked = date('Y-m-d H:i:s');
// prepare and bind
$stmt = $connect->prepare("INSERT INTO `$db_table` (`name`, `check1`, `case`, `date_clicked`) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $name, $check1, $case, $date_clicked);
$stmt->execute();
$stmt->close();