i've got 3 drop down boxes which populate each drop down from the one above but on the 3rd drop down i want it to bring back a value that i selected. The code is below
<tr>
<td width="119">Category</td>
<td width="371">
<select name="cat_id" id="cat_id" onChange="showCompany(this.value);">
<option value="">--Select--</option>
<?php
$sql="select * from category";
$sql_row=mysql_query($sql);
while($sql_res=mysql_fetch_assoc($sql_row))
{
?>
<option value="<?php echo $sql_res["id"]; ?>" <?php if($sql_res["id"] ==$_REQUEST ["cat_id"]) { echo "Selected"; } ?>><?php echo $sql_res["category_name"]; ? ></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>Company</td>
<td id="td_company">
<select name="company_id" id="company_id">;
<option value="">--Select--</option>
<?php
$sql="select * from company where cat_id='$_REQUEST[cat_id]'";
$sql_row=mysql_query($sql);
while($sql_res=mysql_fetch_assoc($sql_row))
{
?>
<option value="<?php echo $sql_res["id"]; ?>"><?php echo $sql_res["company_name"]; ?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>Item</td>
<td id="td_item">
<select name="item_id" id="item_id">
<option value="">--Select--</option>
<?php
$sql="select * from item where comp_id='$_REQUEST[cat_id]'";
$sql_row=mysql_query($sql);
while($sql_res=mysql_fetch_assoc($sql_row))
{
?>
<option value="<?php echo $sql_res["id"]; ?>"><?php echo $sql_res["item_name"]; ?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>Price</td>
<td id="td_item">
<?php
$sql="select unit_cost from item where comp_id='$_REQUEST[cat_id]'";
$sql_row=mysql_query($sql);
while($sql_res=mysql_fetch_assoc($sql_row))
{
echo "<td>" . "£" . $sql_res['unit_cost'] . "</td>";
}
?>
</td>
</tr>
<tr>
</tr>
</table>
</form>
so basically i want it to bring back the price from the option i selected, at the moment its bringing back all prices.
e.g. first drop down i select cellings then the company drop down i select Access Panels then 3rd drop down they is 3 items (Arm Strong, Track and Screw) and it brings back all 3 prices where i want to be able to select one and only bring back that price. any ideas?
First off you shouldn't be using mysql_* functions, they're deprecated. Look into either mysqli or PDO. Second, you have a vulnerability in your code where you are inserting $_REQUEST straight into your SQL. That's called SQL Injection. You should probably do some reading on it.
With all that in mind the problem is your query is trying to select all of the items where company id = category id. This is your query:
$sql="select * from item where comp_id='$_REQUEST[cat_id]'";
Notice the comp_id='$_REQUEST[cat_id]' should it instead be something like comp_id = $_REQUEST[comp_id]'?
Related
This question already has an answer here:
Post form and update multiple rows with mysql
(1 answer)
Closed 3 days ago.
Given this form, shown as a table:
<form action="multi.php" name="multi[]" method="POST" class="forms">
<table class="table-hovered">
<tr>
<th class="text-left highlight">attività svolta</th>
<th class="text-left highlight">categoria</th>
</tr>
<?php
foreach ($_POST['item'] as $k => $v)
{
$q_item = "SELECT * FROM eventi WHERE id = '".$v."'";
$qu_item = mysql_query($q_item);
while($res = mysql_fetch_array($qu_item))
{
?>
<tr>
<td><?php echo $res['descrizione'];?></td>
<td>
<select name="categoria">
<option value="<?php echo $res['categoria'];?>" selected><?php echo $res['categoria'];?>
<option value="80"> 80
<option value="40"> 40
<option value="70"> 70
</select>
</td>
<input type="hidden" name="idd" value="<?php echo $res['id'];?>">
</tr>
<?php
}
}
?>
</table>
<input type="submit" name="submit" value="modify" />
</form>
I am trying to edit multiple entries, using the code below:
<?php
$utente = $_SESSION["username"];
$id = $_POST["idd"];
$categoria = $_POST["categoria"];
if (!$id or !$categoria){
echo "Error";
}
else
if ($categoria!=='80' && $categoria!=='40' && $categoria!=='70'){
echo "Error";
}
else{
$sql="UPDATE eventi SET categoria='$categoria' WHERE id='$id'";
$update=mysql_query($sql);
echo "Entry modified correctly";
}
?>
As you see, this code changes just one item. I have tried making it recursive. Maybe using a "foreach" is the way to go.
Any hints are appreciated. And sorry for using an old version of PHP (I haven't switched to version 7 yet).
As you have same names for both input and select the last value of each of them overwrites previous values. For passing multiple values in inputs with same names - use [] notation:
<select name="categoria[]">
<option value="<?php echo $res['categoria'];?>" selected><?php echo $res['categoria'];?>
<option value="80"> 80
<option value="40"> 40
<option value="70"> 70
</select>
<input type="hidden" name="idd[]" value="<?php echo $res['id'];?>">
After that - check your $_POST values with print_r - you will see that
$_POST[categoria] and $_POST[idd] are arrays and you can iterate over them with for or foreach.
Btw, inserting an <input> right after </td> produces invalid html.
There's no need to create any hidden input element in the first place, you just have to change the name attribute of <select> element in the following way,
name="categoria[<?php echo $res['id'] ?>]"
So your code should be like this,
<form action="multi.php" name="multi[]" method="POST" class="forms">
<table class="table-hovered">
<tr>
<th class="text-left highlight">attività svolta</th>
<th class="text-left highlight">categoria</th>
</tr>
<?php
foreach ($_POST['item'] as $k => $v){
$q_item = "SELECT * FROM eventi WHERE id = '".$v."'";
$qu_item = mysql_query($q_item);
while($res = mysql_fetch_array($qu_item)){
?>
<tr>
<td><?php echo $res['descrizione'];?></td>
<td>
<select name="categoria[<?php echo $res['id'] ?>]">
<option value="<?php echo $res['categoria'];?>" selected><?php echo $res['categoria'];?>
<option value="80"> 80
<option value="40"> 40
<option value="70"> 70
</select>
</td>
</tr>
<?php
}
}
?>
</table>
<input type="submit" name="submit" value="modify" />
</form>
And this is how you can process your form to perform UPDATE operation,
foreach($_POST['categoria'] as $id => $categoria){
$sql="UPDATE eventi SET categoria='". $categoria . "' WHERE id='" . $id . "'";
// execute your query
}
Note: If you want to see the complete array structure, do var_dump($_POST);
Hello to all!
I am new to coding and will be studding in class in next September. Looking forward to that....:-)
I am making a modification page for my data base. It's composed of inputs and a drop down list to modify the content of the DB. At least for now...till I learn more.
I am coding for my self and was wondering if the following was the correct way to do this? In my mind it's not, because the inner query gets executed every time the outer loop goes through...But it work!?!?
It's the only way I could find to make the inner FOREACH loop ($familylist) work with the Mysql query. If the query for the inner loop is outside the outer loop ($plantList)...it does not work. The first drop down list gets populated with the content but the following rows do not, at least only with the first option, it does not get populated with the content from the query.
Any help is welcome and appreciated!
<?php //more code here....
$plantQuery = "SELECT id, genre, espece, famille FROM plante ORDER BY genre";
$plantList = $dbconnect->query ($plantQuery);
?>
<table>
<thead>
<tr>
<th>ID</th>
<th>GENRE</th>
<th>ESPÈCE</th>
<th>FAMILLE</th>
</tr>
</thead>
<tbody>
<?php foreach ($plantList->fetchAll(PDO::FETCH_ASSOC) as $plant) : ?>
<form method="post">
<tr>
<td><input name="id" value="<?php echo $plant["id"] ;?>" readonly></td>
<td><input name="genre" value="<?php echo $plant["genre"] ;?>"></td>
<td><input name="espece" value="<?php echo $plant["espece"] ;?>"></td>
<td><select name="familleList" >
<option value="0" >Choisir une famille</option>
<?php
$familyQuery = "SELECT id, famille FROM famille ORDER BY id ASC";
$familyList = $dbconnect->query ($familyQuery);
?>
<?php foreach ($familyList->fetchAll(PDO::FETCH_ASSOC) as $family):?>
<option value="<?php echo $family["id"] ;?>" <?php if ($plant["famille"] <> 0 && $plant["famille"] == $family["id"] ) {echo "selected"; }?>><?php echo $family["id"] . " - " . $family["famille"] ;?></option>
<?php endforeach ;?>
</select>
</td>
<td><button name="modifier" type="submit">Modifier</button></td>
<td><button name="supprimer" type="submit">Supprimer</button></td>
</tr>
</form>
<?php endforeach ;?>
</tbody>
</table>
Instead of calling the database multiple times, for the same data inside the loop. A simple solution would be to call it once. At the top of the file do something like this.
$families = $familyList->fetchAll(PDO::FETCH_ASSOC);
And then you can chance your foreach loop to.
foreach ($families as $family)
This will make the query execute once, and therefor avoid multiple queries to the database. And loop over the already fetched data in the loops.
You were right. What you are doing is very inefficient. Database queries tend to be something that really create a bottleneck, so minimizing them is generally the best thing to do.
Since you are not passing any values into the second query, just take it out of the loop:
<?php //more code here....
$plantQuery = "SELECT id, genre, espece, famille FROM plante ORDER BY genre";
$plantList = $dbconnect->query ($plantQuery);
$familyQuery = "SELECT id, famille FROM famille ORDER BY id ASC";
$familyList = $dbconnect->query ($familyQuery);
?>
<table>
<thead>
<tr>
<th>ID</th>
<th>GENRE</th>
<th>ESPÈCE</th>
<th>FAMILLE</th>
</tr>
</thead>
<tbody>
<?php foreach ($plantList->fetchAll(PDO::FETCH_ASSOC) as $plant) : ?>
<form method="post">
<tr>
<td><input name="id" value="<?php echo $plant["id"] ;?>" readonly></td>
<td><input name="genre" value="<?php echo $plant["genre"] ;?>"></td>
<td><input name="espece" value="<?php echo $plant["espece"] ;?>"></td>
<td><select name="familleList" >
<option value="0" >Choisir une famille</option>
<?php
?>
<?php foreach ($familyList as $family):?>
<option value="<?php echo $family["id"] ;?>" <?php if ($plant["famille"] <> 0 && $plant["famille"] == $family["id"] ) {echo "selected"; }?>><?php echo $family["id"] . " - " . $family["famille"] ;?></option>
<?php endforeach ;?>
</select>
</td>
<td><button name="modifier" type="submit">Modifier</button></td>
<td><button name="supprimer" type="submit">Supprimer</button></td>
</tr>
</form>
<?php endforeach ;?>
</tbody>
</table>
Even though this is not the case here, whenever you are executing the same query multiple times only changing the variables, you can use prepared statements:
$familyQuery = $dbconnect->prepare("SELECT * FROM famille
WHERE something = :s
AND somethingelse = :se ORDER BY id ASC");
foreach ($values as $val) {
$familyQuery->bindValue('s', $val);
$familyQuery->bindValue('se', somefunction($val));
$familyQuery->execute();
$results = $familyQuery->fetchAll();
// Do something with the results
}
This way the query is first sent to the DB server and the values are all sent separately.
I'm going to construct a table to let my user enter their SPM result then my system will filter and show them which course is eligible to apply.
I've tried to make 10 rows in a table and each row consisted of 2 <select>, one is SPM subject and another one is the grade they obtained. The options of Subject and Grade were fetch from my database.
Here is my coding for my table:
<?php
$result = mysql_query("SELECT * FROM spm_subject");
$result2 = mysql_query("SELECT * FROM spm_grade");
?>
<table class="p1" bgcolor="#FFFFCC" bordercolor="#000000" align="center" width="771" border="2">
<tr>
<td><div align="center"><strong>No.</strong></div></td>
<td><div align="center"><strong>Subject Name</strong></div></td>
<td><div align="center"><strong>Grade</strong></div></td>
</tr>
<form action="checkresult2.php">
<?php
for($i=1; $i<=10; $i++)
{?>
<tr>
<td width="44"><div align="center"><?php echo $i; ?></div></td>
<td width="601">
<select>
<option value="">--- Please choose a subject ---</option>
<?php
while($s = mysql_fetch_assoc($result))
{?>
<option name="subj"><?php echo $s["name"]; ?></option>
<?php } ?>
</select>
</td>
<td width="104"><div align="center">
<select>
<option value=""> </option>
<?php
while($g = mysql_fetch_assoc($result2))
{?>
<option name="grad"><?php echo $g["grade"]; ?></option>
<?php } ?>
</select>
</div>
</td>
</tr>
<?php } ?>
<tr>
<td colspan="3">
<div align="center">
<input type="submit" value="Submit">
</div>
</td>
</tr>
</form>
</table>
The table was constructed but only the FIRST ROW able to display data from the both database tables inside the both <select>.
Any solution to solve this problem?
1) Remove <form> inside <table>. Because, A form is not allowed to be a child element of a table, tbody or tr. You can have an entire table inside a form. You can have a form inside a table cell. You cannot have part of a table inside a form. For more info, click this
2) <option> don't have name attribute. Check here
3) Give name to <select></select> . Check here
4) Since, multiple values are being submitted to checkresult2.php page, you have to define name as name="subj[]" and name="grad[]" as array type.
5) An Alternative way for showing data in rest 9 rows is : before while loop give that query there itself, like below.
Updated Code.
<form action="checkresult2.php">
<table class="p1" bgcolor="#FFFFCC" bordercolor="#000000" align="center" width="771" border="2">
<tr>
<td><div align="center"><strong>No.</strong></div></td>
<td><div align="center"><strong>Subject Name</strong></div></td>
<td><div align="center"><strong>Grade</strong></div></td>
</tr>
<?php
for($i=1; $i<=10; $i++)
{?>
<tr>
<td width="44"><div align="center"><?php echo $i; ?></div></td>
<td width="601">
<select name="subj[]">
<option value="">--- Please choose a subject ---</option>
<?php
$result = mysql_query("SELECT * FROM spm_subject");
while($s = mysql_fetch_assoc($result))
{?>
<option value="<?php echo $s['name']; ?>"><?php echo $s["name"]; ?></option>
<?php } ?>
</select>
</td>
<td width="104"><div align="center">
<select name="grad[]">
<option value=""> </option>
<?php
$result2 = mysql_query("SELECT * FROM spm_grade");
while($g = mysql_fetch_assoc($result2))
{?>
<option value="<?php echo $g['grade']; ?>"><?php echo $g["grade"]; ?></option>
<?php } ?>
</select>
</div>
</td>
</tr>
<?php }?>
<tr>
<td colspan="3">
<div align="center">
<input type="submit" value="Submit">
</div>
</td>
</tr>
</table>
</form>
[NOTE: mysql_ is deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Use MySQLi or PDO_MySQL extension should be used.]
You have to preprocess the query populating two arrays:
$names = $grades = array();
for( $i=1; $i<=10; $i++ )
{
$names[] = mysql_fetch_assoc( $result );
$grades[] = mysql_fetch_assoc( $result2 );
}
Then, in our code:
<?php foreach( $names as $key => $name ) {?>
<option name="subj"><?php echo $name['name']; ?></option>
<?php } ?>
and
<?php foreach( $grades as $key => $grade ) {?>
<option name="grad"><?php echo $grade['grade']; ?></option>
<?php } ?>
mysql_fetch_assoc fetch the current row from results and then ‘go’ to next row, so when the first for loop is terminate, the cursor has reached the end of results and - in next for loops, there is nothing to fetch.
Please note:
mysql_ syntax was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
Im trying to display my database value into the textbox using drop down menu. which is i did and it is displaying. the problem here is that when i choose an item in the drop down list, it goes back to the first choice or last choice, the explanation i got was, my loop is selecting all of the items in the field causing the drop down menu to go back to the first choice when i click on other items. can you help me with the code on how to stop going back to the first choice when i select other options. Here is my whole code. i also use functions.
home.php
<?php
session_start();
include('dbconnect.php');
include('functions.php');
if(isset($_POST['brandname'])){
$id = $_POST['brandname'];
$result = mysql_query("SELECT * FROM tblstore WHERE brandname = '$id'");
while($row = mysql_fetch_array($result)){
$price = $row['price'];
$stocks = $row['stocks'];
}
}
?>
<html>
<body>
<form method="POST" name="">
<table align="center">
<tr>
<td>Choose here:</td>
<td>
<select name = "brandname" onchange = "this.form.submit()">
<?php dropdown() ?>
</select>
</td>
</tr>
<tr>
<td>Quantity:</td>
<td><input type="text" name="qty" id="qty" value="" /></td>
</tr>
<tr>
<td>Price:</td>
<td><input type="text" name="price" id="price" value="<?php echo $price ?>" disabled/></td>
</tr>
<tr>
<td>Stocks:</td>
<td><input type="text" name="stocks" id="stocks" value="<?php echo $stocks ?>" disabled/></td>
</tr>
<tr>
<td>Total:</td>
<td><input type="text" name="total" id="total" disabled/></td>
</tr>
<tr>
<td></td>
</tr>
</table>
</form>
<div align = "center">
hi' <?php echo $userRow['username']; ?> Sign Out
</div>
</body>
</html>
functions.php
<?php
function dropdown(){
$all = mysql_query("SELECT * FROM tblstore");
while($row = mysql_fetch_array($all)){
echo "<option value = '".$row['brandname']."' selected='selected'>" .$row['brandname'] . "</option>";
}
}
feel free to edit the whole code.. im a beginner in php and learning my way to it. thanks
Can add the multiple option if you need to select multiple
<select name="brandname" multiple>
<option value="Select">Select</option>
<?php
do {
?>
<option value="<?php echo $row['brandname']?>"> <?php echo $row['brandname'] ?></option>
<?php
} while ($row = mysql_fetch_assoc($all));
?>
</select>
When I press the Submit Button the Variable "rating" will only passed from the last line. The others are simply empty.
<form method="POST" action="<?php echo $_SERVER["PHP_SELF"]; ?>" enctype="multipart/form-data">
<table width="800" border="0" align="center" class="zui-table">
<thead>
<tr>
<td colspan="4">
</td>
</tr>
<tr>
<th width="96">Kategorie</th>
<th width="177">Unterkategorie</th>
<th width="299">Beitrag</th>
<th width="210"><? if ($rolle == '1') { echo 'Bewertung'; } elseif ($rolle== '9') { echo 'Freischalten';} else { echo 'Status';} ?></th>
<? while ($show = mysql_fetch_array($abfrage)) { ?>
</tr>
</thead>
<tbody>
<tr>
<td><? echo $show['category']; ?></td>
<td><? echo $show['subcategory']; ?></td>
<td><img src="timthumb.php?src=<?php echo $show['url'] ?>&w=300&h=150" alt="resized image" BORDER="2"/> </td>
<td><? if ($rolle == '1') { ?>
<select name="rating" class="style28" style="width: 120px" id="rating">
<option value="0">0</option>
<option value="5">5</option>
<option value="15">15</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
<option value="35">35</option>
<option value="40">40</option>
<option value="45">45</option>
<option value="50">50</option>
<option value="55">55</option>
<option value="60">60</option>
<option value="65">65</option>
<option value="70">70</option>
<option value="75">75</option>
<option value="80">80</option>
<option value="85">85</option>
<option value="90">90</option>
<option value="95">95</option>
<option value="100">100</option>
</select> <? echo '<button type="submit" value="' . $show['id']. '" name="submit">Bewerten?</button>'; }
elseif ($rolle == 9) {
echo '<button type="freigeben" value="' . $show['id']. '" name="freigeben">Freigeben?</button>';
}?></td>
</tr>
</tbody>
<? }
}?>
</table>
Only the "rating" in the last line will be passed to
if (isset($_POST['submit'])) {
echo $_POST['rating'];
echo $_POST['submit'];
//mysql_query("SET CHARACTER SET 'utf8'");
$db = mysql_connect("localhost", "xx", "xx");
mysql_select_db("cx",$db);
//Rating eingeben
$sql = "UPDATE wp_awa_upload SET count = count + '$_POST[rating]' WHERE id = '$_POST[submit]'";
$result = mysql_query($sql,$db);
//Session eintragen
$sql_insert = "INSERT into wp_awa_session (upload_id, user_id) VALUES('$_POST[submit]', '$_SESSION[id]')";
$result = mysql_query($sql_insert,$db);
echo $sql_insert;
echo $sql;
}
All the lines will be displayed, but when I press on the Submit button, then the variable from the rating dropdown will only be passed, when the button of the last line has been pressed.
Thanks for any help!
Kind Regards,
Stefan
If I understand what you try to achieve, you want the rating variable to contain the rating that corresponds to the button that was pressed. But if you think about it, there's no way for the browser to figure out which drop down the button corresponds to. It makes sense for you (because they appear to be next to each other), but HTML has no concept of "being next to each other", from perspective of HTML you have multiple drop downs, for some reason all with the same name, and multiple buttons. When you press one of the buttons, it needs to decide which value to send as the rating. It chooses to use the last one, because it has no way to guess better.
The simplest solution for you would be to actually make each drop down and a button to be its own form. Currently you have one huge form (see the <form> tag at the beginning of your script). Instead, open the form at the beginning of your while loop body and close at the end, along the lines of
<? while ($show = mysql_fetch_array($abfrage)) { ?>
</tr> <form method="POST" action="<?php echo $_SERVER["PHP_SELF"]; ?>" enctype="multipart/form-data">
...
This way the browser can figure out which drop down corresponds to which button, because for each button there's only one drop down in the corresponding form.