I got DB with multiple tables like Regions/Countries/States/Etc. And I want to make dropdown lists based on other list selected.
I have tried many things, but nothing seems to work.
This is my latest version :
Core.php :
<html>
<body>
<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
<script type="text/javascript">
function abc(){
var val = document.getElementById('Region_ID').value;
$.post("getSecondDropDown.php",{ Region_ID:val}, function( data ) {
$("#Country_ID").html(data);
});
}
</script>
<form action="/NewService.php" id="ServiceForm" method="post">
Name:<input type="text" name="Service_Name"></br>
Region: <select name="Region_ID" onchange="abc()" form="ServiceForm">
<?php
include('config.php');
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT Region_ID, Region_Name FROM Regions");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt as $v) {
echo "<option value='" . $v['Region_ID'] ."'>" . $v['Region_Name'] ."</option>";
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
</select></br>
Country: <select name="Country_ID" form="ServiceForm">
</select></br>
<input type="submit">
</form>
</body>
</html>
getSecondDropDown.php :
<?php
$Region_ID =$_POST['Region_ID'];
$option="";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT Country_ID, Country_Name FROM Countries WHERE Region_ID ='$Region_ID'");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt as $v) {
echo "<option value='" . $v['Country_ID'] ."'>" . $v['Country_Name'] ."</option>";
}
echo $option;
?>
Image
Here is your problem , you didn't write the id attribute in select tag
<select name="Region_ID" id="Region_ID" onchange="abc()" form="ServiceForm">
<option></option>
</select>
And try in javascript:
<script type="text/javascript">
function abc(){
var e = document.getElementById("Region_ID");
var val = e.options[e.selectedIndex].value;
$.post("getSecondDropDown.php",{ Region_ID:val}, function( data ) {
$("#Country_ID").html(data);
});
}
</script>
Related
Database Table "Product" has a "Product_Code" and "Product_Name"
We have a form where we fill Product Data
Select options are fetched from Database table column "Product_Code"
<select name="Select_Product_Code" id="Select_Product_Code">
<option value="0">Product</option>
<?php
$con = mysqli_connect('localhost','user1db','userdb','1db');
if (!$con) { die('Could not connect: ' . mysqli_error($con)); }
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM Product";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
?>
<option value = "<?php echo($row['Product_Code'])?>" >
<?php echo($row['Product_Code']);
?>
</option>
<?php
}
?>
</select>
Without Form submit, Is there a way to show "Product_Name" in a Label or TextInput when "Product_Code" is selected ?
Edit , added ajax.
readproduct.php
<!DOCTYPE html>
<html>
<head>
<script>
function showProduct(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("txtHint").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","getproduct.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="products" onchange="showProduct(this.value)">
<option value="">Select </option>
<option value="1">0001</option>
<option value="2">0002</option>
<option value="3">0003</option>
<option value="4">0004</option>
</select>
</form>
<br>
<div id="txtHint"><b>list</b></div>
</body>
</html>
getproduct.php as follows
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','user1db','userdb','1db');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
echo "Connected";
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM Stock WHERE Product_Code = '".$q."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
echo $row['Product_Name'];
}
mysqli_close($con);
?>
If we remove where clause, all products names are displayed,
with where clause, getproduct.php does not display Product_Names.
What we missed or did wrong?
You can populate an array inside your while loop that will be used later in a change listener for the select element like so:
<select name="Select_Product_Code" id="Select_Product_Code">
<option value="0">Product</option>
<?php
$con = mysqli_connect('localhost','user1db','userdb','1db');
if (!$con) { die('Could not connect: ' . mysqli_error($con)); }
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM Product";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
// here it adds a name with a key that matches the option-value
$names[$row['Product_Code']] = $row['Product_Name'];
?>
<option value = "<?php echo($row['Product_Code'])?>" >
<?php echo($row['Product_Code']);
?>
</option>
<?php
}
?>
</select>
<input type="text" id="out-text" value="The Name will appear here" />
<!-- then it populates the array with json_encode() to be used in the event-listener (both below) -->
<script type="text/javascript">
var names = <?php echo json_encode($names); ?>;
document.getElementById("Select_Product_Code").addEventListener(
'change',
function() {
document.getElementById("out-text").value = names[this.selectedIndex];
},
false
);
</script>
This is not the only way to do it, but its vanilla javascript/php, and here is a JSFiddle with the basic logic (minus the PHP part)
I have made a simple php and jquery based program. In which when a page is open then I want to show all category data first and All is selected. And then when change category by dropdown then data will be display according to selected Category.
But using this change function of jquery how to do that.
Two files:
index.php file
<?php
$db = mysql_connect('localhost', 'root', 'root') or die("Could not connect database");
mysql_select_db('myproject', $db) or die("Could not select database");
$result = mysql_query("SELECT * from category");
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#select_category").change(function(){
var catid = $("#select_category option:selected").val();
$.ajax({
type : "post",
url : "product.php",
data: { id:catid },
success: function (response) {
var getres = $.parseJSON(response);
var results = "";
results += "<table border='1'>";
results += "<tr>"+
"<th>Product Name</th>"+
"<th>Category</th>"+
"<th>Publish</th>"+
"</tr>";
$.each(getres.data , function (key,value){
results += "<tr><td>" + value.product_name + "</td><td>" + value.publish + "</td><td>" + value.category + "</td></tr>";
});
results+= "</table>";
$(".result-container").html(results);
}
});
});
});
</script>
</head>
<body>
<select name="cat" id="select_category">
<option value="0">--All--</option>
<?php
while ($row = mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['cat_id'] ?>"><?php echo $row['cat_name'] ?></option>
<?php } ?>
</select><br><br><br>
<div class="result-container">
</div>
</body>
</html>
product.php file
$db = mysql_connect('localhost', 'root', 'root') or die("Could not connect database");
mysql_select_db('myproject', $db) or die("Could not select database");
$cat_id = $_POST['id'];
$query = "SELECT p.name AS product_name,CASE WHEN p.publish='yes' THEN '+' ELSE '-' END AS publish,c.cat_name AS categoryFROM product p LEFT JOIN category c ON c.cat_id = p.category";
if(!empty($cat_id)){
$query = $query. 'WHERE p.category='.$cat_id;
}
$sql = mysql_query($query);
$rows = array();
while($r = mysql_fetch_assoc($sql)) {
$rows[] = $r;
}
$result=array('data'=>$rows);
echo json_encode($result);
You can do that by calling same ajax code on page load with empty category id.
<?php
$db = mysql_connect('localhost', 'root', 'testing') or die("Could not connect database");
mysql_select_db('myproject', $db) or die("Could not select database");
$result = mysql_query("SELECT * from category");
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function ajaxCall(catid = '') {
$.ajax({
type: "post",
url: "product.php",
data: { id: catid },
success: function(response) {
var getres = $.parseJSON(response);
var results = "";
results += "<table border='1'>";
results += "<tr>" +
"<th>Product Name</th>" +
"<th>Category</th>" +
"<th>Publish</th>" +
"</tr>";
$.each(getres.data, function(key, value) {
results += "<tr><td>" + value.product_name + "</td><td>" + value.publish + "</td><td>" + value.category + "</td></tr>";
});
results += "</table>";
$(".result-container").html(results);
}
});
}
$(document).ready(function() {
ajaxCall();
$("#select_category").change(function() {
var catid = $("#select_category option:selected").val();
ajaxCall(catid);
});
});
</script>
</head>
<body>
<select name="cat" id="select_category">
<option value="0">--All--</option>
<?php
while ($row = mysql_fetch_array($result)) {?>
<option value="<?php echo $row['cat_id']; ?>">
<?php echo $row['cat_name']; ?>
</option>
<?php } ?>
</select>
<br>
<br>
<br>
<div class="result-container"></div>
</body>
</html>
I am trying to create a drop down menu that will display Project Names off all Projects present in the table Project in the database Testing... The drop down is created but it is not accessing the database and retrieving the required data...
The code is as follows:
<html>
<head>
<title>Dynamic Drop Down List</title>
</head>
<form id="form1" name="form1" method="post" action="<?php echo $PHP_SELF; ?>">
Project List :
<select Project Name='NEW'>
<option value="">--- Select ---</option>
<?
$serverName = "Swagatha-PC";
$connectionInfo = array( "Database"=>"Testing");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn )
{
echo "Connection established.<br />";
}
else
{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
if (isset ($select)&&$select!="")
{
$select=$_POST ['NEW'];
}
?>
<?
$query=mysql_query("select ProjectName from dbo.Project");
$menu=" ";
while($row = sqlsrv_fetch_array($query))
{
$menu ="<option>" . $row["ProjectName"] . "</option>";
}
?>
</select>
<input type="submit" name="Next" value="Select" />
</form>
</body>
</html>
Dropdown Error
What Do i do to fix this??
The solution is
while($row = sqlsrv_fetch_array($query))
{
echo "<option>" . $row["ProjectName"] . "</option>";
}
See? You output data with echo instead assinging data to variable.
And as #FirstOne noticed using mysql_query with sqlsrv_connect is an error too. I hope it's just your typo:
$query=sqlsrv_query($conn, "select ProjectName from dbo.Project");
As another sidenote
if (isset ($select)&&$select!="")
{
$select=$_POST ['NEW'];
}
this if will always be false, because you first check $select and then define it. It definitely should be:
if (isset($_POST['NEW']) && $_POST['NEW'] != "")
{
$select = $_POST['NEW'];
}
Here is you fixed code. You can try it
<html>
<head>
<title>Dynamic Drop Down List</title>
</head>
<form id="form1" name="form1" method="post" action="<?php echo $PHP_SELF; ?>">
Project List :
<select Project Name='NEW'>
<option value="">--- Select ---</option>
<?php
$serverName = "Swagatha-PC";
$connectionInfo = array( "Database"=>"Testing");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn )
{
echo "Connection established.<br />";
}
else
{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
if (isset ($select)&&$select!="")
{
$select=$_POST ['NEW'];
}
$query=sqlsrv_query("select ProjectName from dbo.Project");
$menu=" ";
while($row = sqlsrv_fetch_array($query))
{
echo "<option>" . $row["ProjectName"] . "</option>";
}
?>
</select>
<input type="submit" name="Next" value="Select" />
</form>
</body>
</html>
I'm using a form to input new projects into my database. One of the fields is Lead Writer. I want to add a drop down menu to that field that will display the names of the lead writers from my database that the user can then select to populate that field. I've managed to get the drop down to appear in the field, but my code isn't generating any names. I tried setting up a function that would call those results, but it's obviously not working. The form worked well prior to my changes, so it's not an issue connecting to the database. Any help would be greatly appreciated.
function query(){
$myNames = "SElECT LastName FROM Projects";
$result = $mysqli->query($myNames);
while($result = mysqli_fetch_array($myNames)){
echo '<option value=' . $record['LastName'] . '>' . $record['LastName'] . '</option>';
}
}
?>
<?php
$connection->close();
?>
<form action="http://www.oldgamer60.com/Project/NewProject.php" method="post">
<div class="fieldset">
<fieldset>
Project: <input type="text" name="Project value="<?php if(isset($Project)){ echo $Project; } ?>">
<span class="error">* <?php if(isset($ProjectErr)){ echo $ProjectErr; } ?></span>
<br><br>
Client: <input type="text" name="Client" value="<?php if(isset($Client)){ echo $Client; } ?>">
<span class="error">* <?php if(isset($ClientErr)){ echo $ClientErr; } ?></span>
<br><br>
Lead Writer: <select name="dropdown">
<?php query() ?>
</select>
<br><br>
Date Received: <input type="text" name="DateReceived" value="<?php if(isset($DateReceived)){ echo $DateReceived; } ?>">
<span class="error">* <?php if(isset($DateReceivedErr)){ echo $DateReceivedErr; } ?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</fieldset>
</div>
</form>
Edited Code:
<html>
<head>
</head>
<body>
<?php
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "oldga740_SeniorProject";
// create connection
$connection = new mysqli($servername, $username, $password, $dbname);
function query($mysqli){
$myNames = "SELECT LastName FROM Projects";
if(!$result = $mysqli->query($myNames)) {die($mysqli->error);} // check for error message
if($result->num_rows > 0){ // if there is rows
while($record = $result->fetch_array()){
echo '<option value="' . $record['LastName'] . '">' . $record['LastName'] . '</option>';
}
} else { // if there is no rows
echo '<option value="">No Rows</option>';
}
}
?>
<form>
Lead Writer: <select name="dropdown">
<?php query($mysqli); ?>
</select>
</form>
<?php
$connection->close();
?>
</body>
</html>
2nd Edit:
// create connection
$connection = new mysqli($servername, $username, $password, $dbname);
function query($connection){
$myNames = "SELECT LastName FROM Projects";
if(!$result = $connection->query($myNames)) {die($mysqliconnection->error);} // check for error message
if($result->num_rows > 0){ // if there is rows
while($record = $result->fetch_array()){
echo '<option value="' . $record['LastName'] . '">' . $record['LastName'] . '</option>';
}
} else { // if there is no rows
echo '<option value="">No Rows</option>';
}
}?>
<?php
$connection->close();
?>
<form>
Lead Writer: <select name="dropdown">
<?php query($connection); ?>
</select>
</form>
</body>
</html>
You have a variable scope issue - http://php.net/manual/en/language.variables.scope.php. $mysqli is undefined in your function query(). You need to pass it as a param. Also, you were trying to do mysqli_fetch_array() on the query string, instead of the mysqli result. I have updated it to the OO ->fetch_array().
function query($mysqli){
$myNames = "SELECT LastName FROM Projects";
$result = $mysqli->query($myNames);
while($record = $result->fetch_array()){
echo '<option value=' . $record['LastName'] . '>' . $record['LastName'] . '</option>';
}
}
You will also need to pass it in your call
Lead Writer: <select name="dropdown">
<?php query($mysqli); ?>
</select>
You can add some debugging to find out why it is not printing
function query($mysqli){
$myNames = "SELECT LastName FROM Projects";
if(!$result = $mysqli->query($myNames)) {die($mysqli->error);} // check for error message
if($result->num_rows > 0){ // if there is rows
while($record = $result->fetch_array()){
echo '<option value="' . $record['LastName'] . '">' . $record['LastName'] . '</option>';
}
} else { // if there is no rows
echo '<option value="">No Rows</option>';
}
}
per your edit - https://stackoverflow.com/posts/34257335/revisions
Your mysqli connection is $connection
// create connection
$connection = new mysqli($servername, $username, $password, $dbname);
so not sure why you are trying to use $mysqli
$mysqli->query($myNames)
as $connection != $mysqli.
As you are doing the query in a function, you don't need to rename all instances of $mysqli to $connection, as you can just change to
Lead Writer: <select name="dropdown">
<?php query($connection); ?>
</select>
I need some help I am trying to create a PHP form using sqlite3 database. I am looking up values from from an existing sqlite3 database in the "lookuptable" where the column "id = 340" and display those values as a dropdown selection. Then once the value is selected by the user then the form is submitted by the user which updates the new value in the "roster" table with the values from the php form. I get it to display the names in the dropdown but when I click on the update button to submit the data it updates what the value is in the array.
How do I post "firstname" and "lastname" from the user to the roster table instead of of the number on the array table?
PHP entry page Code:
<html>
<head>
<title></title>
</head>
<div class = "controlbox">
<body style="font-size:12;font-family:verdana">
<form action="post.php" method="post">
<p>
<h1> </h1>
<br>
<br>
Person : <select name="name">
<option>--Available Options--</option>
<?php
try
{
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e)
{
echo $e->getMessage();
}
$stmt2 = $db->query ("SELECT * FROM lookuptable where ID = '340' ");
$rowarray = $stmt2->fetchall(PDO::FETCH_ASSOC);
$cntr = 0;
foreach($rowarray as $row)
{
echo "<option value = $cntr >$row[FirstName] $row[LastName]</option>";
$cntr++;
}
?>
</select><br>
<p>
<input type="submit" name="update" value="update">
</p>
</form>
</body>
</html>
PHP Code: Post.php
<?php
$name = sqlite_escape_string($_POST['name']);
try
{
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e)
{
echo $e->getMessage();
}
if (!empty($person)) {
try
{
$stmt = $db->prepare("UPDATE roster SET rotationplace = :name WHERE ID = '340'");
$stmt->bindParam(':name', $name,PDO::PARAM_STR);
$stmt->execute();
}
catch(Exception $e)
{
echo $e->getMessage();
}
echo "submitted successfully";
}
?>
Try:
echo "<option value = $INSERT_NAME_HERE_NOT_COUNTER >$row[FirstName] $row[LastName]</option>";