Update multiple rows with radio button check - php

I am getting the value for the single tsid for each record, however the checked radio button value is not returned in the array, I just get 0? Any help is appreciated.
PHP:
// Set the timesheets to set status approved/rejected
// find out how many records there are to update
$size = count($_POST['tsid']);
// start a loop in order to update each record
$i = 0;
while ($i < $size) {
// define each variable
$tsid = intval($_POST['tsid'][$i]);
$personnelid = intval($_POST['personnel'][$i]);
print "TSID: " . $tsid . "<br>";
print "TSuser: " . $personnelid . "<br>";
if ($tsid > 0 && $personnelid > 0) {
// do the update and print out some info just to provide some visual feedback
$query = "Update timesheets set status='1' where id= '$tsid' LIMIT 1";
mysql_query($query) or die ("Error in query: $query");
}
++$i;
}
mysql_close();
HTML:
<input type="hidden" name="tsid[]" value="<?PHP echo $row['id']; ?>">
<li data-role="fieldcontain">
<a href="tsapprove.php?id=<?PHP echo $row['id']; ?>"><p><?PHP echo $row['personnel']; ?></p>
<p><?PHP echo $row['name']; ?></p>
<p class="ui-li-aside"><strong><?PHP echo $row['totalhrs']; ?> H</strong></p>
<fieldset data-role="controlgroup" data-type="horizontal">
<input type="radio" name="personnel[]" id="1" value="<?PHP echo $row['personnel']; ?>" />
<label for="1">Approve</label>
<input type="radio" name="personnel[]" id="2" value="<?PHP echo $row['personnel']; ?>" />
<label for="2">Reject</label>
</fieldset>
</a>
View Details
</li>

Hopefully you can piece this together:
<?
$size = count($_POST['tsid']);
echo "<pre>";print_r($_POST);echo "</pre>";
$i = 0;
while ($i < $size) {
$tsid = $_POST['tsid'][$i];
$pid = $_POST['personnel_'.$i];
print "TSID: " . $tsid . "<br />";
print "TSuser: " . $pid . "<br />";
$i++;
}
?>
<form method="post">
<!--tsid[0] - $i = 0-->
<input type="hidden" name="tsid[]" value="1" />
<input type="radio" name="personnel_0" value="111" />
<input type="radio" name="personnel_0" value="222" />
<!--tsid[1] - $i = 1-->
<input type="hidden" name="tsid[]" value="2" />
<input type="radio" name="personnel_1" value="333" />
<input type="radio" name="personnel_1" value="444" />
<input type="submit" />
</form>
Basically, the way you are returning personnel doesnt really work. So I simplified this a bit, and basically set the radios for personnel differently. Instead of an array, its setting the actual name with the TSID value.
I hard coded 1 and 2, but you would replace with your $row['id'], as well has the number after "personnel_" would be 0..1..2 etc
Hopefully this helps
edit: few issues with code

Related

mysql_data_seek not working

my code is,
$query3 = "SELECT * FROM db_exam_skip WHERE user='$session'";
$result3 = mysql_query($query3) or die(mysql_error());
$length3 = mysql_num_rows($result3);
while($rows3 = mysql_fetch_array($result3))
{
$query1 = "SELECT * FROM db_exam_questions WHERE id='$rows3[ques_id]'";
$result1 = mysql_query($query1) or die(mysql_error());
$length1 = mysql_num_rows($result1);
}
if(isset($_POST['next']))
{
if(isset($_SESSION['list']))
{
mysql_data_seek($result1,$_SESSION['list']);
}
else
{
$list = $_POST['list'];
mysql_data_seek($result1,$list);
}
}
<?php
while($rows1 = mysql_fetch_row($result1))
{
$start = $rows1[0];
$_SESSION['start'] = $start;
?>
<form action="" method="post">
<p style="font-size:20px;font-weight:bold"><?php echo $rows1[5]; ?></p>
<ul style="list-style-type:none">
<input type='hidden' name='number' value='<?php echo $_SESSION['order']++; ?>' />
<input type='hidden' name='list' value='<?php echo $_SESSION['list']++; ?>' />
<input type='hidden' name='ques_id' value='<?php echo $rows1[0]; ?>' />
<input type='hidden' name='correct' value='<?php echo $rows1[10]; ?>' />
<li><input type="radio" name="answer" value="1" /> <?php echo $rows1[6]; ?> <br><br>
<input type="radio" name="answer" value="2" /> <?php echo $rows1[7]; ?> <br><br>
<input type="radio" name="answer" value="3" /> <?php echo $rows1[8]; ?> <br><br>
<input type="radio" name="answer" value="4" /> <?php echo $rows1[9]; ?> <br></li>
</ul>
<input type="submit" class="button4" value="Next" name="next" />
</form>
<?php
break;
}
?>
my question is, after the first question is loaded, when i press next button to load the second question I am getting the below error.
Warning: mysql_data_seek(): Offset 2 is invalid for MySQL result index 8 (or the query data is unbuffered) in C:\wamp\www\Albert\ICAMS\start_skip_question.php on line 15
I have tried a lot to solve this error. But till now no success. Is there any method to solve. Any help will be appreciated.
Thank you.
I guess the result set is empty.I think query is returning empty set.
You will get this error if result set is empty
check the PHP DOCS
First check if you are getting ant rows from the result
if (mysqli_num_rows($sql) > 0)
{
}

