I'm trying to validate my select tag so that if the user has not selected a session an alert will appear when the submit button is pressed. I have my html and php code below, thanks
<select name="ses">
<option> Select a Session </option>
<?php
$get_sess = "select * from sessions where course_id='1'";
$run_sess = mysqli_query($con, $get_sess);
while ($sess_row=mysqli_fetch_array($run_sess)){
$ses_id=$sess_row['session_id'];
$ses_title=$sess_row['session_title'];
echo "<option value='$ses_id'>$ses_title</option>";
} ?>
</select>
my php code is:
<?php
//if submit button is set i.e 'publish exercise now' pressed then:
if(isset($_POST['submit1'])){
$exercises_ses = $_POST['ses'];
$exercise_text = $_POST['exercise_text'];
if($_POST['ses'] == 'NULL'){
echo "<script>alert('Please select a session for the exercise')</script>";
}
}
You should just use the empty function. This will check that the value isn't "empty", check the manual for everything that qualifies as "empty", per comments I think this meets your criteria.
if(isset($_POST['submit1'])){
$exercises_ses = $_POST['ses'];
$exercise_text = $_POST['exercise_text'];
if(empty($_POST['ses'])){
echo "<script>alert('Please select a session for the exercise')</script>";
} else {
// execute functions form value is correct
}
}
'NULL' is a string, if you want to compare to null value - use NULL.
I don't think that $ses_id in your db has value 'NULL'.
Checking if value is set can be done with isset, and with empty for not empty:
if (isset($_POST['ses']) && !empty($_POST['ses'])) {
Related
for example i have
i have two table in my datbase 1st is list1 and 2nd is list2
<select>
<option name='select' value="0">Select</option>
<option value="list1">List1</option>
<option value="List2">List2</option>
</select>
suppose user in drop down option chose list 1 then data insert in list1 option
if user select list2 then data insert in to list2 how to do this please help me to fix this issue
thanks
mysql_query("INSERT list1 SET title='$titile', subject='$subject'")
and here is complete code
<?php
}
//connect to database
mysql_connect('localhost','root','');
mysql_select_db('pdsd');
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$title = mysql_real_escape_string(htmlspecialchars($_POST['title']));
$subject = mysql_real_escape_string(htmlspecialchars($_POST['subject']));
// check to make sure both fields are entered
if ($title == '' || $subject == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($title, $subject,$date, $error);
}
else
{
// save the data to the database
$tables = array('list1', 'list2');
if (in_array($_POST['select'], $tables)) {
mysql_query("INSERT {$_POST['select']} SET title='$title',subject='$subject'");
}
or die(mysql_error());
echo "<center>Succesfully add</center>";
echo "<script>setTimeout(\"location.href = 'login.php';\",1500);</script>";
// once saved, redirect back to the view page
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','','','','','','','','','','','','','','','','','','');
}
?>
As I stated in comments, use a conditional statement and 2 separate queries based on the conditional statement and what the choice equals to the value chosen.
For example and assuming you are using as pure PHP and using a form:
Sidenote: You will need use your own queries here, as seen in commented // query for LIST X.
Another sidenote: The name attribute belongs to <select> and not <option>.
Last sidenote: My omission of action="" is equal to "self". So, you can add action="handler.php" to it if you wish to use separate files.
<form method="post">
<select name="select">
<option value="0">Select</option>
<option value="list1">List1</option>
<option value="list2">List2</option>
</select>
<input type = "submit" name = "submit" value = "Submit">
</form>
<?php
if(isset($_POST['submit'])){
if(isset($_POST['select']) && $_POST['select'] == 'list1'){
// query for LIST 1
}
if(isset($_POST['select']) && $_POST['select'] == 'list2'){
// query for LIST 2
}
if(isset($_POST['select']) && $_POST['select'] == '0'){
// Do nothing
}
}
This is but an example and the use of a prepared statement should be taken into account.
https://en.wikipedia.org/wiki/Prepared_statement
Other references you should read related to MySQL:
http://dev.mysql.com/doc/en/insert.html
http://dev.mysql.com/doc/en/update.html
Edit:
You can also use a switch/case statement:
if(isset($_POST['submit'])){
switch($_POST['select']) {
case 'list1':
// query for LIST 1
break;
case 'list2':
// query for LIST 2
break;
case '0':
// Do nothing
break;
}
}
You should first verify that the input is valid, then you can just substitute it into the SQL.
$tables = array('list1', 'list2');
if (in_array($_POST['select'], $tables)) {
mysql_query("INSERT INTO {$_POST['select']} SET title='$titile', subject='$subject'") or die(mysql_error());
}
Make sure you're properly escaping the variables $titile and $subject if they derive from user input, to protect against SQL-inject (use mysql_real_escape_string()). It would be even better if you used MySQLI or PDO so you could use a prepared statement instead of substituting variables into the query.
I have a single checkbox in a form which I want to assign values to for both checked and unchecked states.
The values are saved in a MySQL database. This is my php to retrieve the values.
<?php
// Value = 10.00
// This should be the checked value (initial state)
function getDel1()
{
global $con;
$get_del1 = "select * from delivery";
$run_del1 = mysqli_query($con, $get_del1);
while($row_del1=mysqli_fetch_array($run_del1)){
$leeds = $row_del1['delivery_leeds'];
echo "$leeds";
}
}
?>
<?php
// Value = 20.00
// This should be the unchecked value (user interaction)
function getDel2()
{
global $con;
$get_del2 = "select * from delivery";
$run_del2 = mysqli_query($con, $get_del2);
while($row_del2=mysqli_fetch_array($run_del2)){
$leeds = $row_del2['delivery_other'];
echo "$other";
}
}
?>
I can display the values independently by calling either function in a div which is adjacent to the form checkbox but I don't know how to assign those values to the form checkbox and then automatically update the div depending on the user interaction. Any suggestions?
A ternary operator can take care of both assigned values and unassigned default values.
Example:
$checkbox = isset($_POST['checkbox']) ? $_POST['checkbox'] : "Default value if unchecked";
This is equivalent to doing: (which you can also use).
if (isset($_POST['checkbox'])){
$checkbox=$_POST['checkbox'];
// do something, as in run a function
}
else{
$checkbox="Default value if unchecked";
// do something else, as in run a different function
}
You can also remove the default text and do "" in the ternary to leave it empty.
Reference:
http://php.net/manual/en/language.operators.comparison.php
Footnotes:
Make sure the checkbox holds the name attribute.
I.e. name="checkbox" as an example.
and your form has a POST method. Use the appropriate method accordingly.
So in your case and as seen in comments from code you left there, change checkbox in the arrays to deliver.
Your checkbox value can also use the following, as a ternary example:
<input type="checkbox" name="deliver" value="<?php echo isset($_POST['deliver']) ? $_POST['deliver'] : "Default value if unchecked"; ?>" />
Following is select option to retrieve the data from mysql db in php. On selecting the dropdown, I need to insert option value to mysql db.
<select device_id='device_id'>;
<?php
require_once('sqlcon.php');
$drop=mysql_query("select * from device");
while($row = mysql_fetch_array($drop)){
echo "<option value='" .$row['device_id']. "'>" . $row['device_id']. "</option>";
}
?>
</select>
I am using the following in add.php . Error is showing only in this line.
$device_id=$_POST['device_id'];
Also check that the device_id is set or not.
isset() function in PHP determines whether a variable is set and is not NULL. It returns a Boolean value, that is, if the variable is set it will return true and if the variable value is null it will return false.
if(isset($_POST['device_id'])){ $device_id = $_POST['device_id']; }
your error says it all,your select box does not have a "name" attribute, you need to give it one..
<select name='device_id'>
undefined index: device_id in C:\...\ in add.php on line 55
It tells what is wrong, $_POST['device_id'] (Index = device_id) is not setted. Make sure you have <select name='device_id'>...</select>
name='device_id' = $_POST['device_id']
Use attribute onchange="document.forms[0].submit()" to submit the form on selected option.
Add hidden field in form.
<input type="hidden" name="action" value="submit" />
Get device_id
if(isset($_POST["action"])) {
echo $_POST['device_id'];
}
I have 2 drop-down lists with different names, and I'm trying to query in just one field.
I'm using a jQuery function wherein if item 1 is selected, the drop-down list 1 will be displayed, and if the item 2 is selected, the drop-down list 2 will be displayed.
This is how I populated my drop-down list from the mysql database and tables:
<div id="minquep">
<label>Branch</label>
<SELECT name="user_min">
<OPTION VALUE="0">Choose a branch
<?=$minq_options?>
</SELECT>
</div>
<div id="albury">
<label>Branch</label>
<SELECT name="user_branch">
<OPTION VALUE="0">Choose a branch
<?=$al_options?>
</SELECT>
And this is how I insert queries into mysql by filling out the form with drop-down lists in it:
if (isset($_REQUEST['Submit'])) {
$sql = "INSERT INTO $db_table(branch) values ('".mysql_real_escape_string(stripslashes($_REQUEST['user_branch'])).",".mysql_real_escape_string(stripslashes($_REQUEST['user_min']))."')";
if($_REQUEST['user_branch']= ""){
($_REQUEST['user_branch']) = NULL;
}
if($result = mysql_query($sql ,$db)) {
echo '<script type="text/javascript">alert("The user has been added successfully!\n");return true;</script>';
echo "<meta http-equiv=\"refresh\" content=\"0;URL=add_user.php\">";
}
else {
echo "ERROR: ".mysql_error();
}
}
The testing scenario is that, I choose the value under <select name="user_min">.
So I assume that sql will just bypass the result for user_branch because it is null. But it does prints '0' instead, after the insert query. For example, if the inserted ($_REQUEST['user_min']) value is "Brisbane" and the ($_REQUEST['user_branch']) value is null (because I didn't selected any value under the user_branch drop-down list), the branch field should just become "Brisbane", knowing that user_branch is NULL. But it does print "BRISBANE" with 0, like 0, Brisbane in my mysql table.
How can I fix this?
I already tried putting an if condition, it did not work.
if($_REQUEST['user_branch']= ""){
($_REQUEST['user_branch']) = NULL;
}
I've also tried changing the user_min into same name user_branch, but it does not get the selected value, instead of Brisbane it just prints '0'
A few things -
you are setting user_branch = NULL after the $sql.
You are using quotes around value. It's fine non-Null values -you need to check if there is NULL value then don't use quotes in your $sql.
You are using single "=" in your IF statement. This is failing your If statement. Change it to if($var == '')
Update
Some suggestions based on your existing code - however there are other best practices to achieve what you are trying to achieve....
$user_branch = $_REQUEST['user_branch'];
$user_min = $_REQUEST['user_min'];
//you should validate above values first
if$user_branch == "" || $user_min == "") {
$db_value = "NULL";
} else
{
$db_value = "'".mysql_real_escape_string(stripslashes($user_branch.','.$user_min))."'";
}
$sql = "INSERT INTO $db_table(branch) values (".$db_value.")";
If you don't want 0, then change:
<option value="0">Chose a Branch</option>
To:
<option value="">Chose a Branch</option>
Otherwise it will get passed through the form as 0
Also, your PHP code won't work as you want it to:
if (isset($_REQUEST['Submit'])) {
// do this before the query
if($_REQUEST['user_branch']== ""){ // note the extra = in there, so you aren't assigning the variable, you are compairing
$_REQUEST['user_branch'] = NULL; // no need for brackets round the variable
}
$sql = "INSERT INTO $db_table(branch) values (".mysql_real_escape_string(stripslashes($_REQUEST['user_branch'])).",".mysql_real_escape_string(stripslashes($_REQUEST['user_min'])).")"; // you had single quotes around everything inside the VALUES() function
if($result = mysql_query($sql ,$db)) {
echo '<script type="text/javascript">alert("The user has been added successfully!\n");return true;</script>';
echo "<meta http-equiv=\"refresh\" content=\"0;URL=add_user.php\">";
}
else {
echo "ERROR: ".mysql_error();
}
}
$sql = "INSERT INTO reg(Name ,Email) values ('".mysql_real_escape_string(stripslashes($_REQUEST['Name']))."','".mysql_real_escape_string(stripslashes($_REQUEST['Email']))."')";
This is my code. Here I found error of Undefined index.
I am a newbie in php. I have a form with multiple checkbox values. I wanna retrieve the checked values and diplay these values on other php form.
Below is the code which works perfectly fine if we add the checkboxes without while loop.
But when added through while loop I am not able to fetch the selected items.
xyzhtml.php(html form)
<?PHP
require ("DBConnect.php");
$selectQuery =mysql_query( "SELECT * FROM fruits where approved = 0");
while($row = mysql_fetch_array($selectQuery))
{
$fruit_name = $row['fruit_name'];
echo "<input type=\"checkbox\" name=\"things[]\" value=\"$fruit_name\">";
echo "<br>";
}
?>
On click of submit I call other php clled "xyz.php".
Below is the code used in it.
<?php
$checkBox = $_POST['things'];
echo $checkBox[0];
for($i=0; $i<sizeof($checkBox); $i++){
echo($checkBox[$i]);
}
?>
Please help.
Thanks in advance.
two things to check:
are you getting right values from the MySQL SELECT statement (check your HTML for empty checkboxes values and check your MySQL database for fruits that have approved field set to 0 to see if there are any)
when you don't tick a checkbox and submit the form, unticked checkboxes' values do not get submitted - have you thought about that?
Use foreach to record $_POST['things']
if (!empty($_POST['things'])) {
foreach ($_POST['things'] as $value) {
echo "the value are: ".$value;
}
}
Note: teh $_POST['things'] not $_POST['things[]']
I think your code should work, but it won't display anything if no checkboxes are selected.
I would however remove the explicit echo $checkbox[0] (unless this is for testing purposes).
Try a print_r($checkbox) to see what's actually in that array.