storing array checkbox value - php

I have a table with no.of users
$listuser = mysql_query('SELECT id,firstname,lastname,approve FROM user');
echo '<form action="" method="post">';
echo '<table>
<tr><td>Name</td>
<td>AdminApprove</td>
</tr>';
while($row = mysql_fetch_assoc($listuser))
{
$id = $row['id'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
echo '<tr>
<td><input type="hidden" name="id[]" value ='.$id.'></td>
<td>'.$firstname.''.$lastname.'</td>
<td><input type="checkbox" name="approve[]"></td>
</tr>';
}
echo '<tr><td><input type="submit" name="submit" value="submit"></td></tr>';
echo '</table></form>';
After submitting the form
$postedid = $_POST['id'];
$approve = isset($_POST['approve']) ? 1 : 0;
$approvestudent = 'UPDATE user SET approve = '.$approve.' WHERE id = '.$postedid.'';
$result_update = mysql_query($approvestudent);
I want to approve either one or more at a time for each student and the approved checkbox value need to store to the database either with 0 or 1

$_POST['id'] is array not a string or integer
You can use php serialize() function to convert array into string
$postedid = $_POST['id'];
$approve = $_POST['approve'];
should be
$postedid = serialize($_POST['id']);
$approve = serialize($_POST['approve']);

Related

Creating an HTML form basing on information extracted from an SQL database using while loop

I am trying to create a form, basing on information picked from the database using a while loop. I need some guidance on how to go about this. When form is supposed to return multiple values (of students) and then a text field for inputting marks is assigned to the students returned, which should allow the user input the marks and then submit the form.
Here is the code i have sofar
<form method="post">
<?php
//picking student details
$sql = mysql_query("SELECT *
FROM student, class, subject, assesment
WHERE
student.class_id = '$assesment_class'
AND subject.idsubject = '$assesment_subject'
AND subject.subject_option = 'Major'
AND class.idclass = student.class_id
AND class.idclass = subject.class_id
AND assesment.subject_idsubject = subject.idsubject
AND assesment.idassesment = '$ass'
");
$Count = mysql_num_rows($sql); //counting the the selected rows
if($Count > 0){
while($row = mysql_fetch_array($sql)){
//picking database values
$student_id = $row["idstudent"];
$student_names = $row["student_names"];
//Query for checking results
$sql1 = mysql_query("SELECT *
FROM result, student_has_result, grade, student, assesment
WHERE
student_has_result.student_id = '$student_id'
AND student_has_result.student_class_id = '$assesment_class'
AND student_has_result.assesment_id = '$ass'
AND student_has_result.result_id = result.idresult
AND result.grade_idgrade = grade.idgrade
AND student_has_result.assesment_id = assesment.idassesment
AND student_has_result.student_id = student.idstudent
AND student_has_result.result_id = result.idresult");
$Count1 = mysql_num_rows($sql1); //counting the the selected rows
if($Count1 > 0){
while($row = mysql_fetch_array($sql1)){
//picking database values
$mark = $row["mark"];
//echo $mark;
}
}else{
$mark = "";
}
?>
<tr>
<td><?php echo $student_names; ?></td>
<td>
<input type="text" name="result" placeholder="<?php echo $mark; ?>"/>
<input type="hidden" name="student" value="<?php echo $student_id; ?>"/>
<input type="hidden" name="assesment" value="<?php echo $ass; ?>"/>
</td>
</tr>
<?php
}
?>
<tr>
<td></td>
<td><button name="submit-results-button" type="submit" class="btn btn-success">-Submit Students Results Now-</button><br><br></td>
</tr>
</form>
Any guidance will be highly appreciated.

editing and deleting records in a database using radio buttons

<?php
$user_name = "root";
$password = "";
$database = "my_db";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if(isset ($_POST['name']))
{
$name = $_POST['name'];
if(mysql_query("INSERT INTO persons VALUES(' ' , '$name') "))
echo "Successful Insertion!";
else
echo "Please try again!";
}
$result = mysql_query("SELECT * FROM persons");
?>
<html>
<head>
<style type = "text/css">
li { list-style-type: none; display: inline; padding: 10px; text-align: center;}
</style>
</head>
<body>
<form action = " . " method = "POST">
Name: <input type = "text" name = "name"><br>
<input type = "submit" value = "Enter">
</form>
<form name = "delete_form" method = "POST" action = "delete.php" >
<input type = "submit" name = "deleteRecord" value = "Delete Record" />
</form>
<h1>List of Names</h1>
<table border = "1" width = "100%" cellpadding = "5" cellspacing = "2">
<tr>
<td><strong></strong></td>
<td><strong>ID</strong></td>
<td><strong>Company</strong></td>
<td><strong>Edit</strong></td>
<td><strong>Delete</strong></td>
</tr>
<?php while ($row = mysql_fetch_array($result)) { ?>
<tr>
<td><input type="radio" Name="id" value="<?php echo $row['id']; ?>" ></td>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo "<a href = 'edit.php?id=$row[id]'>edit</a>" ?></td>
<td><?php echo "<a href = 'delete.php?id=$row[id]'>delete</a>" ?></td>
</tr>
<?php } ?>
<form name = "edit_form" method = "POST" action = " edit.php?edit= "<?php echo $row['id'] ?> >
<input type = "submit" name = "editRecord" value = "Edit Record" />
</form>
</table>
<?php
while($row = mysql_fetch_array($result))
echo "<li>$row[id]</li> . <li>$row[name]</li> <li> <a href = 'edit.php?edit=$row[id]'>edit</a> </li> <li> <a href = 'delete.php?del=$row[id]'>delete</a></li> <br>";
?>
</body>
</html>
edit.php
<?php
$user_name = "root";
$password = "";
$database = "my_db";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$row = " ";
if (isset($_POST['id']))
{
// if there is an id sent through POST and it isn't null/empty, use that
$id = $_POST['id'];
$SQL = "SELECT * FROM persons WHERE id = '$id' ";
$result = mysql_query($SQL);
$row = mysql_fetch_array($result);
}
else
{
// otherwise use id sent through GET links
$id = $_GET['id'];
$SQL = "SELECT * FROM persons WHERE id = '$id' ";
$result = mysql_query($SQL);
$row = mysql_fetch_array($result);
}
if(isset($_POST['newName']))
{
$id = $_POST['id'];
$newName = $_POST['newName'];
$SQL = "UPDATE persons SET name = '$newName' WHERE id = '$id' ";
$result = mysql_query($SQL) or die("Could not update database" . mysql_error());
echo "<meta http-equiv = 'refresh' content = '0 ; url = index.php'>";
}
?>
<form action = " edit.php" method = "POST">
ID: <input type = "text" name = "id" value = "<?php echo $row[0] ?>"<br><br>
Name: <input type = "text" name = "newName" value = "<?php echo $row[1] ?>"<br><br>
<input type = "submit" value = "Update">
</form>
Hello,
The code above shows how to edit and delete records in a database. Originally, the edit and delete options were in the form of links to a php script which performed the required action. The ID number of the selected row gets passed to the edit or delete php file which then does the action that the user selects (refer to the comments in the code above) I am now trying to modify this code so that I can use a radio button to select a record and then edit or delete the record using radio buttons. I know this sounds trivial but I am having some difficulty with it. Any assistance would be greatly appreciated. Thank you.
Hello Tom. I have made the changes that you suggested but I it still giving the same problem. I have included the edit.php file in case you want to have a look.
The value of your radio buttons needs to contain the ID of the record to be edited.
<td><INPUT TYPE="Radio" Name="radio" value="<?php echo $row['id']; ?>"></td>
Then when you submit the form, you will know the record you are editing has id of value $_POST['radio'].
Though you are already using GET method to pass IDs (through your edit and delete links). I would recommend having consistency, and passing all IDs with parameter id. So
Use this
<td><?php echo "<a href = 'edit.php?id=$row[id]'>edit</a>"; ?></td>
<td><?php echo "<a href = 'delete.php?id=$row[id]'>delete</a>"; ?></td>
And this
<td><input type="radio" name="id" value="<?php echo $row[id]; ?>"></td>
Then in edit.php and delete.php, check to see if an ID was passed through POST (if someone submitted the form) or through GET (they clicked a link), then use whichever has a value.
<?php
if (!empty($_POST['id']))
{
// if there is an id sent through POST and it isn't null/empty, use that
$id = $_POST['id'];
}
else
{
// otherwise use id sent through GET
$id = $_GET['id'];
}
I should also mention that mysql_fetch_array is deprecated and you should be using PDO or MySQLi. Read more here: http://www.php.net/mysql_fetch_array

INSERT a row per array object

I am in the process of creating a document association tool whereby users can associate documents to a ticket from a pre-existing list of documents.
Thanks to the help of Alberto Ponte I was able to construct the initial radio box system (originally checkbox, changed for obvious reasons) from this question: Separate out array based on array data
Now that I have the radio buttons presenting correctly I am trying to get the data inserted into a MySQL with a row for each document. Following on from this I want to have it look up the table for each object and see if there is an existing entry and update that rather than inset a duplicate entry.
Apologies in advance for the soon to be depreciated code and I will be correcting the code going forward, however that is a much bigger task than I currently have time for.
Also apologies if the code is considered messy. I'm not fantastic at PHP and not too hot on best practices. Any quick pointers are always welcome.
Display code:
<?php
include "../includes/auth.php";
include "../includes/header.php";
## Security ########################################################
if ($company_id != 1 OR $gid < 7) {
echo' <div class="pageheader">
<div class="holder">
<br /><h1>Access Denied <small> Your attempt has been logged</small></h1>
</div>
</div>
';
exit();
}
// GET Values ###################################################
$jat_id = intval($_GET['id']);
$div_id = intval($_GET['div_id']);
## Page Start ########################################################
echo '
<div class="pageheader">
<div class="holder">
<br /><h1>Clovemead Job Management Platform<small> Welcome...</small></h1>
</div>
</div>
<div class="well5" style="width:1000px !important;">
<h3>Create Document Association</h3>
<table border=1>
<tr>
<td align=center><p>Here you can associate documents to Jobs and Tasks to.</p> </td>
</tr>
</table>';
$order2 = "SELECT * FROM documents";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$nice_name = $row2['nice_name'];
$doc_id = $row2['id'];
}
echo '
<h3>Documents</h3>
<table border=1>
<tr><th>Document Name</th><th>Document Type</th><th>Required</th><th>Optional</th><th>Not Required</th></tr>
';
$order2 = "SELECT * FROM documents ORDER BY type_id";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$nice_name = $row2['nice_name'];
$doc_id = $row2['id'];
$doc_type_id = $row2['type_id'];
echo '
<tr>
<td>'.$nice_name.'</td>';
$order3 = "SELECT * FROM document_types WHERE id = '$doc_type_id'";
$result3 = mysql_query($order3);
while ($row3 = mysql_fetch_array($result3)) {
$type_name = $row3['type_name'];
echo '
<td>'.$type_name.'</td>
<form method="post" action="create-doc-assoc-exec.php">
<input type="hidden" value="'.$doc_id.'" name="doc_id">
<input type="hidden" value="'.$jat_id.'" name="jat_id">
<input type="hidden" value="'.$div_id.'" name="div_id">';
$order4 = "SELECT * FROM document_assoc WHERE doc_id = '$doc_id'";
$result400 = mysql_query($order4);
$_results = mysql_fetch_array($result400);
if (!$_results) {
echo '
<td><input type="radio" name="req0" value="2"></td>
<td><input type="radio" name="req0" value="1"></td>
<td><input type="radio" name="req0" value="0" checked ></td>';
} else {
foreach ($_results as $result400) {
$requirement = $_results['requirement'];
}
$name = "req".$doc_id;
echo '
<input type="hidden" value ="'.$name.'" name="name">
<td><input type="radio" name="'.$name.'" value="2" '; if ($requirement == 2) { echo ' checked '; } echo '></td>
<td><input type="radio" name="'.$name.'" value="1" '; if ($requirement == 1) { echo ' checked '; } echo '></td>
<td><input type="radio" name="'.$name.'" value="0" '; if ($requirement < 1) { echo ' checked '; } echo '></td>';
}
}
echo '
</tr>';
}
echo '
</table>
<input type="submit" name="submit value" value="Create Document Association" class="btn success Large"></form>';
$order2 = "SELECT * FROM divisions WHERE id = '$div_id'";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$dbname = $row2['division_dbname'];
$order3 = "SELECT * FROM $dbname WHERE id = '$jat_id'";
$result3 = mysql_query($order3);
while ($row3 = mysql_fetch_array($result3)) {
$type = $row3['type'];
$type2 = strtolower($type);
echo '
<input type="button" value="Back" onclick="window.location='./view-'.$type2.'.php?id='.$jat_id.''" class="btn primary Large">
';
}}
echo '
</div>';
include "../includes/footer.php";
?>
Execute Code:
<?php
include "../includes/dbconnect.php";
$name = $_POST['name'];
$name = stripslashes($name);
$name = mysql_real_escape_string($name);
$doc_id = intval($_POST['doc_id']);
$jat_id = intval($_POST['jat_id']);
$div_id = intval($_POST['div_id']);
$req = intval($_POST[$name]);
$req_blank = intval($_POST['req0']);
if ($req_blank == 0) {
$requirement = 0;
} elseif ($req_blank == 1) {
$requirement = 1;
} elseif ($req_blank == 2) {
$requirement = 2;
} elseif ($req == 0) {
$requirement = 0;
} elseif ($req == 1) {
$requirement = 1;
} elseif ($req == 2) {
$requirement = 2;
}
foreach ($doc_id as $doc_id2) {
$order = "INSERT INTO document_assoc (jat_id, dept_id, doc_id, requirement) VALUES ('$jat_id', '$div_id', '$doc_id2', '$requirement')";
$result = mysql_query($order);
$order1 = "SELECT * FROM divisions WHERE id = '$div_id'";
$result1 = mysql_query($order1);
while ($row1 = mysql_fetch_array($result1)) {
$dbname = $row1['division_dbname'];
$order2 = "SELECT * FROM $dbname WHERE id = '$jat_id'";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$type = $row2['type'];
$type2 = strtolower($type);
if($result){
header("location:view-$type2.php?id=$jat_id&creation=success");
} else {
header("location:view-$type2.php?id=$jat_id&creation=failed");
}
}}
}
?>
A few reference points:
$doc_id is the ID of each document which is to be passed over as an array for use in a (i believe) foreach insert
$jat_id is the ticket id documents are being associated to
$div_id is the department the ticket is associated
And the radio boxes are to decider the requirement of each document. To be passed over inline with $doc_id
What I have tried:
After a fair bit of searching - finding nothing - rechecking my terminology and searching again I managed to find the suggestion of using base64_encode(serialize()) on the arrays but I could not get this to work.