radio button in while loop

i am coding a page for the attendance of students and in the page all the students name are retrieved dynamically from database using while loop and inside the while loop i have used a radio button.
my problem is the radio button work's correctly but i am unable to insert the value of radio buttons into database.here is my code :
include'connection.php';
#$id = mysql_real_escape_string($_GET['id']);
$res=mysql_query("SELECT * FROM `std_register` AS p1 ,`sims-register-course` AS p2 WHERE p2.semester=p1.std_semester and p2.department=p1.std_department and p2.id = '".$id."'");
if ($res==FALSE) {
echo die(mysql_error());
}
while ($row=mysql_fetch_assoc($res)) { ?>
<input type="hidden" id="dept_0" name="dept[]" value="<?php echo $row["department"] ?>">
<input type="hidden" id="course_name_1" name="course_name[]" value="<?php echo $row["course_name"] ?>">
<input type="hidden" id="std_semester_2" name="std_semester[]" value="<?php echo $row["semester"] ?>">
<input type="hidden" id="std_id_3" name="std_id[]" value="<?php echo $row["id"] ?>">
<input type="hidden" id="std_name_4" name="std_name[]" value="<?php echo $row["std_name"] ?>">
<tr>
<td class =info><?php echo $row["std_name"];?></td>
<td><input type="radio" name="<?php echo "status['".$row["std_name"]."']" ?>" value="1"></td>
<td><input type="radio" name="<?php echo "status['".$row["std_name"]."']" ?>" value="2"></td>
</tr>
<?php }?>
</table><br>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-3">
<input type="submit" name="submit" value="Assign" class="btn btn-large btn-block btn-primary"></div></div>
</form>
<?php
for ($i=0; $i < 4; $i++) {
if(isset($_POST["submit"])) {
$stdid = mysql_real_escape_string($_POST['std_id'][$i]);
$dptname = mysql_real_escape_string($_POST['dept'][$i]);
$courseName = mysql_real_escape_string($_POST['course_name'][$i]);
$stdSemester = mysql_real_escape_string($_POST['std_semester'][$i]);
$std_name = mysql_real_escape_string($_POST['std_name'][$i]);
$present = mysql_real_escape_string($_POST['status'][$i]);
$totalClasses = $present;
$insrt = mysql_query("INSERT INTO `attendence_student` (department_name,courseName,semester,present,absent,total_classes) VALUES('$dptname','$courseName','$stdSemester','$present',0,0)") or die(mysql_error());
}
}
and is it possible to insert values from this radio buttons to two columns of database?
I am not sure but try to add 'checked' property in radio input
<input type="radio" name="<?php echo "status[".$row["std_name"]."]" ?>" value="1" checked></td>
Or
use Select tag instead of radio button
EDIT
use this code to insert in present column or absent column
$value = mysql_real_escape_string($_POST['status'][$i]);
$totalClasses = $value;
if($value == 1) //check if present
{
$sql="INSERT INTO `attendence_student` (department_name,courseName,semester,present,absent,total_classes) VALUES('$dptname','$courseName','$stdSemester','$value',0,0)";
}
else //if absent
{
$sql="INSERT INTO `attendence_student` (department_name,courseName,semester,present,absent,total_classes) VALUES('$dptname','$courseName','$stdSemester',0,'$value',0)";
}
$insrt = mysql_query($sql) or die(mysql_error());

