I'm new in programming and I'm stuck with dropdown lists.
I have to display 2 dropdown lists. In first one I have to display all categories from one table. In second one I have to display values from another table depends of the selected value in first dropdown list.
I found this answer, but I don't know how can I get selected value and use it for second dropdown list. I tried with $_POST, but it doesn't work.
Can someone give me any instructions how to do that?
Thank you.
<?php
...
$conn = new mysqli($hostname, $username, $password, $databaseName)
or die ('Cannot connect to db');
$kat = $conn->query("select idkategorija, kategorija from kategorija");
echo "<html>";
echo "<body>";
echo "<select name='izb_kategorija' method = 'post'>";
while ($row = $kat->fetch_assoc()) {
unset($idkategorija, $kategorija);
$idkategorija = $row['idkategorija'];
$kategorija = $row['kategorija'];
echo '<option value="'.$idkategorija.'">'.$kategorija.'</option>';
}
echo "</select>";
echo $idkategorija; // I want to use idkategorija in my next query for second dropdown list
echo "</body>";
echo "</html>";
?>
I modified this code for you.Use this code,i hope it will work for you.
<?php
...
$conn = new mysqli($hostname, $username, $password, $databaseName);
or die ('Cannot connect to db');
$kat = $conn->query("select idkategorija, kategorija from kategorija");
?>
<html>
<body>
<select name='izb_kategorija' method = 'post'>
<?php
while ($row = $kat->fetch_assoc())
{
$idkategorija = $row['idkategorija'];
$kategorija = $row['kategorija'];
?>
<option value="<?php echo $idkategorija; ?>"><?php echo $kategorija; ?></option>
<?php
}
?>
</select>
</body>
</html>
Related
How do I echo values that are submitted from a form on another page (which they are submitted into the database) into an HTML tag as options?
This is my latest code and I'm still stuck here. When I clicked on the drop-down list, it still shows nothing.
<select name="comName" id="comName" class="form-control" required>
<?php include('db_company.php');
$query_option = "SELECT * FROM company";
$result = mysqli_query($query_option);
while($row = mysqli_fetch_array($result)) {
echo "<option value='{$row['comName']}'>{$row['comName']}</option>";
}
?>
</select>
There are some mistakes that you have done in here.First of all I would like to suggest you to start using error reporting using,
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
If you have used error reporting from the beginning I believe you would have noticed all the issues that you are facing now.
1.You need to use the DB connection when you are using mysqli_query
$link = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DATABASE);
$result = mysqli_query($link,$query_option);
2.You are using the wrong value inside the while loop.
while($row = mysqli_fetch_array($result)) {
echo "<option>".$row{'company'}."</option>";
}
You are getting comName from the query so you have to use comName instead of company.
while($row = mysqli_fetch_array($result)) {
echo "<option value=".$row{'comName'.">".$row{'comName'}."</option>";
}
Your echo in row is wrong
<?php include('db_company.php');
$query_option = "SELECT * FROM company";
$result = mysqli_query($query_option);
while($row = mysqli_fetch_array($result)) {
echo "<option value='{$row['id']}'>{$row['company']}</option>";
}
?>
So I am currently working on a forum, and I want to be able to have users edit their own questions and replies. Currently I am able to edit questions (sort of *other error is below) just fine. But replies are my biggest problem right now. Currently it shows an edit button under a reply but then it will allow me to edit ALL the other replies on the page and then when I save it, it saves the very last row.
<h3>Replies:</h3>
<div id="replies">
<?php
while($rows = mysqli_fetch_array($result2)) {
?>
<p id="dates"><?php echo $rows['a_datetime']; ?></p>
<div id="reply">
<b><p><?php echo $rows['a_username']; ?></p></b>
<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
$text = htmlspecialchars($rows['a_answer']);
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
$url = preg_replace("/^http:/i", "https:", $url);
// make the urls hyper links
echo preg_replace($reg_exUrl, '<a title="Opening this link will take you to a new page" alt="External Link Deleted" target="_blank" href="'.$url[0].'" rel="nofollow">'.$url[0].'</a>', '<p id="reply'.$rows['a_id'].'">'.$text.'</p>');
} else {
?>
<p id="reply<?php echo $rows['a_id']; ?>"><?php echo htmlspecialchars($rows['a_answer']); ?></p>
<?php
}
if($_SESSION['username'] == $rows['a_username']) {
$editReply = true;
?>
<div id="questionId"><?php echo $rows['question_id'];?></div>
<div id="replyId"><?php echo $rows['a_id'];?></div>
<button id="editReply">Edit</button>
<button id="saveReply">Save</button>
<button id="cancelReply">Cancel</button>
<script type="text/javascript">
$(document).ready(function(argument) {
$('#saveReply').hide();
$('#cancelReply').hide();
});
</script>
<?php
}
?>
</div>
<script type="text/javascript">
$(document).ready(function(argument) {
$('#editReply').click(function() {
$('#reply<?php echo $rows['a_id']; ?>').attr('contenteditable','true');
$('#reply<?php echo $rows['a_id']; ?>').css('background','white');
$('#reply<?php echo $rows['a_id']; ?>').css('border','solid 1px');
$('#saveReply').show();
$('#cancelReply').show();
$('#editReply').hide();
});
$('#saveReply').click(function() {
// Get edit field value
$detail = $('#reply<?php echo $rows['a_id']; ?>').html();
$q_id = $('#questionId').html();
$a_id = $('#replyId').html();
$.ajax({
url: 'editReply.php',
type: 'post',
data: {detail: $detail, q_id: $q_id, a_id: $a_id},
datatype: 'html',
});
$('#editReply').show();
$('#saveReply').hide();
$('#cancelReply').hide();
$('#reply<?php echo $rows['a_id']; ?>').attr('contenteditable','false');
$('#reply<?php echo $rows['a_id']; ?>').css('background','#D8D8D8');
$('#reply<?php echo $rows['a_id']; ?>').css('border','none');
});
$('#cancelReply').click(function() {
$('#editReply').show();
$('#saveReply').hide();
$('#cancelReply').hide();
$('#reply<?php echo $rows['a_id']; ?>').attr('contenteditable','false');
$('#reply<?php echo $rows['a_id']; ?>').css('background','#D8D8D8');
$('#reply<?php echo $rows['a_id']; ?>').css('border','none');
});
});
</script>
<?php
}
?>
editreply.php:
<?php
$host = "host"; // Host name
$user = "username"; // Mysql username
$password = ""; // Mysql password
$db_name = "db"; // Database name
$tbl_name = "fanswer"; // Table name
// Connect to server and select databse.
$conn = mysqli_connect($host, $user, $password)or die("cannot connect");
mysqli_select_db($conn, $db_name)or die("cannot select DB");
$detail = htmlspecialchars($_POST['detail']);
$q_id = $_POST['q_id'];
$a_id = $_POST['a_id'];
// Add your validation and save data to database
echo $detail;
echo $q_id;
echo $a_id;
$sql = "UPDATE $tbl_name SET a_answer = '$detail' WHERE question_id='$q_id' AND a_id= '$a_id'";
$result = mysqli_query($conn, $sql);
?>
Originally I had all the editable content in divs but for some reason it made some pages load funny so for now I was hoping to use the p tag.
How can I make it so only one of the replies are editable and so it only sends that information to the editreply.php script?
*My other problem which is sort of a side problem, when I go to edit something that has a link in it I get a load of gibberish posted into my database. E.g. a user post LMAO: https://afunnypic.com, the information in my database says:
LMAO: <a title="Opening this link will take you to a new page" alt="External Link Deleted" target="_blank" href="https://afunnypic.com" rel="nofollow">https://afunnypic.com</a><br>
Which I don't understand.
Just found my answer to the first problem, all I did was move the script inside the if ($editReply = true) statement and it worked!
If anyone can help with the second bit on editing the links bit that would be great!
I'm getting the details from the user and storing it in mysql database. I have an update page in which the user can update the values. At that time, I want to allow the user to reselect the value from the drop down in which the value entered at first should be already selected. how can I make the value fetched from the database as selected option. please explain with some code samples.
$query="SELECT * from tablename where id=".$id;// I've assigned the value for id
$rows=mysql_query($query,$connect);
$row=mysql_fetch_array($rows,MYSQL_ASSOC);
?>
<select name="designation"> <?php
echo "<option value=\"$row[OptionID]\" SELECTED>$row[OptionName]</option>\n";
?>
<option value=sol1>sol1</option>
<option value=sol2>sol2</option>
<option value=sol3>sol3</option>
</select>
Making an assumption that you have a table with users (ID, UserID, OptionID) and a table of options (OptionID, OptionName) or similar.
$get_details = $conn->query("SELECT * FROM table");
$data = $get_details->fetch_assoc();
$get_options = $conn->query("SELECT * FROM options");
while($row = $get_options->fetch_assoc()) {
if($row['OptionID'] == $data['OptionID'])
echo "<option value=\"$row[OptionID]\" SELECTED>$row[OptionName]</option>\n";
else
echo "<option value=\"$row[OptionID]\">$row[OptionName]</option>\n";
}
In order to make a dropdown select box using a database you can follow the below given approach:
<?php
$databaseHost = "localhost";
$databaseUser = "root";
$databasePassword = "password";
$databaseName = "employee";
$con=mysql_connect($databaseHost ,$databaseUser ,$databasePassword,'employee')or die ('Connection Error');
$dbSelected = mysql_select_db('foo', $con);
if (!$dbSelected) {
die ('Can\'t use foo : ' . mysql_error());
}
?>
<strong> Select Designation : </strong>
<select name="empName">
<option value=""> -----------ALL----------- </option>
<?php
$dd_res=mysqli_query($con, "Select DISTINCT designation from emp");
while($r=mysqli_fetch_row($dd_res))
{
echo "<option value='$r[0]'> $r[0] </option>";
}
?>
</select>
UPDATE
For old MySQl:
<?php
$databaseHost = "localhost";
$databaseUser = "root";
$databasePassword = "password";
$databaseName = "employee";
$con=mysql_connect($databaseHost ,$databaseUser ,$databasePassword)or die ('Connection Error');
$db_selected = mysql_select_db('foo', $con);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
?>
<strong> Select Designation : </strong>
<select name="empName">
<option value=""> -----------ALL----------- </option>
<?php
$dd_res=mysql_query("Select DISTINCT designation from emp");
while($r=mysql_fetch_row($dd_res))
{
echo "<option value='$r[0]'> $r[0] </option>";
}
?>
</select>
Hi so the here is my question,
I have a Database containing Categories and Subcategories.
I have two dropdown boxes (select). I want them both to be populated by using PHP/MYSQL.
My Categories have been generated:
<select name="prod_cat">
<?php
include("php/dbconnect.php");
$sql = "SELECT * FROM categories";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
echo '<option value="'. $row["cat_name"] .'">'. $row["cat_name"] .'</option>';
}
}
else{echo "No categories were found!";}
mysqli_close($conn);
?>
</select>
I want the subcategories to load when the category has changed.
My SQL will look something like this:
SELECT subcat_name FROM subcategories WHERE cat_name = '$prod_cat'
I need to get the value from the categories dropdown and store it as a variable.
In the past I have done something similar in javascript:
var subcat=document.forms["form"]['subcat'].value;
and then changed the value of another dropdown by calling an onChange(); function like:
document.getElementById('subcat').innerHTML='<option value=""></option>';
I hope someone can point me in the right direction! Should I be looking into AJAX, JavaScript or can it all be done with PHP?
Thank you.
add an id on category select box , like this -
<select name="prod_cat" id="prod_cat">
<?php
include("php/dbconnect.php");
$sql = "SELECT * FROM categories";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
echo '<option value="'. $row["cat_name"] .'">'. $row["cat_name"] .'</option>';
}
}
else{echo "No categories were found!";}
mysqli_close($conn);
?>
</select>
for subcategory -
<select id='sub_cat' name='sub_cat'></select>
write your script something like this -
<script>
$("#prod_cat").change(function(){
//get category value
var cat_val = $("#prod_cat").val();
// put your ajax url here to fetch subcategory
var url = 'www.example/fetch_subcategory.php';
// call subcategory ajax here
$.ajax({
type:"POST",
url:url,
data:{
cat_val : cat_val
},
success:function(data)
{
$("#sub_cat").html(data);
}
});
});
</script>
add code in ajax calling page -'www.example/fetch_subcategory.php'
<?php
$prod_cat = $_POST['cat_val'];
$sql = "SELECT subcat_name FROM subcategories WHERE cat_name = '$prod_cat'";
$result = mysqli_query($conn, $sql);
$msg ='';
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
$msg =.'<option value="'. $row["sub_cat_name"] .'">'. $row["sub_cat_name"] .'</option>';
}
}
else{$msg .="No categories were found!";}
echo $msg;
mysqli_close($conn);
?>
Do something like this, and hope it will work for you.
i have a problem with that i need to get the value from the dropdown list to be a number and the name for a kategory to be the name that the user picks.
<select name="kategori">
<?php
$query=mysql_query("SELECT KategoriID from Kategori");
$second=mysql_query("SELECT KategoriNavn from Kategori");
while($r=mysql_fetch_row($query) && $v=mysql_fetch_row($second)){
echo "<option value='$r[0]>$v[0]</option>";
}
?>
This is the code i have, but i cant make it to work.
Im kinda new to PHP. Thanks!
There's no need to write two different queries. You could have written just a single one. I think mysql fetch_assoc is a tad easier to understand.
You can try something like this:
<?php
$query = mysql_query("SELECT KategoriID, KategoriNavn from Kategori") or die(mysql_error()); // Debugging displays SQL syntax errors, if any.
echo "<pre>";
print_r($query);
exit; // Let me know what the array looks like.
while ($r= mysql_fetch_assoc($query)) { ?>
<option value=<?php echo $r['KategoriID']; ?> >
<?php echo $r['KategoriNavn']; ?>
</option>
<?php } ?>
<?php
echo "<pre>";
print_r($_POST); // Do this where you're checking your POST data
exit;
?>
Assuming you want option value to be KategoriNavn and the option to display to be KategoriID.
Hope this helps.
Peace! xD