Change SQL statement upon change on seclection - javascript

I have two divs.
First div
Has inputs like checkbox and select.
<div>Events Selection</div>
Events <input type="checkbox" id="Option-1" checked="true">
Leaves <input type="checkbox" id="Option-2" checked="true">
Meetings <input type="checkbox" id="Option-3" checked="true">
Travels <input type="checkbox" id="Option-4" checked="true">
<div>Station Selection</div>
<select id="Filters1">
<option value="0">All Stations</option>
<option value="1">Main Station</option>
<option value="2">Sub Station</option>
<option value="3">Sub Station Main Office</option>
</select>
Second div
Has a SQL statement $sql = "SELECT * FROM events"; which i want to echo all those checked and selected options from First div.
So, my question is how to dynamically change the SQL statement when the selections or checkbox changed in First div.
Like: When the page loads, it should be like this:
$sql = Select * From events Where (every checkboxes are
checked and `All Stations` are selected.)
and when a user wants to filter the result from First div then the $sql statement should be changed to what the user selected and checked.
Like: I want to check the Events and Meetings checkbox with Main Station selection, so now i want that the $sql statement should be change to my selection in the Second div.

At first use parameterized query's, don't construct them dynamically. Examples and explanation on MSDN.
Write stored procedure that will receive value of selected option and will bring you data you need. F.e.:
CREATE PROCEDURE dbo.getevents
#value int
AS
SELECT *
FROM events
WHERE somecolumn = #value
It is simplified version, I guess you need some if statement like IF #value = 0...SELECT this ... IF #value = 1
In that case you can use:
$sql = "EXEC dbo.getevents ?";
$stmt = sqlsrv_query($conn, $sql, array($value));
And then fetch results and show it on your page.
EDIT#1
Using XAMP and SQL Server 2014
Disclaimer: I post this code only for demonstration purpose. Parameters are passed as a string, no styling, maybe some mistakes.
I have an installed XAMP. Downloaded sqlsrv libraries, enable them in php.ini.
I got local SQL Server with database Test. SQL server has an instance named sqldev. My computer name is workshop. So, instead of SERVER\INSTANCE should be workshop\sqldev. Instead of DATABASE - Test. That is what I wrote to connect.
At first I create table like this:
CREATE TABLE dummy (
id int identity(1,1),
[Desc] nvarchar(max),
[Type] nvarchar(100)
)
INSERT INTO dummy VALUES
('Do something already','Events'),
('Congrats!','Events'),
('Meet up at six PM','Meetings'),
('To Amsterdam','Travels'),
('goodbye!','Leaves')
Table contains some dummy-data to play with.
The next step:
Download jQuery from https://jquery.com/download/ (I used jquery-3.1.1.js)
index.php
<html>
<head>
<script src="jquery-3.1.1.js"></script>
<style>
table {
width:20%
}
table, td, th {
border-collapse: collapse;
border: 1px solid gray;
}
</style>
</head>
<body>
<div>Events Selection</div>
Events <input type="checkbox" id="option" class="options" name="options[]" value="Events">
Leaves <input type="checkbox" id="option" class="options" name="options[]" value="Leaves">
Meetings <input type="checkbox" id="option" class="options" name="options[]" value="Meetings">
Travels <input type="checkbox" id="option" class="options" name="options[]" value="Travels">
<div id="response"></div>
<script>
$('input:checkbox').click(function() {
$.ajax({
url: "sql_page.php",
type: "post",
data: $('.options:checked').serialize(),
success: function(data) {
$('#response').html(data);
}
});
});
</script>
</body>
</html>
sql_page.php
<?php
header('Content-Type: text/html; charset=utf-8');
$serverName = "SERVER\INSTANCE";
$connectionInfo = array("Database"=>"DATABASE");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if(isset($_POST['options'])) {
if( $conn === false ) {
echo "Unable to connect.</br>";
die( print_r( sqlsrv_errors(), true));
}
$values = $_POST['options'];
$valuelist = "'" . implode("', '", $values) . "'";
$tsql = "SELECT * FROM dummy WHERE [Type] IN (".$valuelist.");";
$stmt = sqlsrv_query($conn, $tsql);
if( $stmt === false ) {
echo "Error in executing query.</br>";
die( print_r( sqlsrv_errors(), true));
}
echo "<table>";
while ($obj = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC)) {
echo "<tr>
<td>".$obj[0]."</td>
<td>".$obj[1]."</td>
<td>".$obj[2]."</td>
</tr>\n";
}
echo "</table>";
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn );
}
?>
Then I go on index.php in my browser:
If you are using MySQL you need another libraries and commands to use, but they are similar to what I wrote. The main idea is to connect to the database and run some query with parameters, it is a sql_page.php idea.
The index.php part sends Ajax request to sql_page.php when checkboxes are clicked. And then show the data from this page (that was got from SQL Server) in div with id=response.
EDIT#2
Using EasyPHP Devserver 16.1.1 dowloaded from here
I installed EasyPHP in default folder, start it, went to http://127.0.0.1:1111, started Apache + PHP on port 8888, started MySQL.
I create a DB named air-hr, table named events in it. The script and structure of table below:
CREATE TABLE `events` (
`eventid` int(11) NOT NULL,
`eventname` varchar(100) NOT NULL,
`eventcategory` varchar(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `events` (`eventid`, `eventname`, `eventcategory`) VALUES
(1, 'Go now!', 'Leaves'),
(2, 'Meet some new people', 'Meetings'),
(3, 'Travel to Amsterdam', 'Travels'),
(4, 'PARTY HARD!', 'Events');
Also I create user test that can connect to DB and select from table.
I have created 2 files in C:\Program Files (x86)\EasyPHP-Devserver-16.1\eds-www project folder (their description is below) and copy jquery-3.1.1.js.
index.php like above and
sql_page.php
<?php
header('Content-Type: text/html; charset=utf-8');
if(isset($_POST['options'])) {
$values = $_POST['options'];
$valuelist = "'" . implode("', '", $values) . "'";
$query = "SELECT * FROM events WHERE eventcategory IN (".$valuelist.");";
$link = mysqli_connect("localhost", "test", "testpass", "air-hr");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
echo "<table>";
if ($result = mysqli_query($link, $query)) {
while ($row = mysqli_fetch_row($result)) {
echo "<tr>
<td>".$row[0]."</td>
<td>".$row[1]."</td>
<td>".$row[2]."</td>
</tr>\n";
}
mysqli_free_result($result);
}
echo "</table>";
mysqli_close($link);
}
?>
And results here:
Hope this helps you!

here you code
first named your inputs and select as follow:
<form action="sql_page.php" method="post">
<div>Events Selection</div>
Events <input type="checkbox" id="Option-1" name="Option-1" checked="true">
Leaves <input type="checkbox" id="Option-2" name="Option-2" checked="true">
Meetings <input type="checkbox" id="Option-3" name="Option-3" checked="true">
Travels <input type="checkbox" id="Option-4" name="Option-4" checked="true">
<div>Station Selection</div>
<select id="Filters1" name="Filters1">
<option value="0">All Stations</option>
<option value="1">Main Station</option>
<option value="2">Sub Station</option>
<option value="3">Sub Station Main Office</option>
</select>
<input type="submit" id="submit">
</form>
and in your sql_page.php here php code
if (isset($_POST)) {
foreach ($_POST as $col => $value) {
$whare .= "$col = '$value' AND ";
}
$whare = rtrim($whare,'AND ');
$sql = "Select * From events Where $whare";
}

Related

How do I display the HTML GET request data on the same HTML page, using a separate PHP file to fetch it?

I'm trying to get data from a MySQL database, that is being selected from a dropdown in an HTML file, and have the data display on the same HTML page that it is being selected from. I already have the HTML and PHP working to retrieve the data and display it, but it is not displaying on the same page that the user requests it from, it is displaying on the PHP page.
Here is the HTML code for get_project_form.html :
<html>
<head>
<title>Get Project Form</title>
<!--Link this html page to the project_style.css page-->
<link rel="stylesheet" type="text/css" href="project_style.css">
</head>
<body>
<div class="container">
<form action="get_project_action.php" autocomplete="off" method="get">
<label for="Query Selections">Query Selections : (You can only select
all data from "Projects"
for now):</label>
<select id="first_query" name="queries" required>
<option value="" disabled selected>Make a Selection</option>
<option value="Projects">Projects</option>
</select><br />
<input type="submit" value="Submit"><br />
</div>
</body>
</html>
After you make the selection and click submit the data appears on a page with the URL,
http://localhost:8015/get_project_action.php?queries=Projects
Here is the code for the php file get_project_action.php :
<?php
echo "<table style='border: solid 1px black;'>";
class TableRows extends RecursiveIteratorIterator
{
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td style='width: 150px; border: 1px solid black;'>" .
parent::current() . "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pmo";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $_GET["queries"];
$stmt = $conn->prepare("SELECT * FROM $query");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach (new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as
$k => $v) {
echo $v;
}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>
I'd like to keep the HTML and PHP separate if possible. But from what I'm reading I'm guessing that isn't possible. I'm hearing that its best to keep the logic in a separate PHP file but that its best to put the rest of the PHP that does the displaying in the HTML file and change the .html file to a .php instead. But I was hoping there is a way to have the data display in the get_project_form.html page below the form somewhere without combining any of the PHP inside the get_project_form.html file and changing it to a .php. If this is possible, please show me how. If not, please feel free to show me how to do whatever is considered good practice for displaying the data on a web page. Any help will be highly appreciated!
suppose in php file you are using $dropdownData array variable to store data from db.
//PHP file
<?php
//query to fetch data from db.
$dropdownData;
$this->view('get_project_form.html',$dropdownData);
?>
//Then use this array variable $dropdownData in ur HTML file with "for loop" to display
//HTML file
//you can also validate the $dropdownData if it's not empty; otherwise php will give error.
<select id="first_query" name="queries" required>
<option value="" disabled selected>Make a Selection</option>
<? foreach ($dropdownData as $val => $text) { ?>
<option value="<? echo $val; ?>" > <? echo $text;?> </option>
<? } ?>
</select>

Querying MySQL with PHP and javascript drop down menu

I've looked all over for a few days now, but haven't found a solution to my problem. I'm writing some PHP to query from a MySQL database that I have setup on my WAMP server. I'm also learning PHP and HTML javascript as I go, so the syntax of both languages is still a little unfamiliar to me.
My goal is to have a drop down selector box is written in Java that allows the user to chose a filter to apply to the select query, something like this:
SELECT * from exampletable WHERE header = "selected_option"
Where 'exampletable' is the table existing in the SQL database, 'header' is a column within that table, and 'selected option' is the user's choice from the drop-down.
I have tried writing various HTML forms with actions that call the PHP file that contains the SQL query using the $_POST superglobal, but nothing seems to work. Any suggestions and examples of solutions would be amazing.
Thanks!
index.php (index.php is the front end with the user interface)
<!DOCTYPE HTML>
<html>
<form action="search.php" method="post">
<select name="family">
<option value="" selected="selected">Any family</option>
<option value="capacitory">capacitor</option>
<option value="resistor">resistor</option>
<option value="ferrite bead">ferrite bead</option>
</select>
<input name="search" type="submit" value="Search>
</form>
</html>
search.php (search.php receives the selected option value and passes it into the MySQL query)
<!DOCTYPE HTML>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
$con = mysqli_connect('localhost','root','kelly188','mysql');
mysqli_select_db($con,"testv2");
$varfam = $_POST['family'];
$query = "SELECT * FROM testv2 WHERE (family = $varfam)";
$result = mysqli_query($query);
if($result)
{
while ($row=mysql_fetch_array($result)){
echo "<tr>";
echo "<td>".$row['family']."</td>";
}
} else {
die(mysqli_error());
}
?>
</body>
</html>
You should use a prepared statement to prevent SQL injection. The mysql_fetch_array function has been removed from recent versions of PHP. Something more like the following would be more ideal.
if ($stmt = $con->prepare("SELECT * FROM testv2 WHERE (family = ?)")) {
$stmt->bind_param("s", $_POST['family']);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>".htmlentities($row['family'])."</td>";
echo "</tr>";
}
$stmt->close();
}
See PHP documentation: http://php.net/manual/en/mysqli.prepare.php
index.php
<form action="search.php" method="post">
<select name="family">
<option value="" selected="selected">Any family</option>
<option value="capacitory">capacitor</option>
<option value="resistor">resistor</option>
<option value="ferrite bead">ferrite bead</option>
</select>
<input name="search" type="submit" value="Search"/>
</form>
search.php
<?php
//////////////////////////////////
// Connect to database using PDO
$servername = "localhost";
$username = "test";
$password = "";
$dbname = "test_db";
$db_conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,$password);
// End of database connection
////////////////////////////////////
if(isset($_POST['search']))
{
$family = $_POST['family'];
if(empty($_POST['family']))
{
$stmt = $db_conn->prepare("SELECT * FROM testv2");
$stmt->execute();
//we get the data
while($data = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $data['family'];
echo "<hr>";
}
}
else
{
$stmt = $db_conn->prepare("SELECT * FROM testv2 WHERE family = :family");
$stmt ->bindParam(':family', $family);
$stmt->execute();
//we get the data
while($data = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $data['family'];
echo "<hr>";
}
}
}
?>

PHP form text field to mysql based on selected checkbox [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am trying to create sign up form, where it has multiple text field (name, email, phone, ..) and have multiple checkbox options.
I also created multiple tables in mysql database, one for each checkbox.
My goal is to store values in text field to selected checkbox data table.
My question is how can I create if statement to look what checkbox is selected, so it will store input of text field to that table
input.php
<html>
<head>
</head>
<script type="text/javascript">
function toggle(source) {
checkboxes = document.getElementsByName('chk1[]');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
</script>
<body>
<h2><font color="white">Welcome to Cars and Coffee</h2>
<p>Sign up to receive if you are interested in
receiving information from Cars and Coffee.</p>
<p>Please select at least one option</p>
<form name="newEntry" action="page.php" method="POST">
name<input type=text length=60 size=30 name="name"><br>
email<input type=text length=60 size=30 name="email"><br>
car<input type=text length=60 size=30 name="car"><br>
phone<input type=text length=60 size=30 name="phone"><br>
<input type="submit" name="submit" email="add" car="add" phone="add" >
</form>
<form action="page.php" method="POST">
<input type="checkbox" name="chk[]" value="cars_coffee">Cars & Coffee<br>
<input type="checkbox" name="chk[]" value="kentucky">Kentucky Derby Party<br>
<input type="checkbox" name="chk[]" value="july">July 4th<br>
<input type="checkbox" name="chk[]" value="labor">Labor Day<br>
<input type="checkbox" name="chk[]" value="new_year">New Years Day<br>
<input type="checkbox" name="chk[]" value="all" onClick="toggle(this)">Select All<br>
</form>
<?php
mysql_connect("localhost", "db", "pw");
mysql_select_db("db");
$qh = mysql_query("select * from all_emails order by id desc");
if (#mysql_num_rows($qh)) { /* the if(#...) syntax makes PHP supress any
warnings that might come out of that function. */
/* mysql_fetch_object(query handle);
* returns an object whose contents are that of one rotw in the
database. */
while ($obj = mysql_fetch_object($qh)) {
echo "
<p>
$obj->email<br>
$obj->name<br>
$obj->car<br>
$obj->phone<br>
<p>
<hr>
";
}
}
?>
</body>
</html>
page.php
<?php
mysql_connect("localhost", "db", "pw");
mysql_select_db("db");
mysql_query("insert into all_emails (name, email, car, phone) values ('".$_POST['name']."','".$_POST['email']."','".$_POST['car']."', '".$_POST['phone']."' )");
?>
<html>
<head>
<meta http-equiv=refresh content="0; URL=./input.php">
</head>
</html>
Here is the if statement I am trying.
<?php
mysql_connect("localhost", "db", "pw");
mysql_select_db("db");
if( isset($_POST["cars_coffee"] ) ) {
$sql = "INSERT INTO cars_and_coffee (name, email, car, phone) values ('".$_POST['name']."','".$_POST['email']."','".$_POST['car']‌​."', '".$_POST['phone']."' )");
mysql_query($sql) or die(mysql_error());
}
echo "Record is inserted";
}
?>
Hi use the following code :
NOTE : I highly suggest you to use mysqli or PDO. mysql functions are deprecated and are obsolate.
Please sanitize or safe cast your data before inserting into your database.
Also NOTE: In form I am redirecting to the same form page. Please use the appropriate php file name or routing path.
db_connect.php
$host = 'localhost';
$user = 'root';
$password = 'root';
$database = 'skerp';
$connection_error = 'Sorry!!! We are experiencing problems with the database settings';
$link = mysqli_connect($host, $user, $password, $database) or DIE($connection_error);
The following is the implementation
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if($_SERVER['REQUEST_METHOD'] == 'POST'){
include_once ('db_connection.php');
if(in_array('cars_coffee', $_POST['chk'])){
$emails = mysqli_query($link, "INSERT INTO all_emails (name, email, car, phone) VALUES ('".$_POST['name']."','".$_POST['email']."','".$_POST['car']."', '".$_POST['phone']."' )");
}else{
//If it fails then put the condition here or you may skip else part
echo 'Not Exists';
}
echo '<pre>';
print_r($_POST);
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<input type="checkbox" name="chk[]" value="cars_coffee">Cars & Coffee<br>
<input type="checkbox" name="chk[]" value="kentucky">Kentucky Derby Party<br>
<input type="checkbox" name="chk[]" value="july">July 4th<br>
<input type="checkbox" name="chk[]" value="labor">Labor Day<br>
<input type="checkbox" name="chk[]" value="new_year">New Years Day<br>
<input type="checkbox" name="chk[]" value="all" onClick="toggle(this)">Select All<br>
<input type="submit" value="Submit" />
</form>
</body>
</html>
Hope it helps. Happy Coding!
You can use the isset method to check if a checkbox was selected.
if ( isset ( $_POST ["cars_coffee"] ) )
{
// do something
}
if ( isset ( $_POST ["kentucky"] ) )
{
// do something else
}
...
There seems to be a slight problem with your logic because you are using checkboxes to retrieve data from the user. If you want the user to only select one checkbox, use a radio button. That will make them unable to select multiple. If I'm just not understanding you correctly and you really do want users to be able to select multiple boxes, then keep using checkboxes, but change the name attribute of each checkbox to be unique. Because right now, every checkbox has the same name, so it is going to read only the last checkbox that they checked.
The logic would go something like this if you continued using checkboxes and gave each checkbox a unique name:
$sql = '';
// make sure that the checkbox is set
if(isset($_POST['kentucky_checkbox'])){
{
$sql += 'INSERT INTO kentucky VALUES ...;';
}
if(isset($_POST['labor_checkbox'])){
{
$sql += 'INSERT INTO labor VALUES ...;';
}
etc.
...
// execute $sql
The logic would go something like this if you used radio buttons:
// make sure that the variable is set
if(isset($_POST['chk[]'])){
{
// check what the value is
switch ($_POST['chk[]']) {
case 'option1':
// set the table
$table = 'table1';
break;
case 'option2':
$table = 'table2';
break;
case 'option3':
$table = 'table3';
break;
}
}
...
$sql = 'INSERT INTO ' . $table . ' VALUES ...';

update selected dropdown values in database with form submit

users register to site. admin will login & see list of users.
I am trying to give an option for admin to select checkbox and change status of user through Dropdown submit. when i tried below code i can able to select "Y/N/A" , after clicking submit button its displaying message "Added Successfully" , but its not updating values in database.
table name : tbl_users , column : userStatus [enum] , values : Y, N, A
form
<form method="post" action="ajax1.php">
<select name="userStatus">
<option value="N">N</option>
<option value="Y">Y</option>
<option value="A">A</option>
</select>
<button type="submit" name="submit" >Submit</button>
</form>
ajax1.php
if(isset($_POST["submit"]))
{
$userStatus=$_POST["userStatus"];
$conn = new Database();
$stmt = $conn->dbConnection()->prepare("INSERT INTO tbl_users (userStatus) VALUES ('$userStatus')");
echo " Added Successfully ";
}
code to display users checkbox, id, name ,email :
$stmt = $user_home->runQuery("SELECT * FROM tbl_users");
$stmt->execute(array(":uid" => $_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt->execute();
$status = array('Y'=>'Verified','N'=>'Not verified' , 'A'=>'Approved');
echo "<table>";
echo "<tr>
<td></td>
<td>id</td>
<td>name</td>
<td>email</td>
</tr>";
while($data = $stmt->fetch())
{
echo "<tr>
<td> <input type='checkbox' > </td>
<td>" . $data['userID'] . "</td>
<td>" . $data['name'] . "</td>
<td>" . $data['email'] . "</td>
</tr>";
}
echo "</table>";
i researched & tried lot before posting question, in some links i saw we need to use Javascript, but in some other links, they mentioned we can achieve only with php.
i am very new to coding, please help me
Edit
after following below answer , i updated code as $stmt = $conn->dbConnection()->prepare('UPDATE tbl_users SET userStatus = ? WHERE userID = ?');
<form method="post" action="ajax1.php">
<select name="userStatus" id="userStatus" onchange="UpdateStatus();">
<option value="N">N</option>
<option value="Y">Y</option>
<option value="A">A</option>
</select>
<button type="submit" name="submit" >Submit</button>
</form>
<script>
function UpdateStatus(){
var staus=$('#userStatus :selected').val();
allCheckedBoxes="";
$("input[id^='checkBoxId']:visible:checked").each(function(){ // this is to get checked checkbox vaues to update which user to update
allCheckedBoxes=allCheckedBoxes+$(this).val()+","; // comaseparated valuse
});
var dataString="allCheckedBoxes="+allCheckedBoxes+"&staus="+staus;
$.post("aupdate_status.php",'allCheckedBoxes='+allCheckedBoxes'&staus='+staus,function(result,status,xhr)
{
if( status.toLowerCase()=="error".toLowerCase() )
{ alert("An Error Occurred.."); }
else
{
alert(result);
}
})
.fail(function(){ alert("something went wrong. Please try again") });
}
</script>
update_status.php
<?php
$staus=$_POST['staus'];
$allCheckedBoxes=$_POST['allCheckedBoxes'];
$ArrallCheckedBoxes=explode(",",$allCheckedBoxes);
foreach($ArrallCheckedBoxes as $tempBoxes){
$sqlQueryToUpdate=" UPDATE tbl_users SET userStatus = '".$staus."' WHERE userID = '".$tempBoxes."' ;";
$conn = new Database();
$stmt = $conn->dbConnection()->prepare($sqlQueryToUpdate);
echo " ok success";
}
?>
Please try this . This is working in my case. This will work you too. Don't forget add jquery in your coding.
What you are doing is actually inserting a new row to the table with this line:
"INSERT INTO tbl_users (userStatus) VALUES ('$userStatus')"
You should do an UPDATE, not an insert. What you basically want to do is UPDATE the user WHERE the user userID (or whatever the id column is named) is the id of the selected user.
See MySQL UPDATE.

Two drop down list, second one populated with values in database

I need to make two drop down lists. Let's say the first one containing food categories: Ice Cream, Pizzas, Noodles, Milkshakes.
So if I pick ice cream the second drop down list would contain: Chocolate, Vanilla, Mint and so on. And if I pick Pizzas at the first one, I want this second one to change dynamically so that it would contain: Pepperoni, All Meat, and so on.
However, I need the second drop down list to be populated by the values I already have in my database. So let's say if I'm out of chocolate ice cream there would be no chocolate in the second drop down list. That is my desired outcome.
I am using HTML, PHP, JavaScript/jQuery, and MySQL so currently it's a webapp and these two drop down list are for me to delete values from the database. So let's say I want to delete Pepperoni from Pizzas, I would select Pizzas at the first drop down list and then Pepperoni at the second drop down list. Then I would click delete which would execute a js function to pass the parameters using ajax to PHP and then the delete query can be executed.
I am stuck on populating the second drop down list dynamically, any help on this? What I've done so far for the drop down is only:
<select id="tester_type">
<option value=""></option>
<option value="LMX">LMX</option>
<option value="LCX">LCX</option>
<option value="CAT">CAT</option>
<option value="J750">J750</option>
<option value="HPPS">HPPS</option>
<option value="HP93K">HP93K</option>
<option value="UFLEX">UFLEX</option>
<option value="IFLEX">IFLEX</option>
<option value="QRT">QUARTET</option>
<option value="TGR">TIGER</option>
<option value="ETS">ETS</option>
<option value="LEX">LEX</option>
<option value="HPLC">HPLC</option>
<option value="HPSS">HPSS</option>
</select>
</td>
</tr>
<tr>
<td>New Tester Name:</td>
<td>
<select id="tester_type">
<!--Update list of available testers-->
</select>
</td>
Note: I just replaced the first drop down list as food category for a better understanding of my question by the way. Just take the first one as food categories and the second would be its type/flavors.
EDIT:
It doesn't display anything in the desired section/div in the window. Just a blank except for the title I have added in my HTML and other two buttons.
What I have done according to Brandon's answer:
In the HTML:
<html>
<head>
<title>Delete Tester</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="function.js"></script>
<script type="text/javascript">displayDropDown();</script>
</head>
<body>
<h3>Delete Tester</h3>
<div id="drop_two_list"></div>
<table class="deleteTable">
<tr>
<td/><td><br>
<input type="button" value="Cancel" onclick="window.close();"/>
<input type="button" name="send" value="Delete" onclick="deleteTester();"/>
</td>
</tr>
</table>
</body>
</html>
In the external javascript file:
function dislplayDropDown()
{
var page = "database.php";
$.post(page, {
action : "dislplayDropDown"
}, function(data) {
$("div#drop_two_list").html(data);
alert(data);
});
In the PHP:
function displayDropDown()
{
$tester_info = "dummy_tester_list";
$query_string = "select * from $tester_info";
$result = #mysql_query($query_string) or die (mysql_error());
$data = mysql_fetch_array($result) or die (mysql_error());
echo "<select id=\"tester_type\">";
while($data)
{
echo "<option value='$data['tester_type']'>$data['tester_type']</option>"; // first drop down
}
echo "</select>";
$selected_tester_type = $_REQUEST['tester_type'];
$query_string = "select * from $tester_info where tester_type = $selected_tester_type";
$result = #mysql_query($query_string) or die (mysql_error());
$data = mysql_fetch_array($result) or die (mysql_error());
echo "<select>";
while($data)
{
echo "option id=\"tester_name\" value='$data['tester_name']'>$data['tester_name']</option>"// second drop down
}
echo "</select>";
}
?>
<?php
$action = rtrim($_REQUEST['action']);
if($action=="insert")//This is for some other function
{
$tester_type = rtrim($_REQUEST['tester_type']);
$tester_name = rtrim($_REQUEST['tester_name']);
echo checkDuplicateTesterName($tester_type, $tester_name);
}
else if($action=="displayDropDown")
{
echo displayDropDown();
}
?>
Here's the table structure as requested by Kentot, it's only the first five rows because there's more than 500 rows so I wouldn't want to put the whole thing here:
id tester_type tester_name
1 LMX LMX-01
2 LMX LMX-04
3 LMX LMX-05
4 LMX LMX-06
5 LMX LMX-07
you can create this table say we will call this "menu"
food_id | food_type_flavor | food_category
--------------------------------------------
1 | chocolate | ice cream
2 | vanilla | ice cream
3 | lemon | juice
and in your code you can create this
$query = mysql_query("Select * from menu");
echo "<select name='food_category' >";
while($test = mysql_fetch_array($query))
{
echo "<option value='$test['food_category']'>$test['food_category']</option>"; // first drop down
}
echo "</select>";
then when you select category you can get what was the food_category being selected and you can use that variable to make your second drop down
$selected_category = $_POST['food_category'];
$query = mysql_query("Select * from menu where food_category ='$selected_category'");
echo "<select>";
while($test = mysql_fetch_array($query))
{
echo "<option name='food_flavor_type' value='$test['food_type_flavor]' >$test['food_type_flavor']</option>"; // second drop down
}
echo"</select>";
Hai hzq I have made modification in your code for me to answer it cleaner:
your HTML:
<?php
$result = mysql_query("select * from dummy_tester_list");
$data = mysql_fetch_array($result);
?>
<select id="tester_type">
<?php foreach($data as $d): ?>
<option value="<?php echo $d["tester_type"]?>"><?php $d["tester_type"];?></option>
<?php endforeach ?>
</select>
<section id="tester_name">
</section>
<h3>Delete Tester</h3>
<table class="deleteTable">
<tr>
<td><div id="drop_two_list"></div></td>
</tr>
<tr>
<input type="button" value="Cancel" onclick="DELETE_TESTER_POPUP.close();"/>
<input type="button" name="send" value="Submit" onclick="deleteTester();"/>
</td>
</tr>
</table>
Your PHP where you want to get the list of the selected tester type:
<?php
$tester_type = $_POST["tester_name"];
$query = mysql_query("select * from tester_info where tester_type = {$tester_type}");
$select_dropdown;
$select_dropdown .= "<select name='tester_lists'>";
while($row = mysql_fetch_array($query)){
$select_dropdown .= "<option>{$row["tester_name"]}</option>";
}
$select_dropdown .= "</select>";
echo $select_dropdown;
?>
Your jquery when you change the tester name and get the equivalent tester list
$("body").on("change","#tester_type",function(){
$.ajax({
url: "dropdowns.php", // your php file
type: "POST",
data: tester_name: $(this).val(),
success: function(data){
$("#tester_name").html(data);
}
});
});
you can try this one ..
<?php
function displayDropDown()
{
$tester_info = "dummy_tester_list";
$query_string = "select * from $tester_info";
$result = #mysql_query($query_string) or die (mysql_error());
$data = mysql_fetch_array($result) or die (mysql_error());
echo "<select id=\"tester_type\">";
while($data)
{
?>
<option><?php echo $data['tester_type']; ?></option>
<?php
}
echo "</select>";
$selected_tester_type = $_REQUEST['tester_type'];
$query_string = "select * from $tester_info where tester_type = $selected_tester_type";
$result = #mysql_query($query_string) or die (mysql_error());
$data = mysql_fetch_array($result) or die (mysql_error());
echo "<select>";
while($data)
{
?>
<option><?php echo $data['tester_name']; ?></option>
<?php
}
echo "</select>";
}
?>
<?php
$action = rtrim($_REQUEST['action']);
if($action=="insert")//This is for some other function
{
$tester_type = rtrim($_REQUEST['tester_type']);
$tester_name = rtrim($_REQUEST['tester_name']);
echo checkDuplicateTesterName($tester_type, $tester_name);
}
else if($action=="displayDropDown")
{
echo displayDropDown();
}
?>
so we separate the tag to remove the error

Categories