PHP/MySQL throwing me index error but it's already listed

PHP it's throwing at me
Notice: Undefined index: username in D:\xampp\htdocs\0100348514\pages\account.php on line 16
Warning: mysql_query() expects parameter 1 to be string, resource given in D:\xampp\htdocs\pages\account.php on line 19
But in my database I have it exactly the same 'username' but it's still throwing it at me any ideas?
Code on that page
<?php
$page = "My Account";
session_start();
include '../includes/config.php';
?>
<div id="searchbar">
<form action="search.php" method="get">
<input type="text" name="search" />
<input type="submit" name="submit" class="btn btn-primary" value="Search" />
</form>
</div>
</div>
<?php
$username = $_SESSION['username'];
$sql = "SELECT * FROM login WHERE username = '$username'";
$result = mysql_query($con, $sql) or die(mysql_error($con)); //run the query
$row = mysql_fetch_array($result);
?>
<div id="wrapper">
<section id="content" class="shadow">
<div id="titlebar">
<?php
echo $page = '<h1> My ACCOUNT </h1>';
?>
</div>
<br />
<?php
//user messages
if(isset($_SESSION['error'])) //if session error is set
{
echo '<div class="error">';
echo '<p class="center">' . $_SESSION['error'] . '</p>'; //display error message
echo '</div><br />';
unset($_SESSION['error']); //unset session error
}
elseif(isset($_SESSION['success'])) //if session success is set
{
echo '<div class="success">';
echo '<p class="center">' . $_SESSION['success'] . '</p>'; //display success message
echo '</div><br />';
unset($_SESSION['success']); //unset session success
}
?>
<div id='left'>
<form id="registration" form action="accountprocessing.php" method="post">
<br />
<fieldset><h1>Update Your Details</h1><br />
<ol>
<li>
<label>Username*</label> <input type="text" name="username" required value="<?php echo $row['username'] ?>" readonly />
</li>
<?php
//generate drop-down list for state using enum data type and values from database
$tableName='member';
$colState='state';
function getEnumState($tableName, $colState)
{
global $con; //enable database connection in the function
$sql = "SHOW COLUMNS FROM $tableName WHERE field='$colState'";
//retrieve enum column
$result = mysql_query($con, $sql) or die(mysql_error($con));
//run the query
$row = mysql_fetch_array($result); //store the results in a variable named $row
$type = preg_replace('/(^enum\()/i', '', $row['Type']); //regular expression to replace the enum syntax with blank space
$enumValues = substr($type, 0, -1); //return the enum string
$enumExplode = explode(',', $enumValues); //split the enum string into individual values
return $enumExplode; //return all the enum individual values
}
$enumValues = getEnumState('member', 'state');
echo '<select name="state">';
if((is_null($row['state'])) || (empty($row['state']))) //if the state field is NULL or empty
{
echo "<option value=''>Please select</option>"; //display the 'Please select' message
}
else
{
echo "<option value=" . $row['state'] . ">" . $row['state'] .
"</option>"; //display the selected enum value
}
foreach($enumValues as $value)
{
echo '<option value="' . $removeQuotes = str_replace("'", "",
$value) . '">' . $removeQuotes = str_replace("'", "", $value) . '</option>'; //remove the quotes from the enum values
}
echo '</select><br />';
?>
</li>
<p> </p>
<li>
<label>Postcode*</label> <input type="text" name="postcode" required value="<?php echo $row['postcode'] ?>"/>
</li><br />
<li>
<label>Country*</label> <input type="text" name="country" required value="<?php echo $row['country'] ?>"/>
</li><br />
<li>
<label>Phone</label> <input type="text" name="phone" value="<?php echo $row['phone'] ?>"/>
</li><br />
<li>
<label>Mobile</label> <input type="text" name="mobile" value="<?php echo $row['mobile'] ?>" />
</li><br />
<li>
<label>Email*</label> <input type="email" name="email" required value="<?php echo $row['email'] ?>" />
</li><br />
<li><label>Gender*</label>
<?php
//generate drop-down list for gender using enum data type and values from database
$tableName='member';
$colGender='gender';
function getEnumGender($tableName, $colGender)
{
global $con; //enable database connection in the function
$sql = "SHOW COLUMNS FROM $tableName WHERE field='$colGender'";
//retrieve enum column
$result = mysql_query($con, $sql) or die(mysql_error($con));
//run the query
$row = mysql_fetch_array($result); //store the results in a variable named $row
$type = preg_replace('/(^enum\()/i', '', $row['Type']); //regular expression to replace the enum syntax with blank space
$enumValues = substr($type, 0, -1); //return the enum string
$enumExplode = explode(',', $enumValues); //split the enum string into individual values
return $enumExplode; //return all the enum individual values
}
$enumValues = getEnumGender('member', 'gender');
echo '<select name="gender">';
echo "<option value=" . $row['gender'] . ">" . $row['gender'] .
"</option>"; //display the selected enum value
foreach($enumValues as $value)
{
echo '<option value="' . $removeQuotes = str_replace("'", "",
$value) . '">' . $removeQuotes = str_replace("'", "", $value) . '</option>';
}
echo '</select>';
?>
</li>
</ol>
</fieldset>
<br />
<fieldset>
<p>Subscribe to weekly email newsletter?</p><br />
<label>Yes</label><input type="radio" name="newsletter" value="Y" <?php if($row['newsletter'] == "Y"){echo "checked";} ?>><br />
<label>No</label><input type="radio" name="newsletter" value="N" <?php if($row['newsletter'] == "N"){echo "checked";} ?>>
<input type="hidden" name="memberID" value="<?php echo $memberID; ?>">
</fieldset><br />
<p class="center"><input type="submit" name="accountupdate" value="Update Account" /></p><br />
</form>
</div>
<br />
<div id='right'>
<form id="registration" form action="accountimageprocessing.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="memberID" value="<?php echo $memberID; ?>">
<br />
<fieldset><h1>Update Image</h1><br />
<?php
if((is_null($row['image'])) || (empty($row['image']))) //if the photo field is NULL or empty
{
echo "<p class='center'><img src='../images/members/member.png' width=150 height=150 alt='default photo' /></p>"; //display the default photo
}
else
{
echo "<p class='center'><img src='../images/members/" . ($row['image']) . "'" . 'width=150 height=150 alt="contact photo"' . "/></p><br />"; //display the contact photo
}
?>
<label>New Image</label> <input type="file" name="image" />
<br />
<p>Accepted files are JPG, GIF or PNG. Maximum size is 500kb.</p>
<br />
<p class='center'><input type="submit" name="imageupdate" value="Update Image" /></p>
</form>
<br />
<br />
<form action="accountpasswordprocessing.php" method="post">
<h1>Update Password</h1>
<br />
<p>Passwords must have a minimum of 8 characters.</p> <br />
<label>New Password*</label> <input type="password" name="password" pattern=".{8,}" title= "Password must be 8 characters or more" required />
<br />
<input type="hidden" name="memberID" value="<?php echo $memberID; ?>">
<br />
<p class='center'><input type="submit" name="passwordupdate" value="Update Password" /></p>
<br />
</form>
<h1>Delete My Account</h1>
<br />
<p>We're sorry to hear you'd like to delete your account. By clicking the button below you will permanently delete your account.</p>
<br />
<form action="accountdelete.php" method="post">
<p class='center'><input type="submit" value="Delete My Account" onclick="return confirm('Are you sure you wish to permanently delete your account?');" ></p>
<input type="hidden" name="memberID" value="<?php echo $memberID; ?>"><br />
</fieldset>
</form>
</div>
</section> <!-- end #content -->
<div id="footernav" class id="shadow">
<?php
require "../inc/footer.php";
?>
</div>
</div>
Your mysql_query parameteres are reversed. It should be:
mysql_query($sql, $con);
Also as you can see in the linked PHP Manual page, this extension is deprecated and alternatives should be used:
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.
See also MySQL: choosing an API guide and related FAQ for more
information. Alternatives to this function include:
mysqli_query()
PDO::query()

