I'm using a while loop and mysql_fetch_array to display info on a page from a database. How can I give a variable name to certain radio button elements that are echoed on the page, and then use those variable names for the radio buttons as $_POST variables when the form is submitted?
Here is the code:
session_start();
include 'acdb.php';
$prodid = $_SESSION['prodid'];
$e = "SELECT * FROM Images WHERE product_id=$prodid AND active='yes'";
$e_result = mysql_query($e,$connection) or die ('Could not get the list of all Images for this Product and Service');
$amount = mysql_num_rows($e_result);
while ($e_data = mysql_fetch_array($e_result)) {
echo "<img src='images/thumbnails/" .$e_data[1]. "' border='0'>";
echo "<label class='sel-photo'>DISPLAY PICTURE:</label> <input type='radio' name='{radio" .$e_data[0]. "}' value='1'>";
echo "<br>";
echo "<label class='sel-photo'>DO NOT DISPLAY PICTURE:</label> <input type='radio' name='{radio" .$e_data[0]. "}' value='0' checked>";
}
You will get the result you are after by doing this
echo "<label class='sel-photo'>DISPLAY PICTURE:</label> <input type='radio' name='radio" .$e_data[0]. "' value='1'>";
So assuming $e_data[0] = 'xxx' you would get html of
name='radioxxx'
PS. Its best, especially when using SELECT * to use the form $e_data['fieldname']. This is because the columns will be returned in the order they were created on the table when using *. If you/someone else decides to reorganise the table columns at a later date, they will be returned in a different order and $e_data[0] may now point to a different column.
Related
Using php I have manage to search and display the data i need. Now I wish for the user to be able to select a option from a drop down menu and click update. Now when I try this it doesn't update the data for some reason. Are you able to notice any errors in the code below? I have included small bits of relevant code from the php file. I'm using the 'value=1' so that when I click update the query updates using the number rather than the text as i want to update a different field than the output field. Any ideas?
if (isset($_POST['update'])) { //once the update is click this updates the gametable with the adjusted information
$updatequery = "
UPDATE
GameTable
SET
GameID='$_POST[gameid]',
GameName='$_POST[gamename]',
PubID='$_POST[Publisher]',
TimePeriodID='$_POST[TimePeriod]',
SettingID='$_POST[Setting]', //the field i want to update using the value of the named select option
MoodID='$_POST[Mood]',
GameWeaponID='$_POST[Weapon]',
GameCameraAngleID='$_POST[CameraAngle]',
GamePlayerTypeID='$_POST[PlayerType]',
GameDescription='$_POST[Description]'
WHERE
GameID='$_POST[gameid]'";
mysqli_query($dbcon, $updatequery);
echo "Record successfully updated";
};
//query that fetches data from a database and outputs.
while ($row5 = mysqli_fetch_array($result5)) {
echo "<tr> <th> Setting ID</th> </tr>";
echo "<td><select class='text-black input-button-rounded' name='Setting'>";
//the output is a different field to the one I want to update so that's why I want to use the value.
echo "<option disabled selected>" . $row5['SettingName'] . "</option>";
echo "<option class='text-black' type='text' value=1>Western</option> ";
echo "<option class='text-black' type='text' value=2>Space</option>";
echo "<option class='text-black' type='text' value=3>City</option>";
echo "<option class='text-black' type='text' value=4>Sea</option>";
echo "<option class='text-black' type='text' value=5>Apocalypse</option>";
echo "</select></td><br>";
//update button
echo "<td>" . "<input class=text-black input-button-rounded type=submit name=update value=Update" . " </td>";
I think your problem is that your select and submit button need to be wrapped in a <form> element, so that when the "Update" button is clicked, it POSTs the Setting data as well.
A few other things to note:
All the quotes for the values of the HTML attributes are missing from the line which has your button code. Also the quotes for the array keys of $_POST in your SQL statement e.g. you wrote$_POST[Mood] rather than $_POST['Mood'] Why is that?
You don't need type="text" for the option tags.
If you really want to build a secure website/app you shouldn't be using raw SQL statements. Rather, make use of either PDO or MySQLi prepared statements.
I'm trying to create a very easy stock managing system. I'm able to show all the items in my table 'parts' and i'm showing the amount in a textbox. However, when i change the value from, for example, 0 to 5 in the textbox and i press my submit button, it doesn't update the stock.
Below is my code, i don't have alot of experience with update querys but i've read about it on php.net, obviously.
<?php
echo "<table width=\"800\" class=\"nieuws\">";
$db=mysqli_connect("localhost","root","","lichtwinkel");
$p=mysqli_query($db, "SELECT * FROM parts WHERE product LIKE 1");
echo "<form method='post' action=''>";
echo "<tr><th></th><th>Onderdeel nummer</th><th>Eigenschappen</th><th>Prijs</th><th>Voorraad</th></tr>";
while ($row = mysqli_fetch_array($p)){
echo "<tr>";
echo "<td><img class='lamp' src='../css/images/".trim($row['partnr']).".png' alt='Geen afbeelding beschikbaar'></td>";
echo "<td>".$row['partnr']."</td>";
echo "<td>".$row['specs']."</td>";
echo "<td>€ ".$row['price']."</td>";
echo "<td><input type='text' id='aantal' name='aantal' value=$row[voorraad] /></td>";
echo "<td><input type='submit' id='update' name='update' value='Update' /></td>";
echo "</tr>";
}
echo "</table>";
if(isset($_POST['aantal']) && $_POST['update']) {
$y = $_POST['aantal'];
$p=mysqli_query($db, "UPDATE parts SET voorraad = '$y' WHERE partnr = $row[0]");
}
echo "</form>"
?>
Simply said, what i'm trying to achieve is the following:
Whenever i change the value displayed in the texbox, and i press my submit button, i want it to update the value in the database.
Does anyone know what i'm doing wrong? Any ideas? Articles i should read?
All help would be appreciated.
Thank you.
As i see, you were doing it wrong at all.
First you can't use form tag within more then one td element.
You were didn't close the form tag, only at end. (So if it loops 6 times, you will have 6 forms open, but one ended!).
At update, you're selecting row[0] - it's outside of loop with rows?
Even if you update it, it will show wrong results again. Update should be above selects! So it picks up newly updated value.
What to do:
First make one form for all updates.
Use your submit button to have value DATABASE_ID.
Make the name of "aantal" to "aantalDATABASE_ID".
At submit check for $_POST['update'], and use it's value (DATABASE_ID) to get input $_POST["aantal".$_POST['update']].
Do update, you have all you need.
Example:
<?php
echo "<form method='post' action=''>";
echo "<table width=\"800\" class=\"nieuws\">"
$db=mysqli_connect("localhost","root","","lichtwinkel");
if(isset($_POST['update']) && !empty($_POST['update'])) {
$y = $_POST['aantal'.$_POST['update']];
$p=mysqli_query($db, "UPDATE parts SET voorraad = '".$y."' WHERE partnr = '".$_POST['update']."'");
}
$p=mysqli_query($db, "SELECT * FROM parts WHERE product LIKE 1");
echo "<tr><th></th><th>Onderdeel nummer</th><th>Eigenschappen</th><th>Prijs</th><th>Voorraad</th></tr>";
while ($row = mysqli_fetch_array($p)){
echo "<tr>";
echo "<td><img class='lamp' src='../css/images/".trim($row['partnr']).".png' alt='Geen afbeelding beschikbaar'></td>";
echo "<td>".$row['partnr']."</td>";
echo "<td>".$row['specs']."</td>";
echo "<td>€ ".$row['price']."</td>";
echo "<td><input type='text' id='aantal' name='aantal".$row[0]."' value='".$row[voorraad]."' /></td>";
echo "<td><input type='submit' id='update' name='update' value='".$row[0]."' /></td>";
echo "</tr>";
}
echo "</table>";
echo '</form>';
?>
After all, take care about SQL Injections. "aantal" value is user input. As the submit value can be changed.
I'm making a quiz for my students. I would like to make it in such a way that you can only see question 2 after you solved question 1 (and so on).
My current idea is to make a web page for every question with a form on it:
<FORM action="test.php" method="post">
<I>12 is the right answer:</I>
<INPUT TYPE="text" NAME="name" SIZE="20" MAXLENGTH="30"><BR>
<INPUT TYPE="submit" VALUE="send">
</FORM>
And afterwards, I try to redirect from test.php to next.php whenever the answer is 12 and to current.php when the answer is not 12. Though, I am not able to make this work. Can anyone help me?
Have not written php code for a while now but will try to guide you.
No, you should not create a web page for each question. That is not a scalable approach. Imagine if you have to store 1000 questions over time,period.
Instead use dynamic page loading concept in php. Here what you should be doing:
1.Create a table in whichever database you are using with fields like
Id,question,option1,option2,option3,option4,correctAnswer
Create a php page like quiz.php which reads the question based on questionId stored in the session variable.
Lets say you show the first question in front page, displad the options and showed a submit button.
When the user clicks submit button what should happen is that the same quiz.php page will get called courtsy <form action="quiz.php"> with the user selected answer.
You can then check for the correct answer in php file since you have the correct answer stored in a variable which stores the database fetched result of first question, and if that is correct answer you can update the session with id of next question (increment by 1 or any other mechanism) and query the database table for that question id .
Your html should be written in such a way away which reads the current value stored in $row variable, which stores the result of the query w.r.t to questionId stored in session.
little bit of the code :
quiz.php file:
<?php
$con=mysql_connect($dbserver,$dbusername,$dbpassword);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname, $con);
// Check user answer for previous question
if (isset($_POST['submit'])) {
if(isset($_SESSION['question_id'])){
$previous_question_id = (int) $_POST['question_id'];
// Query database
$getQuestion = "SELECT * from questions_table where id =
$previous_question_id";
$resultOfQuestion = mysqli_query($conn, $getQuestion);
$correct = $row_get_question['correctAnswer'];
$selected_radio = $_POST['answer'];
if ($selected_radio == $correct)
echo "THAT ANSWER IS CORRECT";
$_SESSION['question_id'] = $previous_question_id +1;
$getQuestion = "SELECT * from questions_table where
(id=".$_SESSION['question_id'].")";
$resultOfQuestion = mysqli_query($conn, $getQuestion);
else
echo "THAT ANSWER IS WRONG!";
}
}
if(!isset($_SESSION['question_id'])) {
$_SESSION['question_id']="0";
$getQuestion = mysql_query("SELECT * FROM questions WHERE
(id=".$_SESSION['question_id'].")";
$resultOfQuestion = mysqli_query($conn, $getQuestion);
}
echo "<form action='quiz.php' method='post'>";
while($row = mysql_fetch_array($resultOfQuestion)){
echo " <b>" . $row['question'] . "</b>";
echo "<input type='radio' value='' name='answer' checked />";
echo $row['option1']; echo "<br />";
echo "<input type='radio' value='' name='answer' />";
echo $row['option2'];echo "<br />";
echo "<input type='radio' value='' name='answer' />";
echo $row['option3'];echo "<br />";
echo "<input type='radio' value='' name='answer' />";
echo $row['option4'];echo "<br />";
echo "<input type='submit' name='next' value='next' />";
}
I've written this code for a user to edit one row and update it in MySQL, but it always posts the last row no matter which row you have selected (there are 3 rows).
What's the problem?
<?php include("includes/db_connection.php"); ?>
<?php
global $connection;
$sid="s5";
/**select all salesman from store 5**/
$sql ="SELECT * FROM employees WHERE e_type='Salesperson' AND store_assigned='".$sid."';";
/**get the result and put into table, which can be edited by user**/
$result = mysql_query($sql);
echo "<form method='post' action='update_salesman.php'>";
echo "<table border='1'><tr><th>Employee ID</th><th>Name</th><th>Address</th><th>Email</th><th>Job Title</th><th>Store</th><th>Salary</th></tr>";
while ($row = mysql_fetch_assoc($result)) {
echo "<tr><td><input type='text' name='eid' value='".$row['eid']."' readonly /></td>";
echo "<td><input type='text' name='e_name' value='".$row['e_name']."' /></td>";
echo "<td><input type='text' name='e_addr' value='".$row['e_addr']."' /></td>";
echo "<td><input type='text' name='e_email' value='".$row['e_email']."' /></td>";
echo "<td><input type='text' name='e_type' value='".$row['e_type']."' /></td>";
echo "<td><input type='text' name='store_assigned' value='".$row['store_assigned']."'/></td>";
echo "<td><input type='text' name='e_salary' value='".$row['e_salary']."' /></td>";
echo "<td><input type ='submit' value='update' /></td></tr>";
}
echo "</table>";
echo "</form>";
print($sql);
?>
Get the posted data, and update it in MySQL database:
<?php include("includes/db_connection.php"); ?>
<?php
$eid = $_POST['eid'];
$ename = $_POST['e_name'];
$eaddr = $_POST['e_addr'];
$eemail = $_POST['e_email'];
$etype = $_POST['e_type'];
$estore = $_POST['store_assigned'];
$esalary = $_POST['e_salary'];
$sql = "UPDATE employees SET e_name='" . $ename . "', e_addr='" . $eaddr . "', e_email='" . $eemail . "', e_type='" . $etype . "', store_assigned='" . $estore . "', e_salary='" . $esalary . "' WHERE eid='" . $eid . "' ;";
$result = mysql_query($sql);
print("</br>" . $sql);
?>
The result is always this:
UPDATE employees SET e_name='Norah ', e_addr='111 Melwood,PA', e_email='anorahm#gmiil.com', e_type='Salesperson', store_assigned='s5', e_salary='4000.00' WHERE eid='e334' ;
Your problem is twofold. First, when generating the HTML code, you use a while loop to echo the fields. Note that the names of these fields are the same every time the loop runs. (You can see this in the generated HTML (source code). Note that on submitting, one one of the multiple same-named fields will be posted.
Second, in the PHP form handler code, you read the post data and then do one update query, while you may want to update more than one field.
The easiest way to solve this is to make sure that the field names in the HTML form are different for each of the rows, and to use a loop structure when updating the sql table such that there's an update for each row.
even though it may appear fine on the html side, it's clear what's happening on the server side when it gets the form
When the server gets the form it will only see the last record because each record will overwrite the values that come before it resulting in only getting the data from the last record
What you can do is give each set of values its own form (Wouldn't suggest). But with this method, you can leave your code almost as is, just move the form tags into the while loop. OR write the input names as e_name[], etc.
This way it will be passed as an array to the server and you can loop through to get all your values
On the server end, to get the array you would do something like
$e_names = $_POST['e_name']; //Value will be an array
I have a working code where the result of a query is passed to another page. The query comes with only a single answer which is what I want. What I want however is for the field I am passing to be hidden. There is also an option field with multiple answers being passed at the same time, which has to remain. So what I'm asking is for a proper way to pas the hidden field so I don't get all the errors when I do it the way I was trying (ie The wrong way)
Here's the working code that I have. I want the first option field to be a hidden field. Any help is appreciated
$studentquery="SELECT * from student ORDER BY ssurname";<br>
//Do Query
$studentresult = mysql_query ($studentquery);
$options="";
echo "<form action='addstudenttofamily1c.php' method='POST'>";
$familychoice = "SELECT * from hostfamily WHERE hid= '".mysql_real_escape_string($hostfamily). "'";
$resultfamilychoice = mysql_query ($familychoice);
$options2="";
echo "<select name='element_1' id='element_1'>";
while ($rowfam=mysql_fetch_array($resultfamilychoice))
{
echo "<option value='$rowfam[hid]'>$rowfam[hfsurname] $rowfam[hfmname]</option><br/>";
}
echo "</select>";
echo "<select name='element_3' id='element_3'>";
while($row=mysql_fetch_array($studentresult))
{
echo "<option value='$row[sid]'>$row[sname] $row[ssurname]</option>";
}
echo "</select><input type='submit' name='submit3' value='Replace Student'>";
echo "</form>";
echo"</td>";
echo" </tr>";
This is how you can store a hidden value for a form:
<input type="hidden" name="SomeHiddenField" val="ValueOfThisField" />
To which you could code it in PHP to make it dynamic also.