working with foreach in mysql and php - php

I have two arrays the selected and questiondesc, I want to update it to the database but My code doesnt seem to work. Is it possible to do nested for each?
<?php do { ?>
<tr>
<th width="170" scope="col">
<input type="checkbox" name="selected[]"
value="<?php echo $row_Recordset1['question_id'];?>"/>
Description:
</th>
<td colspan="2" scope="col">old:
<?php echo $row_Recordset1['question_description']; ?>
new:<input name="questiondesc[]" type="text" size="50"/>/td>
<td width="549" colspan="2" scope="col">
<div align="left">
</td>
</tr>
<?php
} while ($row_Recordset2 = mysql_fetch_assoc($Recordset2));
if (isset($_POST['selected'])) {
$selected = $_POST['selected'];
$question = $_POST['questiondesc'];
foreach ($selected as $enable) {
mysql_query("
UPDATE exam_questions
SET question_description = '$question'
WHERE question_id = '$selected'
") or die(mysql_error());
}
}

You could use a for instead and make sure to properly sanitize your data:
for ($i = 0; $i < sizeof($selected); $i++)
{
$sql = sprintf("UPDATE exam_questions
SET question_description = '%s'
WHERE question_id = '%s'",
mysql_real_escape_string($question[$i]),
mysql_real_escape_string($selected[$i]));
mysql_query($sql)or die(mysql_error());
}
Keep in mind that the above assumes that questions and selections are ordered the same.

Change this line:
mysql_query("UPDATE exam_questions
SET question_description = '$question'
WHERE question_id = '$enable' ")or die(mysql_error());

<?
$i =0;
while ($row_Recordset2 = mysql_fetch_assoc($Recordset2)):
?>
<tr><th width="170" scope="col"><input type="checkbox" name="selected[]" value="<?php echo $row_Recordset1['question_id']; ?>" />
Description:</th><td colspan="2" scope="col">old:
<?php echo $row_Recordset1['question_description']; ?>
new:<input name="questiondesc_<?=$i?>" type="text" size="50" />/td>
<td width="549" colspan="2" scope="col"><div align="left"></td>
</tr>
<?
$i ++;
endwhile;
?>
if(isset($_POST['selected'])){
$selected = $_POST['selected'];
foreach($selected as $id){
$key = 'questiondesc_' . $id;
$question = $_POST[$key];
$sql = "UPDATE exam_questions SET question_description = '" . $question . "' WHERE question_id = '" . $id . "'";
mysql_query($sql)or die(mysql_error());
}
}

Related

Why is that My PHP records not being INSERTED

Good Day!
Guys can you help me to check why my is it that i cannot insert records using chekbox option on table..
Please Help..
Here's My Code...
--ADDING Subject Load for Teacher HTML Form-- (studsub.php)
<form action="setsubject.php" method="post">
<?php
include('../connect.php');
$id=$_GET['id'];
$result = mysql_query("SELECT * FROM student WHERE id='$id'");
while($row = mysql_fetch_array($result))
{
//$course=$row['course'];
//$year=$row['yearlevel'];
//$section=$row['section'];
$idnumber=$row['idnumber'];
echo '<br/>';
echo $row['lname'].", ".$row['fname'];
?>
<input type="hidden" name="studidnum" value="<?php echo $rows['idnumber']?>">
<?php }
?>
<br/><br/>
<label for="filter">Filter</label> <input type="text" name="filter" value="" id="filter" />
<table cellpadding="1" cellspacing="1" id="resultTable">
<thead>
<tr>
<th style="border-left: 1px solid #C1DAD7"><label>Assign</label></th>
<th style="border-left: 1px solid #C1DAD7"> Subject ID </th>
<th>Title</th>
<th>Units</th>
</tr>
</thead>
<tbody>
<?php
include('../connect.php');
$result = mysql_query("SELECT * FROM tbl_cur_sub where status='1' ");
while($row = mysql_fetch_array($result))
{
echo '<tr class="record">';
echo ' <td>' . '<input type="checkbox" name="subject[]" value="'.$rows['code'].'" />' . '</td> ' ;
echo '<td style="border-left: 1px solid #C1DAD7">'.$row['code'].'</td>';
echo '<td><div align="left">'.$row['subject'].'</div></td>';
echo '<td><div align="left">'.$row['units'].'</div></td>';
echo '</tr>';
}
?>
</tbody>
</table>
<br/>
Course<br>
<select name="course" class="ed">
<?php
include('../connect.php');
$results = mysql_query("SELECT * FROM course");
while($rows = mysql_fetch_array($results))
{
echo '<option>'.$rows['coursecode'].'</option>';
}
?>
</select>
<select name="yearlevel" class="ed">
<?php
include('../connect.php');
$results = mysql_query("SELECT * FROM tbl_yrlevel");
while($rows = mysql_fetch_array($results))
{
echo '<option>'.$rows['yearlevel'].'</option>';
}
?>
</select>
<select name="section" class="ed">
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
</select>
<br>
<br>
<input type="submit" value="Assign" id="button1">
</form>
--The Submission Page -- (setsubject.php)
<?php
include('../connect.php');
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str)
{
$str = #trim($str);
if(get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$course = clean($_POST['course']);
$section = clean($_POST['section']);
$yearlevel = clean($_POST['yearlevel']);
$studidnum=$_POST['studidnum'];
$subject=$_POST['subject'];
$N = count($subject);
for($i=0; $i < $N; $i++)
{
mysql_query("INSERT INTO studentsubject (student, subject, section, course, level) VALUES ('$studidnum', '$subject[$i]','$section','$course', '$level')");
}
header("location: student.php");
mysql_close($con);
?>
--My Database--
TABLE: studentsubject
FIELDS: student, subject, section, course, level
Thanks IN advance for the Help..
TRY
mysql_query("SELECT * FROM tbl_cur_sub where status=1 ");
change the mysql statement...you need to differ the variable and string in the query
$result = mysql_query("SELECT * FROM student WHERE id='".$id."'");

Updating database with for loop and mysql

The code for updating my questions is working but when updating the answers it is not. How can i fix this? help. thanks.:)
This is on my form:
<?php do { ?><tr><th width="170" scope="col"><input type="checkbox" name="selected[]" value="<?php echo $row_Recordset1['question_id']; ?>" />
Description:</th>
<td colspan="2" scope="col">old:
<?php echo $row_Recordset1['question_description']; ?>
new:<input name="questiondesc[]" type="text" size="50" />/td>
<td width="549" colspan="2" scope="col"><div align="left"></td>
</tr>
<input type="hidden" name="ansid[]" value="<?php echo $row_Recordset2['answer_id']; ?>" />
<input name="answerdesc[]" type="text" size="20" value="<?php echo $row_Recordset2['answer_description']; ?>" /><?php
if($row_Recordset2['answer_iscorrect'] == 1){
echo "Correct";
}
?>
<?php } while ($row_Recordset2 = mysql_fetch_assoc($Recordset2)); ?>
<?php } while ($row_Recordset2 = mysql_fetch_assoc($Recordset2)); ?>
/////This is my update code
if(isset($_POST['selected'])){
$selected = $_POST['selected'];
$question = $_POST['questiondesc'];
$answer = $_POST['answerdesc'];
$answerid = $_POST['ansid'];
for ($i = 0; $i < sizeof($selected); $i++)
{
$sql = sprintf("UPDATE exam_questions SET question_description = '%s' WHERE question_id = '%s'",
mysql_real_escape_string($question[$i]),
mysql_real_escape_string($selected[$i]));
mysql_query($sql)or die(mysql_error());
for($x = 0; $x < sizeof($answerid); $x++){
$gomugomu = sprintf("UPDATE exam_answers SET answer_description = '%s' WHERE answer_question_set_id = '%s'",
mysql_real_escape_string($answer[$x]),
mysql_real_escape_string($answerid[$x]));
mysql_query($gomugomu)or die(mysql_error());
}
}
}
?>
Your ansid and answerdesc are not arrays
<input type="hidden" name="ansid" .....
<input name="answerdesc" ....
to
<input type="hidden" name="ansid[]" ...
<input name="answerdesc[]" ...

How to update multiple records on a nested recordsets in php mysql?

Help! I have a nested recordsets namely questions and answers and a corresponsing checkbox for each question. How can I update multiple values in a recordset? shall i loop the Update query? Any help would be extremely appreciated.
here is my code:
<?php
mysql_select_db($database_iexam, $iexam);
$query_Recordset1 = "SELECT * FROM exam_questions WHERE question_exam_id = '$exam_id'";
$Recordset1 = mysql_query($query_Recordset1, $iexam) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
do { ?>
<tr>
<th width="170" scope="col">
<input type="checkbox" name="checkbox"
value="<?php echo $row_Recordset1['question_id']; ?>"/>
Question:
</th>
<td colspan="2" scope="col">
<input name="textfield" type="text"
value="<?php echo $row_Recordset1['question_description']; ?>"
size="50"/></td>
<td width="549" colspan="2" scope="col"></td>
</tr>
<tr>
<td>Answers:</td>
<?php
mysql_select_db($database_iexam, $iexam);
$query_Recordset2 = "SELECT * FROM exam_answers WHERE answer_question_set_id = '" . $row_Recordset1['question_id'] . "'";
$Recordset2 = mysql_query($query_Recordset2, $iexam) or die(mysql_error());
$row_Recordset2 = mysql_fetch_assoc($Recordset2);
$totalRows_Recordset2 = mysql_num_rows($Recordset2);
do { ?>
<tr>
<td width="170"> </td>
<td colspan="2">
<input name="textfield2" type="text" size="20"
value="<?php echo $row_Recordset2['answer_description']; ?>"/>
<input
name="<?php echo $row_Recordset2['answer_question_set_id']; ?>"
type="radio"
value="<?php echo $row_Recordset2['answer_iscorrect']; ?>"/>
</td>
</tr>
<?php } while ($row_Recordset2 = mysql_fetch_assoc($Recordset2)); ?>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
You can set checkbox name like name="checkbox[]" for question_id and name="textfield[]" for question_description and finally when you submitted this form you will get a array of this records then you set a for-loop to get separate value and update it into database or any where

Want to update multiple records using checkboxes and save button

I am searching some records using two text boxes and then updating the selected records in database. i am able to see the value row id of the selected checkbox but when i want to get the value for updation in database it gives 0, i.e showing no record in array
Here is my code
if($_POST["search"])
{
$nitnumber = $_POST["nitnumber"];
$workno = $_POST["workno"];
$query = "select * from print where nit = $nitnumber and work = $work";
$result = mysql_query($query) or die ("<font color =red>NIT Number and/or Work Number is Missing</font>");
$count = mysql_num_rows($result);
if($count == 0)
echo "<font color=red>Record not found</font>";
else
{
while($record = mysql_fetch_assoc($result))
{
?>
<tr class="odd">
<td><div align="center"><?php echo $record['a']; ?></div></td>
<td><div align="center"><?php echo $record['b']; ?></div></td>
<td><div align="left"><?php echo $record['c']; ?></div></td>
<td> <div align="left">
<?php
enter code hereecho $record["d"];
?>
</td>
<td>
<input name="checkbox[]" id="checkbox[]" type="checkbox" value="<?php echo $record[$id];?>">
<?php echo $record["id"];?>
</td>
<?php } } }?>
<tr>
<td colspan="5" align="right"> <input type="submit" value="Save" name="save"> </td>
</tr>
<?php
if ($_POST['save'])
{
$num_chkboxes=count($_POST['checkbox']);
for($i=0; $i<$num_chkboxes; $i++){
$complete = intval($checkbox[$i]);
echo $complete;
var_dump($complete);
echo $updateSQL = "UPDATE toDo SET complete=1, WHERE toDoId=$complete";
//$Result1 = mysql_query($updateSQL, $FamilyOrganizer) or die(mysql_error());
}
}
?>
<?php
if ($_POST['save'])
{
$checkbox1 = $_POST['chk1'];
$selected_checkbox = "";
foreach ($checkbox1 as $checkbox1)
{
$selected_checkbox .= $checkbox1 . ", ";
}
$selected_checkbox = substr($selected_checkbox, 0, -2);
$updateSQL = "" // your update query here
}
?>
<input type="checkbox" name="chk1[]" value=""> // take checkboxes like this
First, the problem started when you fill the values of the checkboxes:
<input name="checkbox[]" id="checkbox[]" type="checkbox" value="<?php echo $record[$id];?>" />
you must gave them the value like
value="<?php echo $record['id'] ?>"
Second, you don't get the values of the checkboxes as you should:
for($i = 0; $i < count($_POST['checkbox']); $i++){
$complete = intval($_POST['checkbox'][$i]);
//echo $complete;
//var_dump($complete);
echo $updateSQL = "UPDATE toDo SET complete=1, WHERE toDoId=$complete";
}
Another thing you should take care about is the assigning of the elements ids:
id="checkbox[]"
you must give unique ids for each element:
id="checkbox-1"
id="checkbox-2"

Need help... how to add md5 to password field in php?

i looking some help and nice attention here..
i bought some php script many years ago and now no suport anymore... i just want to add md5 to password field..
here my form:
<?php
$SQL = "SELECT * from USERS WHERE USERNAME = '$_SESSION[username]'"; $result = #mysql_query( $SQL ); $row = #mysql_fetch_array( $result );
include 'menu.php';
?>
<FORM METHOD="post" ACTION="?page=query_client">
<INPUT TYPE="hidden" NAME="controller" VALUE="USERS~update~account_details&up=1~<?php echo $row[ID]; ?>">
<TABLE CLASS="basictable">
<TR>
<TD CLASS="tdmenu" WIDTH="40%">Username</TD>
<TD CLASS="tdmenu" WIDTH="60%">
<b><?php echo $row[USERNAME]; ?></b>
</TD>
</TR>
<TR>
<TD CLASS="tdmenu" WIDTH="40%">Password *</TD>
<TD CLASS="tdmenu" WIDTH="60%">
<INPUT TYPE="PASSWORD" NAME="PASSWORD" SIZE="40" VALUE="<?php echo $row[PASSWORD]; ?>">
</TD>
</TR>
<TR>
<TD CLASS="tdmenu" WIDTH="40%">Email Address *</TD>
<TD CLASS="tdmenu" WIDTH="60%">
<INPUT TYPE="text" NAME="EMAIL" SIZE="40" VALUE="<?php echo $row[EMAIL]; ?>">
</TD>
</TR>
<TR>
<TD CLASS="tdmenu" WIDTH="40%">Full Name *</TD>
<TD CLASS="tdmenu" WIDTH="60%">
<INPUT TYPE="text" NAME="FULLNAME" SIZE="40" VALUE="<?php echo $row[FULLNAME]; ?>">
</TD>
<TR>
<TD CLASS="tdmenu" WIDTH="40%">Address *</TD>
<TD CLASS="tdmenu" WIDTH="60%">
<INPUT TYPE="text" NAME="ADDRESS1" SIZE="40" VALUE="<?php echo $row[ADDRESS1]; ?>">
</TD>
</TR>
<BR>
<TABLE CLASS="basictable">
<TR>
<TD CLASS="tdhead2" >
<DIV ALIGN="CENTER"><B>
<INPUT TYPE="submit" NAME="Submit" VALUE="Submit">
</B></DIV>
</TD>
</TR>
</TABLE>
</FORM>
and the
it self as query_client.php inside look like:
<?PHP
#session_start();
$controller = $_POST['controller'];
$pieces = explode("~", $controller);
$table = $pieces[0];
$qt = $pieces[1];
$return = $pieces[2];
$id = $pieces[3];
$hack = $pieces[4];
if ($qt == insert) $qt = 'INSERT INTO';
if ($qt == update) { $qt = 'UPDATE'; $end = "WHERE ID = '$id'"; }
$pre = array_keys( $_POST );
mysql_query ("CREATE TABLE IF NOT EXISTS `$table` (`ID` INT NOT NULL AUTO_INCREMENT , PRIMARY KEY ( `id` ) )");
$count = count($pre); $count = $count - 2;
$sql = "$qt $table SET";
for ($i=0; $i < $count; $i++)
{
$x=$i+1;
$y = $_POST[$pre[$x]];
$d = $y;
mysql_query ("ALTER TABLE `$table` ADD `$pre[$x]` TEXT NOT NULL");
$sql .= " `$pre[$x]` = '$d',";
}
$sql .= " ID = '$id' $end";
$query = mysql_query($sql) or die("$sql_error" . mysql_error());
if (empty($hack)) { } else {
$pieces = explode("/", $hack);
$h0 = $pieces[0];
$h1 = $pieces[1];
$h2 = $pieces[2];
$h3 = $pieces[3];
$h4 = $pieces[4];
$h5 = $pieces[5];
mysql_query ("ALTER TABLE `$table` $h0 $h1 $h2 $h3 $h4 $h5");
$query = mysql_query($sql) or die("$sql_error" . mysql_error());
}
if (isset($_GET[inc])) include "$_GET[inc].php";
?>
so please help me how to add md5 in PASSWORD field?
thanks in advance..
Best to use a salt also - hashing and verification should be done at server - see secure hash and salt for PHP
Some links on writing secure code:
OWASP Top 10 for 2010
PHP Security: Fortifying Your Website
Writing Secure PHP

Categories