PHP - Loop number of selected check boxes on form submit

I have an issue where I need to loop the number of check boxes on a form submit. Foreach check box that is looped I need to then insert data into the database.
How Would I go about looping over the amount of check boxes that have being passed via form submit?
My code is as follows:
Form:
<form action="createChallenge.php" method="post" name="chalCreate">
Challenge Name:<input type="text" name="chalName" />
<br />
Challenge Target:<input type="text" name="chalTarget"/>
<br />
End Date:<input type="text" name="chalDate">
<br />
<!-- Needs a jquery datepicker -->
Select Friends: <br />
<?php
$selFriend = $conn->prepare("SELECT * FROM Friends WHERE UserID = '$userID' AND Friend = 'y' ORDER BY FriendName ASC");
$selFriend->execute();
foreach($selFriend as $row){
?>
<input type="checkbox" name="test" value="<?php echo $row['FriendID'] ?>"><?php echo $row['FriendName'] ?><br>
<?php
}
?>
<br />
<button type="submit">Create Challenge</button>
</form>
PHP to handle the form:
<?php
if(isset($_POST['test']))
{
$i = 0;
foreach($_POST['test'] as $checked)
{
echo $friend = $checked;
$i++;
}
echo $name = $_POST['chalName'];
echo $target = $_POST['chalTarget'];
echo $date = $_POST['chalDate'];
echo $friend = $_POST['test'];
echo $setby = $_COOKIE['userID'];
$create = $conn->prepare("INSERT INTO Challenge ( chalSetBy, chalName, chalTarget, chalDate ) VALUES ('$setby', '$name', '$target', '$date') ");
$create->execute();
if($create)
{
echo "Challenge made successfully";
}
else
{
echo "There was a problem";
}
}
?>
I thought doing the following would echo out data, but it didn't, it only selected the last check box:
$i = 0;
foreach($_POST['test'] as $checked)
{
echo $friend = $checked;
$i++;
}
Make an array of your checkbox in HTML page like as below,
<form name="frm" method="post">
<input type="checkbox" value="1" name="test[]">
<input type="checkbox" value="2" name="test[]">
<input type="checkbox" value="3" name="test[]">
<input type="checkbox" value="4" name="test[]">
<input type="checkbox" value="5" name="test[]">
<input type="checkbox" value="6" name="test[]">
<input type="submit">
</form>
<?php
foreach($_POST['test'] as $key=>$value)
{
echo $value."<br>";
}

