how to chose MySQL table via drop down list - php

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.

Related

validate select tag html php

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'])) {

I am trying to add a static option to a dynamic drop down field in php

I am working on an in house web based license tracking application for my small business. The web filter contains a dynamic drop down box that populates based on the data in a certain field within the database.
It works great and is functional now, but I would like to add some functionality to it.
Currenty there are two drop down boxes, one for department and one for software. The way it works is, you set those two filter, and it will output a table with all the records that match BOTH criteria. This makes it easy to see all software licenses of a particular application that each department has ordered and had installed.
What I have started doing, is using this to also track uninstalled, or available licenses to cut software costs, and re-use more. What I would like to do is add a static ALL option to each of the fields so it will select all departments that match the selected software, or show all the software that matches a particular department, and in some rare cases set both to all so it displays all software from all departments.
Here is the code that I currently have in place and is functioning properly...
<?php
echo "<p><a href='view.php'>View All</a> | <a href='un_view.php'>View Uninstalled</a> | <a href='view_paginated.php?page=1'>View Printable Version</a></p>";
echo "<br>";
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<p><strong>Filter Options</strong></P>
<?php
$sql2 = "SELECT DISTINCT dept FROM sw_lic";
$sql3 = "SELECT DISTINCT sw_name FROM sw_lic WHERE sw_name != ''";
$result2 = mysql_query($sql2);
$result3 = mysql_query($sql3);
?>
<form action="filter_view.php" method="POST">
<p><select name="dept">
<?php
while($nt=mysql_fetch_array($result2))
{
echo "<option name='dept' value=$nt[dept]>$nt[dept]</option>";
}
?>
</select>
<select name="sw_name">
<?php
while($st=mysql_fetch_array($result3))
{
echo "<option name='sw_name' value='$st[sw_name]'>$st[sw_name]</option>";
}
?>
</select>
<input type="submit" name="submit" value="Submit">
</form>
<?php
}
// connect to the database
include('connect-db.php');
// 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
$username = mysql_real_escape_string(htmlspecialchars($_POST['username']));
$sysname = mysql_real_escape_string(htmlspecialchars($_POST['sysname']));
$dept = mysql_real_escape_string(htmlspecialchars($_POST['dept']));
$sw_name = mysql_real_escape_string(htmlspecialchars($_POST['sw_name']));
$sw_ver = mysql_real_escape_string(htmlspecialchars($_POST['sw_ver']));
$origin = mysql_real_escape_string(htmlspecialchars($_POST['origin']));
$sw_key = mysql_real_escape_string(htmlspecialchars($_POST['sw_key']));
// check to make sure all fields are entered
if ($username == '' || $dept == '' || $sw_name == '' || $sw_ver == '' || $origin == '' || $sw_key == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($username, $sysname, $dept, $sw_name, $sw_ver, $origin, $sw_key, $error);
}
else
{
// save the data to the database
mysql_query("INSERT sw_lic SET username='$username', sysname='$sysname', dept='$dept', sw_name='$sw_name', sw_ver='$sw_ver', origin='$origin', sw_key='$sw_key'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','');
}
?>
If anyone can help me out I would greatly appreciate it. If anymore details are required please let me know.
Thanks,
Just add a static option value like this:
<p><select name="dept">
<option value="_all_">All</option>
<?php
while($nt=mysql_fetch_array($result2))
{
echo "<option name='dept' value=$nt[dept]>$nt[dept]</option>";
}
?>
</select>
</p>
And then modify your query accordingly.

Unable to Submit to Database

Using the MVC Framework, I have made some code that is meant to add information to the Database.
In Index.php (views)
<form method="post" action="<?php echo URL;?>note/updatetopic">
<select>
<option value="1">Coasts</option>
<option value="2">Energy Demand</option>
</select>
<input type="submit" name="topic_selection" value="Choose" />
</form>
The Code above is meant to post information about what a user would like to revise.
In note.php (controllers)
public function updatetopic() {
if (isset($_POST['topic_selection'])) {
$note_model = $this->loadModel('Note');
$note_model->updatetopic($_POST['topic_selection']);
}
header('location: ' . URL . 'note');
}
The Code above is meant to get information from the code in index.php and forward it onto the note_model where it runs a function.
In note_model.php (models)
public function updatetopic($topic_selection)
{
$topic_selection = strip_tags($topic_selection);
$sql = "INSERT INTO users (topic_revising) VALUES (:topicselected) WHERE user_id=:user_id";
$query = $this->db->prepare($sql);
$query->execute(array(':topicselected' => $topic_selection, ':user_id' => $_SESSION['user_id']));
$count = $query->rowCount();
if ($count == 1) {
return true;
} else {
$_SESSION["feedback_negative"][] = TOPIC_UPDATE_FAILED;
}
// default return
return false;
}
This is meant to validate the submitted information and insert it into the database but it outputs:
$_SESSION["feedback_negative"][] = TOPIC_UPDATE_FAILED;
Can someone please help me and tell me what im doing wrong? Thanks.
You are not choosing any name for your select tag:
try like this:
<select name="topic">
<option value="1">Coasts</option>
<option value="2">Energy Demand</option>
</select>
And now get the the value of yuor drop down list:
if (isset($_POST['topic'])) {
$note_model = $this->loadModel('Note');
$note_model->updatetopic($_POST['topic']);
// $_POST['topic'] == 1 or 2 depends upon selection
}
you can change it like:
<select name="topic">
<option value="coasts">Coasts</option>
<option value="Energy_Demand">Energy Demand</option>
</select>
now u'll get the real value of selected list item and can move further....
Your SQL query will not work as you have tagged mysql which does not support this kind of syntax:
INSERT INTO users (topic_revising) VALUES (:topicselected) WHERE user_id=:user_id
Basically there is no WHERE in MySQL (MySQL Insert Where query)
You should check for duplicated either in select query, or if there are unique keys - use ON DUPLICATE KEY. Also take a look at the linked topic

A null value becomes 0 in Mysql and PHP

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.

submit one or another query

I'm continuing to hack away at my newbie php/mySQL 'Invoicer' app.
I now have a form page in which I want to run one of two queries - either an INSERT or an UPDATE, depending on whether an ID is present. When present,
the ID is used to retrieve the record and pre-populate the form accordingly, which I have working. My problem now is that my conditional bits are
obviously not right because in either case when submitting the form the INSERT query is run, can't get the UPDATE to run, and I've exhausted my
understanding (and guess-ology).
I'd love to know why this ain't working, even if it's not the best approach, and I'm definitely open to suggestions to move the queries to a process.php,
etc. I'm also wondering if I should use 'if(isset($_GET['ID'])' to simply include one block or the other.
Many thanks in advance for any help or suggestions. (p.s. my intention is to overhaul for best practices/security once I've got the broad strokes wired up)
cheers, s
<?php
// CASE I: 'EDIT RECORD':
// If there's an ID ...
if (isset($_GET['ID']) && is_numeric($_GET['ID'])) {
$id = $_GET['ID'];
echo "<p class=\"status\"><strong>ID IS SET ... ergo we're editing/UPDATING an existing record</strong></p>";
// ... retrieve the record ....
$query = sprintf("SELECT * FROM Invoices WHERE ID = %s", $id);
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
// ... assign variables to pre-populate the form
$id = $row['ID'];
$invNumber = $row['invNumber'];
$invDate = $row['invDate'];
// [ snip: more variables > field data ]
// on submit: get the form values ...
// no worky: if (isset($_GET['ID']) && isset($_POST['submit'])) {
if (isset($_POST['submit'])) {
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
// [ snip: more variables > field data ]
// ... and UPDATE the db:
$qUpdate = "UPDATE Invoices SET invNumber='$invNumber', invDate='$invDate', projNumber='$projNumber', client='$client', task='$task', issueDate='$issueDate', subTotal='$subTotal', tax='$tax', invTotal='$invTotal', datePaid1='$datePaid1', datePaid2='$datePaid2', comments='$comments' WHERE ID='3'";
$result = mysql_query($qUpdate) or die(mysql_error());
if($result) {
echo "<p class=\"status\"><strong>SUCCESS: RECORD UPDATED!</strong></p>";
}
else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error());
} // CLOSE '(isset($_POST['submit']))
} // END CASE I: ID present
// CASE II: 'NEW RECORD'; query = INSERT
elseif (empty($_GET['ID'])) {
echo "<p class=\"status\"><strong>No ID ... ergo we're INSERTING a new record:</strong></p>";
// on submit: get the form values ...
if (isset($_POST['submit'])) {
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
// [ snip: more variables > field data ]
$qInsert = "INSERT INTO Invoices (invNumber,invDate,projNumber,client,task,issueDate,subTotal,tax,invTotal,datePaid1,datePaid2,comments)
VALUES('$invNumber','$invDate','$projNumber','$client','$task','$issueDate','$subTotal','$tax','$invTotal','$datePaid1','$datePaid2','$comments')";
$result = mysql_query($qInsert) or die(mysql_error());
if($result) {
echo "<p class=\"status\"><strong>SUCCESS: NEW RECORD INSERTED!</strong></p>";
}
else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error());
} // CLOSE '(isset($_POST['submit']))
} // END CASE II: No ID present
?>
and:
<form id="invoiceData" method="post" action="/html/form.php">
When you submit the form, you need to include the ID again, otherwise it is silently dropped off since you are posting to the hard-coded value /html/form.php (with ID removed). This will cause the empty($_GET['ID']) part to match and run, causing the INSERT. You can simply include the ID value back into the action of every form post like this:
<form
id="invoiceData"
method="post"
action="/html/form.php?ID=<?php echo $_GET['ID']; ?>"
>
This should work in both the cases of the UPDATE and the INSERT, because if there was no ID to begin with, this will render as /html/form.php?ID=, which will match the case of ID being empty, I believe. You may want to test this logic out for sure.
Hope this helps!
$_GET[ID] will be set if you pass it as a URL parameter. So if you change your <form> action to
<form id="invoiceData" method="post" action="/html/form.php?ID=12">
Where 12 is whatever ID you want, you should be getting the results you're wanting -- as long as you do have a <input type="hidden" name="submit" value="1" /> (value can be whatever) in your form somewhere as well.

Categories