I am using PHP 5 to create a query page for a MySQL database with 2 tables "students" and "teachers". I have created a combo box which can allow users to view and select the 2 tables from the combo box via a "submit" button after selecting from the combo box.
However the problem with the script is that I want to verify if the "submit" button works which I created a "echo.php" to echo out the value of the combo box and submit button. Overall the idea is to do a query like these steps:
1) User selects value from combo box "teacher" or "student".
2) User clicks submit button.
3) After clicking submit button, user is redirected to "echo.php"
4) "echo.php" should output/echo out either "teacher" or "student".
The codes for script:
<?php
include "db_connect.php";
{
?>
<td valign=top><strong>Name:</strong></td>
<td>
<?php
echo "<form name = \"queryEquipTypeForm\" method = \"post\" action
=\"select_table.php\">";
echo '<select name=\"table\">';
echo "<option size =30 selected>Select</option>";
$result = mysql_query("show tables");
if(!$result) trigger_error("Query Failed: ". mysql_error($db), E_USER_ERROR);
if(mysql_num_rows($result))
{
while($table_array = mysql_fetch_array($result))
{
echo "<option>$table_array[0]</option>";
}
echo '</select>';
echo '</form>';
if(!$_POST['submit'])
{
?>
<form method="post" action="select_table.php">
<input type="submit" name="submit" value="Submit">
</form>
<?php
}
else
{
echo '<script type="text/javascript">
alert("Redirecting you to echo.php page");
window.location="echo.php"</script>';
}
}
else
{
echo "<option>No Names Present</option>";
}
}
?>
</td>
The codes for "echo.php" :
<?php
include "select_table.php";
echo "data is : ".$_POST['table'];
?>
The output of echo.php would be exactly the same as "select_table.php" with the cobo box and the "data is: " without the "teachers" or "student" word as its being redirected to echo.php.
I'm not quite sure what exactly what you want to do, but as michaeltwofish already pointed out, redirecting to another page using javascript will make you lose the post data. Also you seem to echo two <form> elements when the select_table.php is called without post data, one with only a submit button, while your first form is missing the button.
Normally, you would want your php script to either output the form with the combobox where the user can select the table, or, if there was post data (meaning that the user selected a value), the results of the selection, kinda like the following:
<?php
if(isset($_POST['table'])) {
print "Selected element: " . $_POST['table'];
} else {
echo '<form method="post" action="select_table.php">';
echo '<select name="table">';
// here should be your SQL query and the combobox options generation
echo '</select>';
echo '<input type="submit" />';
echo '</form>';
}
?>
When the form is submitted, you redirect to echo.php, but that means you lose the POST data. You need to think carefully about the flow of your application, because what you have seems a bit confused.
Related
I've written a while loop in PHP which creates many buttons which contain their individual username in a drop-down list, which relate to some usernames being brought in from a database. (it's a friend adding system)
I would like to be able to get the username from the clicked button and just store it in a variable, I know what to do from there, but I can't work that out.
if($getAddFriendUsernamesResult)
{
$row=mysqli_fetch_array($getAddFriendUsernamesResult);
while($row)
{
$username = $row['username'];
if($username!=$_SESSION['_username']) #Doesnt print the users own name in add friends
{
?><a><button class="AddFriendButton"><?php echo $row['username']; ?></button></a>
<?php
}
$row=mysqli_fetch_array($getAddFriendUsernamesResult);
}
}
At the moment this lists all of the usernames accept the person logged in in a long list. I want to get the contents of the button (the username of the clicked button) and store that in a php variable.
First, get rid of the <a> tag.
Then give the button name and value attributes.
<button name="add_friend" class="AddFriendButton" value="<?= $row['username'] ?>">
<?= echo $row['username']; ?>
</button>
Then (assuming all the code in your loop is contained in a <form> element), you'll be able to get the value from $_POST['add_friend'].
Overall, something like this:
<?php if ($getAddFriendUsernamesResult) {
// open a form
echo '<form method="post" action="add_friend.php">';
while ($row = mysqli_fetch_array($getAddFriendUsernamesResult)) {
$username = $row['username'];
if ($username != $_SESSION['_username']) {
// give each button a name and value - may want to use id instead of username
echo "<button name='add_friend' value='$row[username]' class='AddFriendButton'>
$row['username']
</button>";
};
}
echo '</form>';
}
I have a music database with a PHP front end where you can add/edit/delete artists, albums, tracks using the web client. The last real problem I have is getting a select box to automatically select an option I pass to the page.
Example:
On a page called 'createCD.php' I have this code:
echo "<td><a href=\"editCD.php?cdTitle=".rawurlencode($row['cdTitle'])."&cdID=$row[cdID]&artID=$row[artID]&cdGenre=".rawurlencode($row['cdGenre'])."&cdPrice=$row[cdPrice]\" </a>Edit</td>";`
This is used as a link to the next page, and collects all the information about an album in the database and sends in to a page called 'editCD.php'.
Now on this page, all the information is used to fill out the webpage as shown here (there is more but for the purposes of this post, only the first select box matters):
Artist Name:
<!-- dropdown with artist name -->
<?php
echo '<select name= "artID" id="artID">';
while ($row = mysqli_fetch_assoc($result)){
echo '<option value="'.$row['artID'].'">'.$row['artName'].'</option>';
}
echo '</select>';
?>
<p>
Album Title:
<input id="cdTitle" type="text" name="cdTitle" value ="<?php echo htmlspecialchars($cdTitle); ?>" />
</p>
What I would like is for the "selected" option for 'artID' to be the value that is passed to the page. Using the associative array, I was able to display the 'artName' associated with the 'artID'. Currently, all the information about the album appears correctly apart from the 'artName' and it defaults to the first value. This is a problem as if a user simply clicks "Update" it will update the name to the default name, therefore changing the database entry by accident.
I know I need to be using
<option selected ...>
but I'm not sure on the syntax to use.
<?php
$artID = $_GET['artID']; // get the artID from the URL, you should do data validation
echo '<select name= "artID" id="artID">';
while ($row = mysqli_fetch_assoc($result)){
echo '<option value="'.$row['artID'].'"';
if ($artID == $row['artID']) echo ' selected'; // pre-select if $artID is the current artID
echo '>'.$row['artName'].'</option>';
}
echo '</select>';
?>
$artId = $_GET['artID'];
while ($row = mysqli_fetch_assoc($result)) {
$selected = $artId == $row['artID'] ? 'selected' : '';
echo '<option value="'.$row['artID'].'" '.$selected.'>'.$row['artName'].'</option>';
}
First you get the id via $_GET['artID']. (In a real scenario use intval or something to prevent sql injection)
Then check in the loop if the id from database is the same as the id from GET and when it is print "selected, else nothing.
i've tried many solutions from the website, but noone give me the result.
I have a combobox, and i insert data from mysql db
after pressing "submit button", the combobox refresh, but restart from first data and not from selected,
hereunder my code,
can someone help me?
$result = mysql_query("SELECT * FROM courier");
while($row = mysql_fetch_array($result))
{
echo "<option ". (($_POST['NAZIONE'] == $row["NAZIONE"]) ? 'selected ' : '') ."value=\"".$row["NAZIONE"]."\">".$row["NAZIONE"]."</option>";
}
echo'</select> <br> <input type="submit" value="Proceed">';
mysql_close($con);
?>
you can set selected value to $_SESSION variable and then you can get that selected value
I'm currently using php to populate a form with selections from a database. The user chooses options in a select style form and submits this, which updates a summary of the selections below the form before a second submit button is used to complete the interaction.
My issue is that every time a user uses the first submit, the selections that were there previously do not stick. They have to go through the whole form again.
Is there anyway to keep these selections present without resorting to php if statements? There are a ton of options so it would be a pain to use php for each one. Also, form is being submitted via POST.
Sample from form:
<?php
// GRAB DATA
$result = mysql_query("SELECT * FROM special2 WHERE cat = 'COLOR' ORDER BY cat")
or die(mysql_error());
echo "<div id='color'><select id='color' name='product_color'>";
while($row = mysql_fetch_array( $result )) {
$name= $row["name"];
$cat= $row["cat"];
$price= $row["price"];
echo "<option value='";echo $name;echo"'>";echo $name;echo" ($$price)</option>";}
echo "</select>";
echo "<input type='hidden' name='amount_color' value='";echo $price;echo"'></div>";
?>
I tried using this js snippet to repopulate the selections, but it does not seem to work properly...
<script type="text/javascript">document.getElementById('color').value = "<?php echo $_GET['proudct_cpu'];?>";</script>
This does not seem to work. Any suggestions other than php if statements?
Thanks!
edit: This is basically the form set up I'm using, though I've shortened it significantly because the actual implementation is quite long.
// Make a MySQL Connection
<?php mysql_connect("localhost", "kp_dbl", "mastermaster") or die(mysql_error());
mysql_select_db("kp_db") or die(mysql_error());
?>
<br />
<form action="build22.php" method="post">
<input type="hidden" name="data" value="1" />
<br />
<br />
<?php
// GRAB DATA
$result = mysql_query("SELECT * FROM special2 WHERE cat = 'color' ORDER BY cat")
or die(mysql_error());
echo "<div id='color'><select id='color' name='product_color'>";
while($row = mysql_fetch_array( $result )) {
$name= $row["name"];
$cat= $row["cat"];
$price= $row["price"];
echo "<option value='";echo $name;echo"'>";echo $name;echo" ($$price)</option>";}
echo "</select>";
echo "<input type='hidden' name='amount_color' value='";echo $price;echo"'></div>";
?>
<input type="submit" value="Update Configuration">
</form>
The selections from the form above get echoed after submission to provide the user with an update as such:
<div id="config" style="background-color:#FFF; font-size:12px; line-height:22px;">
<h1>Current Configuration:</h1>
<?php echo "<strong>Color:</strong>    ";echo $_POST['product_color']; ?>
</div>
I assume you're storing the user's selections in a separate table. If that's the case, you'll need to add some logic to determine if you should display the form values or what's already been stored.
<?php
// form was not submitted and a config id was passed to the page
if (true === empty($_POST) && true === isset($_GET['config_id']))
{
// make sure to properly sanitize the user-input!
$rs = mysql_query("select * from saved_configuration where config_id={$_GET['config_id']}"); // make sure to properly sanitize the user-input!
$_POST = mysql_fetch_array($rs,MYSQL_ASSOC); // assuming a single row for simplicity. Storing in _POST for easy display later
}
?>
<div id="config" style="background-color:#FFF; font-size:12px; line-height:22px;">
<h1>Current Configuration:</h1>
<?php echo "<strong>Color:</strong>    ";echo $_POST['product_color']; ?>
</div>
So after storing the user's selections in the database, you can redirect them to the page with the new config_id in the URL to load the saved values. If you're not storing the selected values in a table, you can do something similar with cookies/sessions.
echo the variables into the value tag of the form elements. If you post all your code I'm sure I can help you.
UPDATE
ah, so they are dropdown lists that you need to remember what was selected? Apologies, I read your post in a rush yesterday and thought it was a form with text inputs.
I just did a similar thing myself but without trying your code let me see if I can help.
Basically what you need to do is set one value in the dropdown to selected="selected"
When I had to do this I had my dropdown values in an array like so:
$options = array( "stack", "overflow", "some", "random", "words");
// then you will take your GET variable:
$key = array_search($_GET['variablename'], $options);
// so this is saying find the index in the array of the value I just told you
// then you can set the value of the dropdown to this index of the array:
$selectedoption = $options[$key];
This is where it might be confusing as my code is different so if you want to use it you will probably need to restructure a bit
I have a doSelect function to which I pass the following parameters:
// what we are passing is: name of select, size, the array of values to use and the
// value we want to use as the default selected value
doSelect("select_name", 1, $options, $selectedoption, "");
// these are the two functions I have:
// this one just processes each value in the array as a select option which is either
// the selected value or just a 'normal' select value
FUNCTION doOptions($options, $selected)
{
foreach ($options as $option)
{
if ($option == $selected)
echo ("<option title=\"$title\" id=\"$value\" selected>$option</option>\n");
else
echo ("<option title=\"$title\" id=\"$value\">$option</option>\n");
}
}
// this is the function that controls everything - it takes your parameters and calls
// the above function
FUNCTION doSelect($name, $size, $options, $selected, $extra)
{
echo("<select class=\"\" id=\"$name\" name=\"$name\" size=\"$size\" $extra>\n");
doOptions($options, $selected);
echo("</select>\n");
}
I know that's a lot of new code that's been threw at you but if you can get your select values from the db into the array then everything else should fall nicely into place.
The only thing I would add, is at the start where we call doSelect, I would put that in an if statement because you don't want to set something as selected which hasn't been set:
if (isset($_GET['variable']))
{
$key = array_search($_GET['variablename'], $options);
$selectedoption = $options[$key];
doSelect("select_name", 1, $options, $selectedoption, "");
}
else
{
doSelect("select_name", 1, $options, "", "");
}
I hope that helps!
I am currently using PHP 5 with a MysSQL database with 2 tables. So far my PHP Combo Box is working however I need to access the values selected from the combo box. it goes like this:
1) I select a value from the Combo Box.
2) I click on the Submit button
3) The Submit button brings me to another webpage.
The problem that my program is facing now is during step 3 when I click the submit button there is no webpage generated. I think the problem is due to the sequencing of the Combo Box Codes and Button Codes.
My codes are as shown:
<?php
include "db_connect.php";
{
?>
<td valign=top><strong>Name:</strong></td>
<td>
<?php
echo '<select name="table_choice">';
echo "<option size =30 selected>Select</option>";
$result = mysql_query("show tables");
if(!$result) trigger_error("Query Failed: ". mysql_error($db), E_USER_ERROR);
if(mysql_num_rows($result))
{
while($table_array = mysql_fetch_array($result))
{
echo "<option>$table_array[0]</option>";
}
$array_value = $_POST['table_choice'];
if(!$_POST['submit'])
{
?>
<input type="submit" name="submit" value="Submit">
<?php
}
else
{
echo '<script type="text/javascript">
alert("Redirecting you to the site main page");
window.location="echo.php"</script>';
}
}
else
{
echo "<option>No Names Present</option>";
}
}
?>
Everything seems fine to me.
Where is the <form> tag?
Anyway, consider writing your web applications using some web framework or at least templates to separate the program logic (PHP code) from the presentation (HTML code). Else it will be a big unmaintainable mess soon (or maybe it already is).
<?php
include "db_connect.php";
{
?>
what's with the random bracket?
Never Mind got the answer. The answer is just to simply add an echo '</select>' above the $array_value = $_POST['table_choice'];. The answer is simply to end select with /select.
Thanks for the extra tips guys.