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.
Related
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'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.
First off, I want to store the names of these checkboxes which are submitted, and not their values.
This is my code:
<?php
$con=mysqli_connect("localhost","root","","notifier");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM student");
echo "Enter the attendance. Please untick for 'ABSENT' students and submit";
echo "<br>";
echo "<form action=\"d.php\" method=\"post\">";
while($row = mysqli_fetch_array($result))
{
echo "<br>" .$row['classrollno'] . "   <input type=\"checkbox\" name=\"" . $row['studentid'] . "\" value=\"P\" checked>";
}
echo "<input type=\"submit\" name=\"submit\" value=\"submit\">";
echo "</form>";
?>
This code simply fetches a column of student rollnumberss from student table, prints them, and as well as prints a checkbox infront of them which is checked by default.
Names of checkboxes will be the student id (varchar, another column).
Now since All Checked checkboxes, that is the checboxes which will be submitted to next page will have same default value "P", I m not concerned about their values.
How do I store the names of these checkboxes in an array, and later on use it to perform updation in table for all these student id's?
Use the following code:
while($row = mysqli_fetch_array($result))
{
echo '<br>' .$row['classrollno'] . ' <input type="checkbox" name="studentId[]" value="' . $row['studentid'] . '" checked />';
}
Then, when you process the form, the $_POST['studentId'] variable will contain an array with all the id's.
Since the value that will probably be inserted in the db is 'P' for every student, you wouldn't need to include it in your form, but just hardcode it in your query.
Keep adding the names to an array. Its straight forward.
Declare $allStudentIds = array(); outside while loop. Then, to store in that array,
$allStudentIds[] = $row['studentid'];
Since you wanted to use these values later, you can directly store them inside a session variable:
$_SESSION['allStudentIds'][] = $row['studentid'];
In above case, $_SESSION['allStudentIds'] will be an array of all student ids selected.
Note: You need to start session using session_start() as the first line in the script after opening <?php tag.
Simply, in the fetching while loop, define an array and set each checkbox value to one of its elements then assign it as a session variable:
while($row = mysqli_fetch_array($result))
{
echo "<br>" .$row['classrollno'] . "   <input type=\"checkbox\" name=\"" . $row['studentid'] . "\" value=\"P\" checked>";
$names[] = $row['studentid'];
}
Then,
$_SESSION['names'] = $names;
Your confusion seems to stem from the fact that you are mixing the View (the name of the checkbox in HTML) and the Model/Data (which the student_id you are getting from your DB query ie. the $row = mysqli_fetch_array($result) in the while loop).
All you need to do is create an empty array (eg. $studentid_arr) before the loop and after the echo statement which is just contributing to the view (the HTML) you do some work with your data. What you want to do currently is to store the student_ids (and not the name of the checkbox) in your $studentid_arr.
That can be done with a simple array_push ($studentid_arr,$row['studentid']);
So your while loop would look like
while($row = mysqli_fetch_array($result))
{
echo "<br>" .$row['classrollno'] . "   <input type=\"checkbox\" name=\"" . $row['studentid'] . "\" value=\"P\" checked>";
array_push ($studentid_arr,$row['studentid']);
}
Now you can just POST this PHP array to your next script which is expecting these values. (which is what I assume you mean by submitting to the next page)
Sorry if this is a noob question, but I'm still getting up to speed with PHP and can't find an answer to this one.
I have a php script that queries a mySQL table and then builds an HTML table from the results. This all works just fine. As part of that script, I add a <td> to each <tr> that gives the user a chance to delete each specific record from the database, one by one, if they so choose.
To make this work, I have to be able to pass over to the php script the unique identifier of that record, which exists as one of the values. Problem is, I don't know how to pass this value.
Here is my php script that builds the HTML table:
while ($row = mysql_fetch_array($result)) {
echo
"<tr class=\"datarow\">" .
"<td id=\"id_hdr\">" . $row['id'] . "</td>" .
"<td id=\"name_hdr\">" . $row['name'] . "</td>" .
"<td id=\"btn_delete\">
<form action=\"delete_item.php\">
<input type=\"image\" src=\"images/delete.png\">
</form>
</td>" .
"</tr>";
}
So, somehow I either need to explicitly pass 'id' along with "delete_item.php" and/or find a way on the php side to capture this value in a variable. If I can accomplish that I'm home free.
EDIT: Trying to implement both suggestions below, but can't quite get there. Here is how I updated my form based on how I read those suggestions:
"<td id='btn_delete'>".
"<form action='scripts/delete_item.php'>".
"<img src='images/delete.png'>".
"<input type='hidden' id='uid' value='" . $row['id'] . "'>".
"<input type='submit' value='Submit'/>".
"</form>".
"</td>" .
Then, in delete_item.php, I have this:
$id = $_POST['uid'];
$sql = "DELETE FROM myTable WHERE id=$id";
$result = mysql_query($sql);
if (!$result) {
die("<p>Error removing item: " . mysql_error() . "</p>");
}
But when I run it, I get the error:
Error removing item: You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near '' at line 1
And one final thing: this approach gives me a button with the word 'submit' directly under my image. I'd prefer not to have this if possible.
Thanks again!
<form action=\"delete_item.php\">
<input type=\"hidden\" value=\"$row['id']\" name=\"uid\" >
<input type=\"image\" src=\"images/delete.png\">
</form>
The unique id is placed in a hidden input. You can get this value using
$_POST['uid']
But you need to submit the form
<input type=\"submit\" name=\"submit\" value=\"delete\" ">
You could use an anchor tag with parameter for id.
ie, www.example.com/delete.php?id=20
Now you could get that id on page delete.php as $_GET['id']
Using that you could delete the data from the table and return to the required page by setting up header
If you required you could use the same logic with AJAX and with out a page reload you could permenently delete that data. I would recommend AJAX