I have a form with checkboxes which are used to select data from mysql. I also would like to have the checkboxes to stay checked if the user has done so. In addition to that, those checkboxes are generated from a mysql select. Each user has different checkboxes based on their permission levels etc.
So I got this code working:
<form method="post" id="someselect">
<?php
function checked() {
if (in_array("somestring", $_SESSION['specificvalue'])) {
return "checked";
};
}
$i = 0;
while ($row = $result->fetch_assoc()) {
echo "<input id='specificvalue' type='checkbox' " . checked() . " name='specificvalue[]' value='" . $row['specificvalue'] . "'>" . $row['longvalue'] . "<br>";
};
mysqli_close($con);
//$_SESSION['specificvalue']=implode("','",$specificvalue);
$_SESSION['specificvalue'] = $specificvalue;
?>
<input type="submit" value="Submit">
</p>
</form>
It works, generates user specific checkboxes and the function checked() also works with the exeption that instead in_array("somestring", $_SESSION['subunit']) , I would like to use in_array($row['subunit'], $_SESSION['subunit']), which simply does not work. I am to noob to understand why or come up with a better solution. The point of this would be to generate checkbox list and already check the boxes that have been stored in session variable before.
At the moment, with this working code. If I have the list of checkboxes and I check the box with specificvalue "somestring", all the checkboxes will be checked when the checkbox form is generated.
I think I would be able to use jquery for that but google gives me different kinds of solutions which cannot be used in mine. I also cannot manually write the checkboxes because there are ca 70 of them all together and they vary in time. I would like to get them autopopulated when the mysql database is updated.
The reason why you can't use in_array($row['subunit'], $_SESSION['subunit']) in your function is that $row['subunit'] doesn't exist in the scope of the function, it's defined out of it. What you can do, is pass the value of the checkbox when you call the checked() function for the specific row. So, that would be:
function checked($value) {
if (in_array($value, $_SESSION['specificvalue'])) {
return "checked";
}
}
And the call:
while($row = $result->fetch_assoc())
{
echo "<input id='specificvalue' type='checkbox' ".checked($row['subunit']).
" name='specificvalue[]' value='". $row['specificvalue'] . "'>" .
$row['longvalue']."<br>";
}
If you want to use it with $row['subunit'] you will be unable to do that with in functions scope as $row is not accessible inside the function checked().
To be able to do this you need to define the value of $row['subunit'] in the function as argument. Like this:
function checked($valueToSearch)
{
if (in_array($valueToSearch, $_SESSION['specificvalue']))
return "checked";
}
And, you have to pass it from the loop everytime you call the check.
while($row = $result->fetch_assoc())
{
echo "<input id='specificvalue' type='checkbox' ".checked($row['subunit'])." name='specificvalue[]' value='". $row['specificvalue'] . "'>" .$row['longvalue']."<br>";
};
Hope it would help.
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.
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
I have this codes so far:
This form is generated during a query loop
while ($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['breed'] . "</td>";
if($row['neuteredOspayed']=="1"){
echo "<td>" . "neutered" . "</td>";
}else
echo "<td>" . "spayed". "</td>";
echo "<td>" . $row['priceFee'] . "</td>";
if($row['housebroken']=="1"){
echo "<td>" . "yes" . "</td>";
}else
echo "<td>" . "no". "</td>";
if($row['goodwithdogs']=="1"){
echo "<td>" . "yes" . "</td>";
}else
echo "<td>" . "no". "</td>";
if($row['goodwithcats']=="1"){
echo "<td>" . "yes" . "</td>";
}else
echo "<td>" . "no". "</td>";
echo "<td>" . $row['status'] . "</td>";
echo "</tr>";
}
echo "</table>";
Now, is there a way to put a link saying "delete" next to every result? For example next to the status field?
Here is what it's looking like:
To get this deleted I guess that I need to spot the record somehow. What I need is to take the name of the animal. For example, how can I get the value "Sparky" from the table and assign it to a variable? If I have the name I would be able to make the checks and run a query witch will delete the record.
You will have to use Javascript and AJAX.
Basically, you'll want to put a button in a cell, one per row, and when it's clicked, pass the id of the record to be deleted back to a PHP script via AJAX, then remove the record from the database. It should also hide the row when it is clicked.
I'd recommend using jQuery's .ajax(), as raw XHR is painful at best.
There is no way to do this with just PHP, because HTTP is stateless. Once your web page is loaded, the HTML and PHP parts are done, and fixed. You'll HAVE to use Javascript to make consecutive requests.
Alternatively, as bcmcfc points out, you can also just have a hyperlink to a script that will delete a record from your database.
You'd need something like this in your while loop:
echo '<td>Delete</td>';
Using the table's primary key would be better than the name though - is the name unique in the db? Assuming there is a PK and it's called id:
echo '<td>Delete</td>';
Php just is for page generation, once you have generated that table you cannot modify it.
You could, however, make a new get request, specifying a parameter with the row name to delete, you have to change your server php code to take in account this parameter, though.
The best, according to me, is using javascript: you assign a td id to each row and then you write a simple function in which you delete that row.
You have to submit the form and do this action....
<input type="submit" name="submit" value="Delete" />
After submit the form will redirected to some page. In that page you got all the posted values. In that you can delete the record by using the record id otherwise you use the name for appropriate record.
$query = "DELETE FROM table_name WHERE name='$_POST['name']'";
(or)
$query = "DELETE FROM table_name WHERE id='$_POST['id']'";
After this execution you have to redirect the URL to that page.
(or)
Delete
In this file you have to written like this...
$id = $_REQUEST['id'];
$query = "DELETE FROM table_name WHERE id='$id'";
//Add this form before the end of the while loop
<form action="#" method="post">
<input type="hidden" name="name" value="<?php echo $row['name']?>">
<input type="submit" name="delete" value="delete">
</form>
//Add this at the end of the coding
<?php
if(isset($_POST['delete']))
{
//database connection
$sql="DELETE FROM `table_name` WHERE `name`='{$_POST['name']}'";
$queryEXE=mysql_query($sql);
}
?>
You add a "elemID" attribute to each of your <tr>s and a new class that would be individual for each row (for example, elem+the id):
<tr elemId="12" class="elem12">...</tr>
Then, for the Delete link, you use AJAX to call the page that deletes the row from your DB, passing the elemID as an argument to this function:
function deleteRow(thisElemID) {
$.ajax({
url: yourURL,
data: {'elemID', thisElemID },
success: function() {
$('.elem'+thisElemID).remove();
}
});
}
More on $.ajax here.
Create another cell in your table and call ajax onclik of that button. Inside your ajax call delete the pecific row
Use a 'delete' form for each row.
The best way would be to add, for each row, a form with a submit button. Each form has a hidden field containing the id (or name, if you must) of the record to delete. Set the method of the form to 'post'.
Reasons why:
A delete link (a href) can be indexed and bookmarked easily. You
don't want pets to be deleted everytime Google drops by or a user is
browsing through their history.
A method='get' form also can cause
the url to be bookmarked and/or show up in the history. The method
with a form will work without Javascript altogether.
Apart from that,
Any solution (both forms and links) can easily be 'upgraded' to a solution with Ajax for a better user experience, but that's always an extra and no core functionality.
If you like, you can style the submit button to look like a link.
Use the post-redirect-get pattern if you implement this solution.
That is, assuming you want to actually remove the record from the database. If you just want to alter the HTML, a Javascript soliution would make more sense.
I have a list of checkboxes and save the checked values in an array. However, when someone clicks 'submit' and they get an error, all their checked boxes are forgotten. Usually I would let the script remember the checked boxes with a code like
IF checkbox value = OK { echo checked="checked"}
However, now I save it in an array and I have no idea how to do this?
<?php
$sql = "SELECT merknaam FROM merken";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo " <input type=\"checkbox\" name=\"merken[]\" value='" . $row['merknaam'] . "'> " . $row['merknaam'] . " <Br /> ";
}
?>
This is the code I use for the checkboxes. Next I display the array with this code:
$merkenstring = implode(",", $_POST['merken']);
echo $merkenstring;
Result: AC Ryan,Adidas,Agu,Cargo
I hope someone could give me a code example!
Assuming you are posting this to the same page, and $_POST['merken'] is still available after an error, use in_array() to test each checkbox's value against the current set in $_POST:
while ($row = mysql_fetch_array($result)) {
// If the current value is in the $_POST['merken'] array
// and the array has been initialized...
if (isset($_POST['merken']) && is_array($_POST['merken']) && in_array($row['merknaam'], $_POST['merken'])) {
// Set the $checked string
$checked = "checked='checked'";
}
// Otherwise $checked is an empty string
else $checked = "";
// And incorporate it into your <input> tag
echo " <input $checked type=\"checkbox\" name=\"merken[]\" value='" . $row['merknaam'] . "'> " . $row['merknaam'] . " <Br /> ";
//----------------------^^^^^^^^^^
}
If this was posted to a different script, you would (as with any post value returned to a previous script) need to store the array in $_SESSION instead and compare against $_SESSION['merken'] in your in_array() call.
Assuming $row['merknaam'] is the checkbox value, and $_POST['merken'] holds an array of checked checkbox values, then you simply need to check if the value is in the array:
if (in_array($row['merknaam'], $_POST['merken'])) {
// this checkbox should be checked
}