Check a check box if it's value is in DB. PHP

I have a loop of checkboxes from a MySql table "exercise" in a form as shown below:
<form id="form1" name="form1" method="POST" action="insertDrills.php">
<table width="100%" border="1" cellspacing="0" cellpadding="0">
<?php do { ?>
<tr>
<td>
<input type="checkbox" name="drillSelect[]" value="<?php echo $row_Recordset1['drillID']; ?>" id="drillSelect" />
<?php echo $row_Recordset1['rubrik']; ?>
</td>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
<tr>
<td colspan="2">
<input name="spelarID" type="hidden" id="spelarID" value="<?php echo $row_rsSpelare['id']; ?>" />
<input name="date" type="hidden" id="date" value="<? print date("Y-m-d h:i:s"); ?>" />
<input type="submit" name="submit" id="submit" value="Välj övningar" />
<input type="button" value="Avbryt" onclick="window.close();"></button>
</td>
</tr>
</table>
</form>
The value from the hidden fied "spelarID" along with the value from the checkbox array are inserted to a look-up table "exercise_spelare_ref" with this:
<?php
$id = $_POST['spelarID'];
$drills = $_POST['drillSelect'];
$date = $_POST['date'];
$inserts = array();
foreach ($drills as $drills)
$inserts[] = "('$id','$drills','','$date')";
$query = "REPLACE INTO exercise_spelare_ref VALUES ". implode(", ", $inserts);
//echo "query = $query"; // for debugging purposes, remove this once it is working
mysql_query($query) or die(mysql_error());
?>
How can I make values that are in the look-up table marked as "checked" in the form?
There are a solution here https://stackoverflow.com/a/4069477 written by Martin Bean but I cant get it to work?
I have been stuck here for ever, hope anyone can help me out here!
I tried Martin Beans script like:
$uid = $row_rsSpelare['id']; // your logged in user's ID
$exercise = array();
// get an array of exercise
$sql = "SELECT drillID FROM exercise";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$exercise[$row->id] = $row->drillID;
}
// get an array of exercise user has checked
$sql = "SELECT DISTINCT drillID FROM exercise_spelare_ref WHERE id = '$uid'";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$checked[] = $row->drillID;
}
// this would be templated in a real world situation
foreach ($exercise as $id => $drillID) {
$checked = "";
// check box if user has selected this exercise
if (in_array($checked, $id)) {
$checked = 'checked="checked" ';
}
echo '<input type="checkbox" name="drillSelect[]" value="'.$id.'" '.$checked.'/>';
}
But getting a warning:
Warning: in_array() expects parameter 2 to be array, string given in /customers/b/d/e/teeview.se/httpd.www/analys_kund/selectDrills.php on line 158
Line 158 is:
if (in_array($checked, $id)) {
Well, you will need to SELECT the items from the table, store them into an array, and if the current checkbox's ID matches something in the array, add the checked attribute to it in the HTML.

Create input fields dynamically with values and column names from database

I create inputs using the information in the columns for example if a field is called about_content it outputs a label of About Content with an input field. This works fine for inserting however I want to use this code similarly to UPDATE and I want to display to users the current value of a field as entered in the database. For example if about_content = Hello World! I want the input value to reflect that. Is there a way of doing this dynamically?
<?php
require('dbc.php');
mysql_select_db($db);
$resultInput = mysql_query("SHOW COLUMNS FROM about WHERE Field NOT IN
('id', 'created', 'date_modified', 'last_modified', 'update', 'type', 'bodytext')
AND Field NOT REGEXP '_image'"); // selects only the columns I want
$result = mysql_query("SELECT * FROM about WHERE id=".$_GET['id']); // values I want to put into the values for <input>
while ($row = mysql_fetch_assoc ($result) && $column = mysql_num_rows ($resultInput)) {
foreach($row as $column => $value){
echo '<label>'.$column.'<input name="'.$column.'" type="input" value="'.$value.'"></label><br>';
}
}
?>
See the spot you've marked with an arrow? Instead of the string (1), set value to the appropriate database value you read in $result (not in $resultInput).
Here's how: use mysql_fetch_assoc for your SELECT query, not mysql_fetch_row. There will be only one row, so fetch it before you start generating the form. You'll then have a named array with the row values, and you can grab each field by name and put it in the form.
If you don't understand how to do that, check the php documentation for mysql_fetch_assoc.
And escape your $_GET['id'] like you were told in your last question. You're begging to be pwned!
See mysql_fetch_field.
if (mysql_num_rows($result) > 0) {
//loop creates inputs
//make $resultInput object to array.
$i=0;
while ($row = mysql_fetch_assoc($result)) {
$meta = mysql_fetch_field($result, $i);
if(in_array($meta->name, $resultInput )){
echo '<div class="wrapper"><label>' . ucfirst(str_replace('_', ' ',$meta->name)) .
'<br><input name="' . $meta->name .
'" type="text" class="input" value="$row[$meta->name]"><br></label></div>';
}
$i++;
}
}
<?php
include('db.php');
if (isset($_POST['btn'])) {
$dcolumn = $_POST['dyncolumns'];
$dvalue = $_POST['dynfields'];
$name = $_POST['name'];
$mobile = $_POST['mobile'];
$address = $_POST['address'];
$query = "INSERT into addtable(name,mobile,address)VALUES('" . $name . "','" . $mobile . "','" . $address . "')";
$result = mysql_query($query)or die(mysql_error());
$id = mysql_insert_id();
if ($dcolumn) {
foreach ($dcolumn as $key => $value) {
$result1 = "show COLUMNS from addtable like '.$value.'";
$exists = mysql_query($result1)or die(mysql_error());
$data = mysql_fetch_assoc($exists);
if ($data==TRUE) {
$query = "update addtable set $value = '" . $dvalue[$key] . "' where id=$id";
} else {
$query1 = "ALTER TABLE addtable ADD $value varchar(45)";
$result2 = mysql_query($query1)or die(mysql_error());
$query = "update addtable set $value = '" . $dvalue[$key] . "' where id=$id";
$result = mysql_query($query)or die(mysql_error());
}
}
}
}
?>
<script>
function myFunction() {
var table = document.getElementById("insert");
var row = table.insertRow(3);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "<input type='text' name='dyncolumns[]'>";
cell2.innerHTML = "<input type='text' name='dynfields[]' >";
}
</script>
<html>
<body>
<form name="insert" method="post">
<table border="2" align="center" id="insert">
<tr>
<td>Name</td><td><input type="text" name="name" /></td>
</tr>
<tr>
<td>Mobile</td><td><input type="text" name="mobile" maxlength="10"/></td>
</tr>
<tr>
<td>Address</td><td><input type="text" name="address" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="btn" value="submit"></td>
</tr>
</table>
<input type="button" onclick="myFunction()" name="add" value="Add">
Logout
</form>
</body>
</html>

Categories