I am working on a system and i want to check if a record exist. If a record exist then it will not record the data and instead will return to the form. If the data does not exist then it will proceed to recording the data to DB.
HTML form:
<form name="studentform" onSubmit="return validate_form ( );" action="queries/insert.php" method="post">
Student Number: <input type="text" name="studentnumber"/>
College:
<select name="college" id=a></select>
Course:
<select name="course" id=b></select>
<input type="radio" name="status" value="regular" />Regular
<input type="radio" name="status" value="irregular" />Irregular
<br><br>
<hr>
<br>
Name:
<input type="text" name="lname">
<input type="text" name="fname">
<input type="text" name="mname">
Address:
<input type="text" name="address" />
<br><br>
Gender:
<select name="gender">
<option value="">---</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<input type="submit" value="Submit">
</form>
PHP form:
$query = ("SELECT studentnumber FROM students where studentnumber = '$_POST[studentnumber]'");
$result=mysql_query($query);
if($result)
{
if(mysql_num_rows($result) >= 1)
{
echo "<script type='text/javascript'>alert('User already exist'); location.href = '../admin_home.php';</script>";
}
}
else{
$sql="INSERT INTO students (studentnumber, college, course, status, lname, fname, mname, address, gender)
VALUES
('$_POST[studentnumber]','$_POST[college]','$_POST[course]','$_POST[status]','$_POST[lname]','$_POST[fname]','$_POST[mname]','$_POST[address]','$_POST[gender]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "<script type='text/javascript'>alert('Record Successfully Added'); location.href = '../admin_home.php';</script>";
}
I don't know why but i always get the undefined index error. Maybe i've done something wrong somewhere. Thanks !!
"Undefined index" is referring to your array ($_POST, probably), and it should be a notice, not an error. Can you post the exact message?
In the meantime, switch your first line for
$query = "SELECT studentnumber FROM students where studentnumber = '".mysql_real_escape_string($_POST['studentnumber'])."'";
Also, it's helpful for debugging to print out the query to make sure it looks like you'd expect:
print $query."<br />"; // obviously
[edit]As you've now posted the error message, it becomes far more simple - $_POST['studentnumber'] does not exist. Check your form.
A good way to debug posted results is to use the code
print '<pre>';
print_r($_POST);
print '</pre>';
The problem is in your queries:
$query = ("SELECT studentnumber FROM students where studentnumber = '$_POST[studentnumber]'");
$_POST[studentnumber] is not correct. It needs to be $_POST['studentnumber']. Notice the quotes around the key.
I suggest doing it this way:
$query = sprintf("SELECT studentnumber FROM students where studentnumber = '%s'"
, mysql_real_escape_string($_POST['studentnumber']));
Change all your queries accordingly.
try with this:
if( isset($_POST['submit']) ){
$student_num = mysql_real_escape_string( $_POST['studentnumber'] );
// Set all the require form fields here with mysql_real_escape_string() fun
if( !empty($student_num) ){
// Your Query Here
}
else{
echo 'Value not Set in Student Number Field!';
}
}
Edit: first check all the fields after isset($_POST['submit']) so that you confirm about all the values are properly getting or not
after getting all the required values start your query
Related
I am getting Database query failed error while trying to insert a new row into a table. This table (pages) has a column (subject_id) referencing another table (subjects). I am passing the value of the of the subject_id from the url and it is passed on the form correctly. All the values seem to be passed correctly on the form using php, but i get error while i try to insert the row. The form submits to itself.
select_all_pages_by_subject($sid) is a function that selects all rows (pages) from the current subject (passed from the url). It works fine for the position field.
I suspect this error is probably a MySQL syntax error somewhere in my code, but i just cant seem to figure it out yet. I appreciate some help. Thank you.
Here is my code:
<div class="body_content">
<?php
$sid = null;
if(isset($_GET["subject"])) {
$sid = $_GET["subject"];
}
?>
<form action="create_page.php" method="post">
Menu Name: <input type="text" name="menu" /> <br>
Position: <select name="position">
<?php
$new_page_query = select_all_pages_by_subject($sid);
$page_count = mysqli_num_rows($new_page_query);
for($count=1; $count<=($page_count + 1); $count++) {
echo "<option value=\"$count\">$count</option>";
}
?>
</select> <br>
Visible:<br>
No <input type="radio" name="visible" value="0" />
Yes <input type="radio" name="visible" value="1" /> <br>
Subject ID: <input type="text" name="subject_id" value="<?php echo $sid; ?>" /> <br>
Content: <br>
<textarea rows="5" cols="40" name="content"></textarea> <br>
<input type="submit" value="Create Page" name="submit" /> <br>
Cancel <br>
</form>
<?php
if(isset($_POST['submit'])) {
$menu_name = $_POST["menu"];
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
$content = $_POST["content"];
$subject_id = (int) $_POST["$sid"];
$insert_query = "INSERT INTO pages (subject_id, menu_name, position,
visible, content) VALUES ({$subject_id},'{$menu_name}', {$position},
{$visible}, '{content}')";
$page_insert = mysqli_query($connection, $insert_query);
if($page_insert) {
$_SESSION["message"] = "Page created successfully";
redirect_to("admin.php");
} else {
$_SESSION["message"] = "Page creation failed";
redirect_to("create_page.php?subject=$sid");
}
}
?>
</div>
Edit: removed the WHERE statement
The problem is INSERT cannot have a WHERE after it.
$insert_query = "INSERT INTO pages (subject_id, menu_name, position, visible, content) VALUES ({$subject_id},'{$menu_name}', {$position}, {$visible}, '{content}')";
So after some troubleshooting, i decided to separate the form and form processing into 2 different pages, then i realized the problem, in the form action, i did not specify the subject id in the URL since i was passing the id from the URL:
<form action="create_page.php" method="post">
should be:
<form action="create_page.php?subject=<?php echo $sid; ?>" method="post">
Edit: I have also noticed that the "Database query failed" error was being called on the Position form field where i was making a database connection on the "pages" table to pull the number of rows. So when the insert statement failed due to the absence of subject id from the url, php did not process the page past the position form field, it called the error on the field and stopped execution. When insert query fails, parts of the form are displayed on the screen (only the menu name field and the position field with empty values). When i tried to view source code for errors, it requested the page be reloaded again (felt like an infinite loop running or something)
I have come across a problem when inserting values from a html select in to a mysql database. I can't seem to get the values to insert for some reason; I have looked for help on this but they keep giving me errors.
Also, can some please tell me what the difference between mysql and mysqli?
php code
<?php
$con = mysql_connect("localhost","barsne","bit me");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("testing", $con);
$sql="INSERT INTO client_details (id, f_name, l_name, phone, email, job_est) VALUES
('', '$_POST[f_name]', '$_POST[l_name]', '$_POST[phone]', '$_POST[email]', '$_POST[job_est]')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
echo "Thank you for booking a with us we will contact you in the next 24 hours to confirm your booking with a time and date";
mysql_close($con)
?>
html code
<form method="post" action="processing_booking.php">
<h4><u>Basic Contact Details</u></h4>
<label>First Name</label>
<input type="text" name="f_name">
<label>Last Name:</label>
<input type="text" name="l_name" id="l_name">
<label>Phone Number:</label>
<input type="text" name="phone" id="phone">
<label>Email:</label>
<input type="text" name="email" id="email">
<h4><u>Job Details</u></h4>
<label>You Would Like To Book A:</label>
<select name="job_est">
<option value="select">--SELECT--</options>
<option value="job">Job</option>
<option value="est">Estimation</option>
</select>
<label>Service Your Booking:</label>
<select name="job_type">
<option value="select">--SELECT--</option>
<option value="gardening">Gardening</option>
<option value="landscaping">Landscaping</option>
<option value="painting">Painting & Decorating</option>
<option value="decking">Decking & Fencing</option>
</select>
<label>Any Additional Information </label>
<textarea name="extra_info"></textarea>
<input type="submit" value="lets get your dreams started">
</form>
sorry wirting is not my strong point
Note that $_POST['name'] you missed single quotations
you must prevent from injection with
// String Type Fields
$name = strip_tags($_POST['name']);
$f_name= strip_tags($_POST['f_name']);
$l_name= strip_tags($_POST['l_name']);
$phone= strip_tags($_POST['phone']);
$email= strip_tags($_POST['email']);
// Int Type Fields
if (isset($_POST['job_est']) && is_numeric($_POST['job_est']))
$job_est= $_POST['job_est'];
else
$job_est= 0;
then use in your query
other point is
if your id field is primary and auto increment , you can define your query as below :
$sql="INSERT INTO client_details (f_name, l_name, phone, email, job_est) VALUES
( '".$f_name."', '".$l_name."', '".$phone."', '".$email."', ".$job_est.")";
for strings you must use '".$variable."'
and for integer or numeric you must use ".$variable."
other point is you must change your select element to below because you have noticed in your comments your job_est field type is int(11)
<select name="job_est">
<option value="0">--SELECT--</option>
<option value="1">Gardening</option>
<option value="2">Landscaping</option>
<option value="3">Painting & Decorating</option>
<option value="4">Decking & Fencing</option>
</select>
The mysql functions are deprecated. Use the mysqli or pdo class
instead.
mysqli: https://php.net/manual/en/class.mysqli.php
pdo: https://php.net/manual/en/book.pdo.php
Make a var_dump($_POST) and you will see what the problem is. By the way you missed the single quotes $_POST['value']
Never ever write $_POST or $_GET data directly in your sql queries. Always validate them before, because even the value of a selectbox can get easily changed with tampadata or chrome developer tools.
Well you can obviously start printing the results of your $_POST array with :
print_r($_POST,1);
to check all variables existence in it
this is going to be my second post, I am very confused and need some assistance. first I will explain what I would want it to do and then post my code. I am first search a database using first name, last name, or a date to print the results.
I first need help in only printing a repeating name once. It is printing every possible case and I would like it to match the fields (except arrival, reason, or even company (these can change ) )
Next once the results print on my search page, I would like radio buttons to be next to each set of data. for instance, if there are two people with the last name brown, i would like the first name, last name, and DL# to have ONE radio button next to it. resulting in two total buttons. this is where i am having trouble. once the selected radio is pressed and the next button (hyperlink) is pressed, i will then direct the user to a set of forms where the selected data ( firstname, lastname, dl#, company) is pre filled in the spots.
so all in all i need help limiting the prints of repeating individuals, and also i need assistance with saving data after a search function using a radio button to then print and pre populate the forms on the following page. my code currently for the search function is:
<h3>Search By First Name, Last Name, or Arrival Date (20XX-MO-DY)</h3>
<form action="searchpage.php" method="GET">
<label>Search:
<input type="text" name="searchname" id="searchname" />
</label>
<input type="submit" value="Search" />
</form>
My searchpage is :
<?php
$host = "localhost"; //server
$db = "practice_table"; //database name
$user = "root"; //databases user name
$pwd = ""; //password
mysql_connect($host, $user, $pwd) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());
$searchTerm = trim($_GET['searchname']);
// Check if $searchTerm is empty
if ($searchTerm == "") {
echo "Enter name you are searching for.";
exit();
} else {
$sql = "SELECT * FROM contractor WHERE CONCAT(FIRSTNAME,' ',LASTNAME,' ', ARRIVAL) like
'%$searchTerm%'";
$query = mysql_query($sql);
$count = mysql_num_rows($query);
if (($count) >= 1) {
$output = "";
while ($row = mysql_fetch_array($query)) {
$output .= "First Name: " . $row['FIRSTNAME'] . "<br />";
$output .= "Last Name: " . $row['LASTNAME'] . "<br />";
$output .= "Arrival: " . $row['ARRIVAL'] . "<br />";
}
echo $output;
} else {
echo "There was no matching record for the name " . $searchTerm;
}
}
?>
this code above is where all the results print and I would like to regulate the repeating cases, also where the radio button per individual should be.
finally this is the form page the hyperlink goes to where I would like to pre poppulate the code.
Welcome Back Contractor. Please fill the following information in again below for today's visit.
First Name:
<input type="text" name="FIRSTNAME" id="FIRSTNAME" value="<?php echo $_POST['radio']; ?>"/>
Last Name:
<input type="text" name="LASTNAME" id="LASTNAME" value="<?php echo $_POST['radio']; ?>"/>
<form action="insert_submit.php" method="post" style="margin-left:35px;">
First Name: <input type="text" name="FIRSTNAME" id="FIRSTNAME"/>
Last Name: <input type="text" name="LASTNAME" id="LASTNAME"/>
Purpose: <input type="text" name="PURPOSE" id="PURPOSE"/>
<br />
Company:
<input type="text" name="COMPANY" id="COMPANY"/>
DL #:
<input type="text" name="DRIVERL" id="DRIVERL"/>
<input type="radio" name="STATUS" id="STATUS" value="CHECKED IN">Log In
<br/>
<input type="radio" name="STATUS" id="STATUS" value="CHECKED OUT">Log Out
<br/>
<input type="submit" value="Submit">
<br/>
</form>
I appreciate any help. i hope I was just complicating things and can easily solve my last few issues. thank!
To remove duplicates from your results add DISTINCT or a GROUP BY clause to your SQL statment, eg:
SELECT DISTINCT FIRSTNAME, LASTNAME, PURPOSE FROM ...
or
SELECT DISTINCT FIRSTNAME, LASTNAME, PURPOSE
FROM ...
WHERE ...
GROUP BY DISTINCT FIRSTNAME, LASTNAME, PURPOSE
To add an arrival date while still only printing one row per person add MAX(ARRIVAL) to the SELECT clause:
SELECT DISTINCT FIRSTNAME, LASTNAME, PURPOSE, MAX(ARRIVAL)
FROM ...
WHERE ...
GROUP BY DISTINCT FIRSTNAME, LASTNAME, PURPOSE
I need advice, what i did wrong and this code not working. In short I have droplist menu with data read from mysql database and I want this data what user selected put in to another table/row in db. with present code I received only NULL value in inserted row... some I assume maybe something wrong with syntax, I tried search similar topic and tried different way but result is same :| This is my code :
get function and form
<br><br>
<?php
include 'connectdb.php';
$sql="select * from persons";
$result=mysqli_query($con,$sql);
while ($row=mysqli_fetch_array($result)) {
$id=$row["id"];
$name=$row["name"];
$name_done.="<OPTION VALUE=\"$id\">".$name;
}
?>
<form action="insert.php" method="post">
<SELECT name="name_done" id="nane_done">
<OPTION VALUE=0>Choose Your name :
<?=$name_done?>
</SELECT> <br>
RFC: <input type="text" name="number"><br>
Date: <input type="text" id="datepicker" name="date">
<input type="submit" value="submit" />
</form>
And Insert
<?php
include 'connectdb.php';
$name_done = $_POST['nane_done'];
mysqli_query($con,"INSERT INTO rfc(name_done) VALUES (.$name_done)");
---- below working OK----
$sql = "INSERT INTO rfc(number,date)
VALUES
('$_POST[number]','$_POST[date]')";
if (!mysqli_query($con,$sql,$name_done))
{
die('Error: ' . mysqli_error($con));
}
echo "RFC added";
mysqli_close($con);
?>
You have a typo - "nane_done" rather than "name_done" in this line: $name_done = $_POST['nane_done'];.
i'm new to php , i have been searching for a tutorial regarding inserting form's input(text) , radio and selection data to MySQL database's table using php. i found some tutorials but most are confusing. So i decided to ask.
Okay here's what i want to do. I have a form which have two types of input and a selection
1. input type text
2. input type radio
3. selection
Here's the HTML code :
<form action="" method="post" enctype="multipart/form-data">
<strong>Your Name: </strong><br>
<input type="text" name="myname" value="" />
<br /><br/>
<strong>Which class type you want:</strong><br>
<select name="selection">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<strong>Do you agree?</strong><br>
<input type="radio" name="agree" value="Yes"> or
<input type="radio" name="agree" value="No">
<input type="submit" name="submit" value="Submit">
</form>
I have set the form action to blank because the php code will be in the same file as the HTML (it's a php file btw)
MySQL table : info
structure :
1. name
2. class
3. agree
I want the php code to insert myname into name , selection's selected data into class , radio selected data into agree
P/S Yes i have added a connect to database php script , i just want to know how to get the form data into mysql.
Can someone write a php code example on how can i do this?
Thanks and have a nice day . I hope i have provided enough information. Thanks again if you help.
1. There is a problem with your radio element. The name should be the same for both options.
It should be like this:
<input type="radio" name="agree" value="Yes"> or
<input type="radio" name="agree" value="No">
2. You can access everything in the $_POST array, since you are using the method post for the form.
$name = $_POST['myname'];
$selection = $_POST['selection'];
$agree = $_POST['agree'];
3. If you are not using parametrized SQL with a library such as PDO, MySQLi, etc... you must always escape the data, which will be used in query using mysql_real_escape_string(), in order to protect against SQL injection.
This would be a sample code, to do the escaping and the query.
// write a function somewhere, to use as a shortcut
// for escaping data which will be used in a query
function sql_escape($str){
return "'".mysql_real_escape_string($str)."'";
}
// build the query
$query = sprintf('INSERT INTO table_name(name, class, agree) VALUES(%s, %s, %s)',
sql_escape($_POST['myname']),
sql_escape($_POST['selection']),
sql_escape($_POST['agree']));
// finally run it
$result = mysql_query($query);
I've taken it a little further here, there is still plenty more that can be done and many way's to do it, for instance you could extend the $errors array to include a field id and then highlight the HTML form field so the user can see exactly where they went wrong.
Considering your form is fairly simple you would not need this.
#Shef's code would certainly do the job but I thought you might be interested in some more.
<?php
// check the form has been submitted
if (isset($_POST['submit'])) {
// escape the form fields and assign them to variables
// validate myname to ensure the user entered data
if (isset($_POST['myname']) && $_POST['myname']!='') {
$myname = mysql_real_escape_string($_POST['myname']);
} else {
// create an error variable array to store errors to display
$errors[] = 'Please enter your name';
}
// no need to validate selection here as it alway's has a value
$classtype = mysql_real_escape_string($_POST['selection']);
// validate agree unless you want to add 'checked' to one of the values
if (isset($_POST['agree']) && $_POST['agree']!='') {
$agree = mysql_real_escape_string($_POST['agree']);
} else {
$errors[] = 'Please tell us if you agree?';
}
//if errors found tell the user else write and execute the query
if ($errors) {
$message = '<p class="error">We found a problem:</p><ul>';
foreach($error as $msg){
$message .= '<li>'.$msg.'</li>';
}
$message .= '</ul><p>Please fix the error/s to continue.</p>';
} else {
// write the query
$query = "INSERT INTO table (myname, classtype, agree) VALUES ";
$query .= "('$myname','$classtype','$agree')"
// run the query
mysql_query($query);
$message = '<p class="sucessful">Thanks '.htmlspecialchars($myname).'. Your selection has been saved.</p>';
}
}
// print the message
// show the variables in the form field so they don't need re-input
if ($message!='') { echo $message; }
?>
<form action="" method="post" enctype="multipart/form-data">
<strong>Your Name: </strong><br>
<input type="text" name="myname" value="<?php echo htmlspecialchars($myname) ?>" />
<br /><br/>
<strong>Which class type you want:</strong><br>
<select name="selection">
<option value="A"<?php if ($classtype=='A') { echo ' selected'; } ?>>A</option>
<option value="B"<?php if ($classtype=='B') { echo ' selected'; } ?>>B</option>
<option value="C"<?php if ($classtype=='C') { echo ' selected'; } ?>>C</option>
</select>
<strong>Do you agree?</strong><br>
<input type="radio" name="agree" value="Yes"<?php if ($agree=='Yes') { echo ' checked'; } ?>> or
<input type="radio" name="agree" value="No"<?php if ($agree=='No') { echo ' checked'; } ?>>
<input type="submit" name="submit" value="Submit">
</form>
Also: #sqwk, Don't point people towards w3schools, see this: http://w3fools.com/
Check whether there is any data in the $_POST array and get the values from it.
Have a look hereāthe second example down is what you need: http://www.w3schools.com/php/php_mysql_insert.asp
(You do have to make the changes that Shef suggested, though.)
Also remember to check your data-integrity, otherwise people could use your insert to run malicious code.
check this simple example:
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Sname: <input type="text" name="sname" />
<input type="submit" />
</form>
after you submit form, you can take name and sname.
welcome.php::
<?php
$name= $_POST["name"];
$sname= $_POST["sname"]; ?>
now you can use this variables as if you want.