PHP can't echo for each array

I am trying to echo out an array using for each but it's not displaying any values. The only values i can echo out is within a second for each.
Can anyone tell me what i'm doing wrong?
What i am trying to echo is the price, item, description etc but i am getting nothing.
If you need to see the output of the array it's here http://operationbraveheart.org.uk/jcart/testshop.php
while ($row = $result->fetch()) {
$superitem[$row['itemid']][] = $row;
}
foreach($superitem AS $subitem) {
list($prodid,$item,$size,$description,$price) = $subitem[0];
if ($count % NUMCOLS == 0) echo "<tr>"; # new row
echo '<td>';
var_dump($subitem);
//Your normal code up until the select box...
echo '<form method="post" action="" class="jcart">
<fieldset>
<input type="hidden" name="jcartToken" value="'.$_SESSION['jcartToken'].'" />
<input type="hidden" name="my-item-id" value="'.$subitem['prodid'].'" />
<input type="hidden" name="my-item-price" value="'.$subitem['price'].'" />
<input type="hidden" name="my-item-url" value="http://yahoo.com" />';
if(count($subitem) > 1) {
echo '<li><select name="my-item-name" id="foo">';
foreach($subitem AS $subsubitem) {
echo "<option value='".$subsubitem['size']."'>".$subsubitem['size']."</option>";
}
echo "</select></li>";
}
else {
echo '<input type="hidden" name="my-item-name" value="'.$subitem['item'].'" />';
}
echo'<li>Price: $<span class="price">'.$subitem['price'].'</span></li>
<li>
<label>Qty: <input type="text" name="my-item-qty" value="1" size="3" /></label>
</li>
</ul>
<input type="submit" name="my-add-button" value="add to cart" class="button" />
</fieldset>
</form>';
echo '</td>';
$count++;
$counter++;
if ($count % NUMCOLS == 0) echo "</tr>\n"; # end row
}
Current it looks like $subitem contains an array of length 1 where the first index is a row. Change...
$superitem[$row['itemid']][] = $row;
should be...
$superitem[$row['itemid']] = $row;
and...
list($prodid,$item,$size,$description,$price) = $subitem[0];
should be...
list($prodid,$item,$size,$description,$price) = $subitem;

Categories