This is what the page looks like:
And this is what the database looks like:
Now, I had this all working with textfields. (When you press save, the text fields get inserted in the bogie_nr.
Now, I don't want to have text fields but checkboxes.
So, if I select the first 2 checkboxes, and press save. I want the database to insert the number 1 by the axle_nr 1 and 2.
Now, I want the first 2 boxes to be disabled (So you can't check them again).
Now when you select the 3rd and 4th box, and press save. I want the database to insert the number 2 by the 3rd and 4th axle_nr.
When everything is filled in, I want a button that redirects me to a new page.
How do I do this?
Code (for the checkboxes only):
<tr>
<?php
$show_axle = $database->bogies($_GET['train_id']);
foreach($show_axle as $bogiebox){ ?>
<input type='hidden' name='bogie_id[<?php echo $bogiebox['bogie_id']?>]' value='<?php echo $bogiebox['bogie_id']?>'>
<td>
<input type='checkbox' id="bogie_axle_fields" name='bogie_nr[<?php echo $bogiebox['bogie_id']?>]' placeholder = "enter bogie number">
</td>
<?php
}
?>
</tr>
Function:
function bogies($id){
$sql = "SELECT * FROM bogie WHERE train_id = :id2";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(":id2", $id, PDO::PARAM_STR);
$sth->execute();
return $sth->fetchAll();
}
EDIT:
Behind my save button is right now a page: end_result.php . Right there I have a function:
function update_bogie($id) {
$sql = "UPDATE bogie SET bogie_nr = :bogie_nr WHERE bogie_id = :bogie_id";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(':bogie_id', $id, PDO::PARAM_INT);
$sth->bindParam(":bogie_nr", $_POST['bogie_nr'][$id], PDO::PARAM_STR);
$sth->execute();
}
This updates the bogie table (Works when I change the checkboxes to textfields)
What i want now:
Checkboxes. When I check the first 2 boxes, and press save. I want the number 1 to be inserted 2 times for axle 1 and 2 in the database.
After that, I want the first 2 boxes to be disabled selected. So you can't select them once again.
EDIT:
What the ids look like:
THE ALMOST WORKING EDIT:
Okay, so the checkboxes now insert in the database. Also they are disabled when they are inserted in the database.Only a few problems now:
When i insert them for the first time. The value = 1. But on the
2nd insert it also is 1. while it should be 2.
I need to refresh the page in order to see wich select boxes are
disabled. I want this to happen immediately.
When i insert new values. the old (Disabled one) go back to NULL. But it should keep the old value.
Code i have now:
<form method='POST'>
<input type="hidden" value="true" id="y" name="y">
<div id="axle_bogie_border">
<div id="train_adjusted">
<h2>
Train
</h2>
</div>
<table id="distance_margin">
<div id="bogiebox">
<tr>
<?php
$x = 1;
foreach($show_axle as $bogiebox){ ?>
<input type='hidden' name='bogie_id[<?php echo $bogiebox['bogie_id']?>]' value='<?php echo $bogiebox['bogie_id']?>'>
<td>
<?php
if($bogiebox['bogie_nr'] == ''){
?>
<input type='checkbox' id="bogie_axle_fields" value="<?= $x ?>" name='bogie_nr[<?php echo $bogiebox['bogie_id']?>]' placeholder = "enter bogie number"></td>
<?php
}
else{
?>
<input type='checkbox' id="bogie_axle_fields" checked disabled value="<?= $x ?>" name='bogie_nr[<?php echo $bogiebox['bogie_id']?>]' placeholder = "enter bogie number"></td><?php } }
?>
</tr>
</div>
</table>
<input type='submit' id="add_train_button1" value='Save'>
<?php
if(isset($_POST['y'])){
$validbogies = false;
//validate
if(($_POST['bogie_id']) >0){
if($_POST['bogie_id'] >0){
$validbogies = true;
}elseif($_POST['bogie_id'] <= 0){
echo "Error!";
}
else{
echo "Error!." . "<br>";
}
}else{
echo "Error!" . "<br>";
}
//If valid, then insert.
if($validbogies){
foreach($_POST['bogie_id'] as $id) {
$update_axle = $database->update_bogie($id);
}
$x++;
unset($_POST['y']);
echo "Yea! Things have been moved to the database :)";
}
}
?>
</div>
</form>
And the function is still the same as the old one.
EDIT:
Here a example:
<?php
$show_axle = $database->bogies($_GET['train_id']);
// First question : When everything is filled in,
// i want a button that redirects me to a new page.
if(count($show_axle) == 4)
echo "<button type=\"button\" onClick=location.href=''>Click Me!</button>";
// Second question :
// WE display the missing checkboxes
// We will display until we found the first value axle_nr
// (i.e. the checkbox the user click last time)
// when we found we need to move to the next value of axle_nr
else
{
$j = 0;
for($i = 0; $i < 4; ++$i)
{
if($show_axle[$j]['axle_nr'] != ($i + 1))
{
echo "<input type='hidden' name='bogie_id[" .
$bogiebox['bogie_id']. "]' value='" .
$bogiebox['bogie_id'] . "'><td>";
echo "<input type='checkbox' id='bogie_axle_fields'
name='bogie_nr[" . $bogiebox['bogie_id'] .
"]' placeholder='enter bogie number'></td>";
}
else
++$j;
}
?>
That should do it (mb some mistakes on echo but algorithm is ok).
In the code behind your save button try this: (I am assuming the id's for your checkboxes are like this: bogie_nr[455]
function update_bogie($id) {
$sql = "UPDATE bogie SET bogie_nr = :bogie_nr WHERE bogie_id = :bogie_id";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(':bogie_id', $id, PDO::PARAM_INT);
if(isset($_POST['bogie_nr' . '[' . $id .']' ]){
$sth->bindParam(":bogie_nr", $_POST['bogie_nr' . '[' . $id .']' ], PDO::PARAM_STR);
}
else {
$sth->bindParam(":bogie_nr", 'NULL', PDO::PARAM_STR);
}
$sth->execute();
}
EDIT FOR CORRECT NUMBER:
Mitch to get your number try doing a query like this:
SELECT COUNT(*)
FROM bogie
WHERE train_id = #youridhere;
This will return you the amount of bogies you already have for that train, just do +1 or +2 depending on how many elements you are adding (use a counter in your for loop) and you have your correct number to insert
Related
i am trying to bulid an online attendace in php, i am fetching student list from student table, and want to put all chkboxs if checkd as present and if unchecked as absent,
i am unable to do that.
<div class="attendance">
<form accept="att.php" method="POST">
<?php
$sel_sql = "SELECT * FROM student";
$run_sql = mysqli_query($conn,$sel_sql);
while($rows = mysqli_fetch_assoc($run_sql)){
$id = $rows['id'];
echo '<input type="checkbox" name="status" value="'.$id.'" checked>'.ucfirst($rows['f_name']).'';
}
?>
<input type="submit" name="submit_attendance" value="Post Attendance">
<?php echo $msg; ?>
</form>
</div>
it shows prefect students list, but i dont know how to set insert query for all of these chkboxes
try this query to insert from another table
SELECT * INTO TABLE2 FROM student
use where condition on student table as where student.column value to select checked values
Applied same above things with checkbox input field
echo '<input type="checkbox" name="status" value="'.$id.'" 'if($row['present_field_of_database']) ? 'checked' : ''
'>'.ucfirst($rows['f_name']).'';
it's fine then updated code with your problems i hope it's work for you
<div class="attendance">
<form accept="att.php" method="POST">
<?php
$sel_sql = "SELECT * FROM student";
$run_sql = mysqli_query($conn,$sel_sql);
while($rows = mysqli_fetch_assoc($run_sql)){
$id = $rows['id'];
// if your $id value is right from $rows['id'] then
// change your student table name to the another table where available status of the student
$wh_sql = "SELECT * FROM student WHERE id=".$id;
$run_wh_sql = mysqli_query($conn, $wh_sql);
$Wh_rows = mysqli_fetch_assoc($run_wh_sql);
// add student present or absent value to the rows data
$rows['status'] = $Wh_rows['status'];
}
// set value as A or P respectively absent or present add jquery plugins for onclick event while client click on checkbox change value respectively
echo '<input type="checkbox" name="status" value="'.$rows['status'].'" 'if($rows['status'] == "A") ?'checked': '' '>'.ucfirst($rows['f_name']).' onclick= "$(this).val(this.checked ? P : A)"';
?>
<input type="submit" name="submit_attendance" value="Post Attendance">
<?php echo $msg; ?>
</form>
</div>
if (isset($_POST['send'])) {
$s_id = $_POST['status'];
$id = $_POST['student'];
if ($s_id) {
foreach ($s_id as $s) {
foreach ($id as $i) {
if (mysqli_query($conn, "INSERT INTO attendence(s_id,status) VALUES('".
mysqli_real_escape_string($conn, $s)."','".
mysqli_real_escape_string($conn, $i)."')")) {
$msg = "success";
}else{
$msg = "failed";
}
}
}
}
}
i have 3 students. when i press send it sends 9 entries. i am unable to understand how to insert all students data
This is attendance table
This is attandance table
i want to put entries like this if check box chekd it wil post p and if not it wil post a. i just need how to insert all sutdent at once quert
I have an array that is created from a mysqli query.
The array then goes through a for loop to display a table.
Within the table there is a form submit that needs to take the selected row and pass the information into a variable to be modified.
I tried to take a screenshot, but I just joined and have no rep. In theory, the user needs to be able to select Modify and the array elements for that row need to pass into text input boxes with a preset value of $row[$j][0] where $j is fixed based on the row selected to modify.
Here is what this part of the code looks like.
if (isset($_POST['Select']) &&
isset($_POST['Search']))
{
$Select = get_post($con,'Select');
$Search = get_post($con,'Search');
if ($Select == "Invalid")
{
echo "<br /><br />Please select a search catagory";
}
else if ($Search == NULL)
echo "<br /><br />Please enter search field";
else
{
$query = "SELECT * FROM table WHERE $Select LIKE '$Search%'";
$result = mysqli_query($con,$query);
if (!mysqli_query($con,$query)) {
die('Error: ' . mysqli_error($con));
}
$rows = mysqli_num_rows($result);
echo "<table id='myTable' class='tablesorter'>
<thead><tr>
<th>Modify</th>
<th>Field1</th>
<th>Field2</th>
<th>etc...</th>
</tr></thead><tbody>";
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysqli_fetch_row($result);
$modrow[$j] = $row;
echo <<<_END
<tr>
<td><form action="Lookup.php" method="post"><input type="submit" value="Modify" /><input type="hidden" name="submitted" value="$modrow[$j]"</form></td>
<td>$row[0]</td>
<td>$row[1]</td>
<td>etc...</td>
</tr><br />
_END;
}
echo "</tbody></table>";
if (isset($_POST['submitted']))
{
echo <<<_END
<form action="Lookup.php" method="post"><pre>
Field1 <input type="text" name="Field1" size="50" **value="$modrow[$j][0]"** />
...more of the same...
From what I gather, you're wanting to pass a request to the server containing some form of identifier for the row so that you may create a form for users to modify that row's data. Sorry if I misunderstood - I would ask first if I understood you correctly as a comment, but don't have enough rep.
You can use an id to submit to the server.
<button type="submit" name="modify" value="<?= $theRowsId ?>">Modify</button>
Think of the values of name and value attributes as a function/method and value being passed respectively.
Now when Modify is clicked, you can get retrieve the ID, perform a query for the ID and populate the input with the rows data.
$rowId = $_POST['modify'];
I have this code so far, which reads a simple table with 3 varchar fields:
<?php
//db connection code...
// select database
mysql_select_db($db) or die ("Unable to select database!");
// create query
$query = "SELECT * FROM Sheet1";
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
// yes
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
// yes
// print them one after another
echo "<html><body><table cellpadding=10 border=1>";
while($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row['stickerID']."</td>";
echo "<td>" .$row['stickerName']."</td>";
echo "<td>".$row['stickerSection']."</td>";
echo "<td>"?>
<form name="some form" action="editform.php" method="post">
<input type="checkbox" name="<?php echo $row['stickerID'] ?>" value=" <?php echo $row['stickerStatus'] ?> ">
<?php "</td>";
echo "</tr>";
}
echo "</table></body></html>";
echo " " ?>
<input type="submit" name="editWish" value="Edit">
</form>
<?php " ";
} else {
// no
// print status message
echo "No rows found!";
}
// free result set memory
mysql_free_result($result);
// close connection
mysql_close($connection);
?>
The database has 4 fields, 3 varchar and 1 int with current value of 0. I checked the page source code and confirmed each checkbox name is the stickerID. Now I will post this to the editform.php which I must create. What Im wondering is how should I write the update sql so that it takes into account each new value selected by the user in the form?
This is my idea, but how to I do it for every checkbox?
editform.php
<?php
//update multiple records
//UPDATE user_items SET stickerStatus = $_POST["stickerStatus"] WHERE stickerID = $_POST["stickerID"];
?>
First question: use mysql_fetch_assoc() instead of mysql_fetch_row(). That will return an associative array instead of an enumerated one.
Second question: read up on HTML forms and form handling.
The answer to the question in the comments:
// The <form> tag should only be echoed once.
echo '<form name="some form" action="editform.php" method="post">';
while($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row['stickerID']."</td>";
echo "<td>" .$row['stickerName']."</td>";
echo "<td>".$row['stickerSection']."</td>";
echo "<td>"?>
<input type="hidden" name="status_<?php echo $row['stickerID"; ?>" value="0">
<input type="checkbox" name="status_<?php echo $row['stickerID'] ?>" value="<?php echo $row['stickerStatus'] ?> ">
<?php "</td>";
echo "</tr>";
}
// You need a submit button to send the form
echo '<input type="submit">';
// Close the <form> tag
echo '</form>';
Using a hidden input with the same name as the checkbox makes sure a value for the given input name is sent to the server. The value of a checkbox that's not checked will not be sent. In that case the hidden input will be used.
You can get the submitted values in editform.php as follows:
<?php
foreach ($_POST as $field => $value) {
if (strpos($field, 'status_')) {
// Using (int) makes sure it's cast to an integer, preventing SQL injections
$stickerID = (int) str_replace('status_', '', $field);
// Again, preventing SQL injections. If the status could be a string, then use mysql_real_escape_string()
$stickerStatus = (int) $value;
// Do something with the results
}
}
Do
print_r($row)
to find out exactly how your row arrays are constructed and work from there.
For your comparison operator, use
$row[3] === 0
instead of
$row[3] == 0
This will return true if both the value and data type match rather than just the value.
0 can mean the Boolean false aswell as the numeric value 0
Actually I am very new to php.. I have a task that select records from database as checkboxes checked. When I uncheck a checkbox it should delete that particular record from my database..
My code is
<?php
if(isset($_POST['delete']))
{
$test=$_POST['test'];
$qun1=$_POST['question1'];
//DB connection
$CON=mysql_connect("localhost","root","");
mysql_select_db("Dbname");
if($qun1!=0 && $test!=0)
{
foreach($qun1 as $qunestion)
{
echo $question; //this is for testing
$query=mysql_query("delete from test_question where test_questions_id='$test' AND question_id IN ('$question') " ) or die(mysql_error());
}
if($query)
{
echo "success";
}
else
{
echo "No";
}
}
}
?>
my code is working properly but if i use NOT IN in the place of IN it is not working..why?..if unchecked the records it should be delete..i already retrieve records from database as checked fields..
My html markup:
<script>
function fun2(ts)
{
$.post("ajax2.php",{qs:ts},function(data)
{
document.getElementById('div1').innerHTML=data
})
}
</script>
<form action="somepage.php" method="post">
//dynamic selection test code
<select name="test" id="test" onChange="fun2(this.value);">
<option value="">Select Test</option> </select>
<div id="div1" > </div>
<input type="submit" name="delete" value="Delete" >
</from>
my ajax code:
<?php
$qs=$_REQUEST['qs'];
mysql_connect("localhost","root","");
mysql_select_db("advancedge");
$sql=mysql_query("select question_id from test_question where test_questions_id='$qs'");
if($sql)
{
while($rec=mysql_fetch_row($sql))
{
echo "<input type='checkbox' name='question1[]' value='$rec[0]' checked='checked' >";
}
}
?>
If I understand correctly, you want to delete as soon as the item is unchecked? To check if a checkbox is unchecked, you have to use javascript. PHP runs on the server, not the client side (you could use ajax, but I would recommend not to for this).
I would recommend, you delete whatever you want to on form submission, if you don't know how to do that,I can tell you if you post the html part up.
I would also recommend you learn PHP from a course on the internet, so you know some standards and get some good practices. (Youtube or Lynda.com)
It is an old post, but if someone end up here - this might solve the problem:
<?php
echo "<form action='' method='post'>";
echo "<input type='checkbox' id='chk_1' name='chk_1' value='First' />chk 1 </br>";
echo "<input type='checkbox' id='chk_2' name='chk_2' value='Second' />chk 2 </br>";
echo "<input type='submit' />";
echo "</form>";
$check = array();
// Set all checkboxes to 0 if unchecked
for($i = 1; $i<=2; $i++) {
$check["chk_$i"] = isset($_POST["chk_$i"]) ? 1 : 0;
}
// Output of the array
echo '<pre>';
var_export($check);
echo '</pre>';
The code will set all unchecked checkboxes to 0.
Then you have to take care of that using something like this:
<?php
if($_GET['chk_1'] == 0) {
$sql = "DELETE FROM mytable WHERE...";
}
i have a website where the admin can choose to add a certain number of bbcode tags and the corresponding html tags.
First he chooses how many tags he wants to add from a drop down select form in a for Each loop.
Depending on how many tags he chose when he clicked the submit button, the corresponding number of input tags appear in a second form, also in a for Each loop. He fills in the bbcode and html input and clicks the submit button. Normally the tags should be added to my database but in this case when he clicks submit the form disappears and nothing is added..
Here is the code :
//FIRST FORM WHERE HE DECIDES HOW MANY TAGS TO ADD
<form id='nbbalises' action='config.ini.php' method='post' accept-charset='UTF-8'>
<fieldset>
<legend>How many tags ?</legend>
<input type='hidden' name='submitted' id='submitted' value='1' />
<?php
echo '<select name="number">';
$range = range(1,50,1);
foreach ($range as $nb) {
echo "<option value='$nb'>$nb</option>";
}
echo "</select>";
?>
<input type='submit' name='Submit' value='Submit' />
</fieldset>
</form><br /> <br />
<?php
if (!(empty($_POST['number']))) {
if ($_POST['number'] >= 1 && $_POST['number']<= 50){
$number = $_POST['number'];
$range2 = range(1,$number,1);
?>
//SECOND FORM WHERE I GENERATE THE INPUT DEPENDING ON THE NUMBER CHOSEN FROM FIRST FORM
<form id='balises' action='config.ini.php' method='post' accept-charset='UTF-8'>
<fieldset>
<legend>Balises bbc : </legend>
<input type='hidden' name='submitted' id='submitted' value='1' />
<?php
foreach ($range2 as $nb2) {
echo "<label>bbcode tag $nb2 :</label>
<input type='text' size='40' name='bbc$nb2' id='bbc$nb2' maxlength='40' />
<label>html tag $nb2 :</label>
<input type='text' size='40' name='html$nb2' id='html$nb2' maxlength='40' />
<br />";
}
}
?>
<input type='submit' name='Submit2' value='Submit2' />
</fieldset>
</form>
<?php
//PROBLEM STARTS HERE, NOTHING WORKS UNDER HERE
if (isset($_POST['Submit2'])){
//CONNECT TO MY DATABASE
connectDB();
for ($i=0; $i<$number ; $i++){
if (!(empty($_POST["bbc$i"])) && (empty($_POST["html$i"])))
//FUNCTION ADDS TAGS TO DATABASE
addBbc($_POST["bbc$i"], $_POST["html$i"]);
}
mysql_close();
}
}
//MY FUNCTIONS TO ADD THE BBCODE AND HTML TO DATABASE
function connectDB(){
//connexion DB
$link = mysql_connect('127.0.0.1', 'USERNAME', 'PASSWORD');
if (!$link) {
die('Erreur de connexion: ' . mysql_error());
}
$db = mysql_select_db('1213he200967',$link) or die("N'a pu selectionner
1213he200967");
mysql_query("SET NAMES 'utf8'");
}
function addBbc($bbc, $html){
$b = mysql_real_escape_string($bbc);
$h = mysql_real_escape_string($html);
$query="INSERT INTO bbcode (BBC,HTML) VALUES ('$b','$h')";
$result = mysql_query($query) or die("error");
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
die($message);
return false;
}
else return true;
}
Thank you very much, and sorry if my code is amateur-ish, i'm only starting in php.
EDIT
Found part of my problem
$number = $_POST['number'];
$range2 = range(1,$number,1);
This goes from 1 to the number chosen by the user in the first form.
for ($i=0; $i<$number ; $i++){
if (!(empty($_POST["bbc$i"])) && (empty($_POST["html$i"])))
//FUNCTION ADDS TAGS TO DATABASE
addBbc($_POST["bbc$i"], $_POST["html$i"]);
This goes from 0 to $number - 1
So i changed my code to this.
for ($i=0; $i<$number ; $i++){
$nb = $i + 1;
if (!(empty($_POST["bbc$nb"])) && (empty($_POST["html$nb"]))) {
addBbc($_POST["bbc$nb"], $_POST["html$nb"]);
}
else echo "$nb tags empty ";
This works a bit better but now it goes to the else just here above and displays "2 tags empty", so it still doesn't quite work.
Ok to solve it I finally decided to post the data from the second form to another page and i modified my code to this.
for ($i=0; $i<$number ; $i++){
$nb = $i + 1;
$varBbc = 'bbc'.$nb;
$varHtml = 'html'.$nb;
if ((isset($_POST[$varBbc])) && (isset($_POST[$varHtml]))) {
addBbc($varBbc, $varHtml);
}
else echo "$nb tags empty ";
}
Apparently using !empty instead of isset doesn't work in this case, maybe because of the html tags.
$nb should be in double quotes.
so echo "<option value='$nb'>$nb</option>"
change to echo "<option value='".$nb."'>$nb</option>";
and also
if (!(empty($_POST['number']))) {
if ($_POST['number'] >= 1 && $_POST['number']<= 50){
$number = $_POST['number'];
$range2 = range(1,$number,1);
?>
change to:
if (isset($_POST['submit'])) {
if ($_POST['number'] >= 1 && $_POST['number']<= 50){
$number = $_POST['number'];
$range2 = range(1,$number,1);
?>