Reflecting sub records in PHP from MySQL - php

I am trying to get records from my DB using 2 seperate tables. The query is
public function get_pages_by_campign_id($campaignID) {
$campaignID = $this->real_escape_string($campaignID);
return $this->query("SELECT pid, campaignid FROM pages,campaigns WHERE 'pages.campaignid = campaigns.id'");
}
And this is called into play by :
$counter = 1;
$userID = PageDB::getInstance()->get_user_id_by_name($_SESSION['user']);
$result = PageDB::getInstance()->get_pages_by_campaign_id($campaignID);
$i=0;
while ($row = mysqli_fetch_array($result)):
$style = "";
if($i%2==0)
{
$style = ' style="background-color: #EFEFEF"';
}
echo "<tr".$style.">";
echo "<td style='width:140px;'> Page " . $counter . "</td>";
echo "<td> </td>";
echo "<td></td>";
//The loop is left open
?>
<td>
<form style="display:none;"></form>
<form name="editPage" action="editPage.php" method="GET">
<input type="hidden" name="pageID" value="<?php echo $pageID = $row['pid']; ?>"/>
<input type="submit" name="editPage" value="Edit"/>
</form>
</td>
<td>
<form name="deletePage" action="deletePage.php" method="POST">
<input type="hidden" name="pageID" value="<?php echo $pageID = $row['pid']?>"/>
<input type="submit" name="deletePage" value="Delete" onclick = "javascript: return confirm('Delete Page <?php echo $counter ?> ?');"/>
</form>
</td>
<?php
$pageID = $row['pid'];
$counter++;
$i++;
echo "</tr>\n";
endwhile;
mysqli_free_result($result);
?>
This should list all "page" Records, but it is returning nothing.
I have set up the "id" column in table "campaigns" to correspond with "campaignid" in table "pages" using foreign keys.
I manged to fix it with this :
public function get_pages_by_campaign_id($campaignID) {
$campaignID = $this->real_escape_string($campaignID);
return $this->query("SELECT pid, campaignid FROM pages WHERE campaignid = 'campaigns.id'");
}

"SELECT pid, campaignid FROM pages,campaigns WHERE pages.campaignid = campaigns.id"
?

Related

Not Able to save data to Mysql database

I am developing a simple attendance system in which the attendance is taken by the a teacher and then saved to the database. However, I am having a problem with saving the data to the database. when i click on "submit attendance" the data won't be submitted to the database. i use register.php to register students but take the attendance in different file.
Below is the code i use to submit. Can someone help me? Thanks.
sorry the file i shared was supposed to save data to mysql database. Below is the file which takes the data and am still having the problem for saving it.
this is the teacher file to take the attendance
teacher.php
<?php
$pageTitle = 'Take Attendance';
include('header.php');
require("db-connect.php");
if(!(isset($_COOKIE['teacher']) && $_COOKIE['teacher']==1)){
echo 'Only teachers can create new teachers and students.';
$conn->close();
include('footer.php');
exit;
}
//get session count
$query = "SELECT * FROM attendance";
$result = $conn->query($query);
$sessionCount=0;
setcookie('sessionCount', ++$sessionCount);
if(mysqli_num_rows($result)>0){
while($row = $result->fetch_assoc()){
$sessionCount = $row['session'];
setcookie('sessionCount', ++$sessionCount);
}
}
if(isset($_GET['class']) && !empty($_GET['class'])){
$whichClass = $_GET['class'];
$whichClassSQL = "AND class='" . $_GET['class'] . "'";
} else {
$whichClass = '';
$whichClassSQL = 'ORDER BY class';
}
echo '
<div class="row">
<div class="col-md-4">
<div class="input-group">
<input type="number" id="session" name="sessionVal" class="form-control" placeholder="Session Value i.e 1" required>
<span class="input-group-btn">
<input id="submitAttendance" type="button" class="btn btn-success" value="Submit Attendance" name="submitAttendance">
</span>
</div>
</div>
<div class="col-md-8">
<form method="get" action="' . $_SERVER['PHP_SELF'] . '" class="col-md-4">
<select name="class" id="class" class="form-control" onchange="if (this.value) window.location.href=this.value">
';
// Generate list of classes.
$query = "SELECT DISTINCT class FROM user ORDER BY class;";
$classes = $classes = mysqli_query($conn, $query);
if($classes && mysqli_num_rows($classes)){
// Get list of available classes.
echo ' <option value="">Filter: Select a class</option>';
echo ' <option value="?class=">All classes</option>';
while($class = $classes->fetch_assoc()){
echo ' <option value="?class=' . $class['class'] . '">' . $class['class'] . '</option>';
}
} else {
echo ' <option value="?class=" disabled>No classes defined.</option>';
}
echo '
</select>
</form>
</div>
</div>
';
$query = "SELECT * FROM user WHERE role='student' $whichClassSQL;";
$result = $conn->query($query);
?>
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Class</th>
<th>Present</th>
<th>Absent</th>
</tr>
</thead>
<tbody>
<form method="post" action="save-attendance.php" id="attendanceForm">
<?php
if(mysqli_num_rows($result) > 0){
$i=0;
while($row = $result->fetch_assoc()){
?>
<tr>
<td><input type="hidden" value="<?php echo($row['id']);?>" form="attendanceForm"><input type="text" readonly="readonly" name="name[<?php echo $i; ?>]" value="<?php echo $row['fullname'];?>" form="attendanceForm"></td>
<td><input type="text" readonly="readonly" name="email[<?php echo $i; ?>]" value="<?php echo $row['email'];?>" form="attendanceForm"></td>
<td><input type="text" readonly="readonly" name="class[<?php echo $i; ?>]" value="<?php echo $row['class'];?>" form="attendanceForm"></td>
<td><input type="radio" value="present" name="present[<?php echo $i; ?>]" checked form="attendanceForm"></td>
<td><input type="radio" value="absent" name="present[<?php echo $i; ?>]" form="attendanceForm"></td>
</tr>
<?php $i++;
}
}
?>
</form>
</tbody>
</table>
<script>
$("#submitAttendance").click(function(){
if($("#session").val().length==0){
alert("session is required");
} else {
$.cookie("sessionVal", $("#session").val());
var data = $('form#attendanceForm').serialize();
$.ajax({
url: 'save-attendance.php',
method: 'post',
data: {formData: data},
success: function (data) {
console.log(data);
if (data != null && data.success) {
alert('Success');
} else {
alert(data.status);
}
},
error: function () {
alert('Error');
}
});
}
});
</script>
<?php
$conn->close();
include('footer.php');
save-attendance.
<?php
//include ("nav.php");
require("db-connect.php");
$query = "SELECT * FROM user WHERE role='student'";
$result = $conn->query($query);
$nameArray = Array();
$count = mysqli_num_rows($result);
if(isset($_COOKIE['sessionCount'])){
$sessionCount = $_COOKIE['sessionCount'];
}
//save record to db
if(isset($_POST['formData'])) {
//increment the session count
if(isset($_COOKIE['sessionCount'])){
$sessionCount = $_COOKIE['sessionCount'];
setcookie('sessionCount', ++$sessionCount);
}
parse_str($_POST['formData'], $searcharray);
//print_r($searcharray);die;
//print_r($_POST);
for ($i = 0 ; $i < sizeof($searcharray) ; $i++){
// setcookie("checkloop", $i);;
$name = $searcharray['name'][$i];
$email= $searcharray['email'][$i];
$class = $searcharray['class'][$i];
$present= $searcharray['present'][$i];
if(isset($_COOKIE['sessionVal'])){
$sessionVal = $_COOKIE['sessionVal'];
}
//get class id
$class_query = "SELECT * FROM class WHERE name='".$class."'";
$class_id = mysqli_query($conn, $class_query);
if($class_id){
echo "I am here";
while($class_id1 = $class_id->fetch_assoc()){
$class_id_fin = $class_id1['id'];
echo $class_id['id'];
}
}
else{
echo "Error: " . $class_query . "<br>" . mysqli_error($conn);
}
//get student id
$student_query = "SELECT * FROM user WHERE email='".$email."'";
$student_id = $conn->query($student_query);
if($student_id) {
while ($student_id1 = $student_id->fetch_assoc()) {
$student_id_fin = $student_id1['id'];
}
}
//insert or update the record
$query = "INSERT INTO attendance VALUES ( '".$class_id_fin."', '".$student_id_fin."' , '".$present."','".$sessionVal."','comment')
ON DUPLICATE KEY UPDATE isPresent='".$present."'";
print_r($query);
if(mysqli_query($conn, $query)){
echo json_encode(array('status' => 'success', 'message' => 'Attendance added!'));
} else{
echo json_encode(array('status' => 'error', 'message' => 'Error: ' . $query . '<br>' . mysqli_error($conn)));
}
}
$conn->close();
}
You did not provide a lot of information, but I understand from the comments that the error is $sessionVal is undefined.
if $_COOKIE['sessionVal'] is not set, try:
1- print_r($_COOKIE) and check if [sessionVal] is set;
2- Try to add a fallback to:
if(isset($_COOKIE['sessionVal'])){
$sessionVal = $_COOKIE['sessionVal'];
}
else {
$sessionVal = 0;
}
or
$sessionVal = (isset($_COOKIE['sessionVal'])) ? $_COOKIE['sessionVal'] : 0;
Bottom line, there is not point to check if a variable is set and not having a fallback in case it is not set.

PHP button click - value / id to pass over

Hey I'm currently having a problem with trying to make my input button have a value of the id / server that I need and it showing a different value this is how my code currently looks I know the HTML and forms are invalid I will be refactoring it however I'm trying to get a server identifier and a id identifier to cross to another page
<?php
$propertyType = $xmlDom1->getElementsByTagName('PropertyType');
$rent = $xmlDom1->getElementsByTagName('rates');
$rooms = $xmlDom1->getElementsByTagName('rooms');
//$server = $xmlDom1->getElementsByTagName('server');
$propertyServer = $xmlDom1->getElementsByTagName('Property');
$propertyID = $xmlDom1->getElementsByTagName('Property');
$imageURL = $xmlDom1->getElementsByTagName('url');
$imageAlt = $xmlDom1->getElementsByTagName('altText');
$server = $propertyID->item($i)->getAttribute('server');
echo '<form action="level5Details.php" method="get" enctype="application/x-www-form-urlencoded">';
echo '<table><th>Type:</th><th>Rent:</th><th>Rooms:</th><th>Server</th>';
$records = $xmlDom1->documentElement->childNodes;
for ($i = 0; $i < $records->length; $i++) {
echo "<tr><td>".$propertyType->item($i)->nodeValue."</td>";
echo "<td>".$rent->item($i)->nodeValue."</td>";
echo "<td>".$rooms->item($i)->nodeValue."</td>";
echo "<td>".$propertyServer->item($i)->getAttribute('Server')."</td>";
echo '<td><img src="data:image/jpeg;base64,'.$imageURL->item($i)->nodeValue.'" alt="'.$imageAlt->item($i)->nodeValue.'"></img></td>';
?>
<td>
<button class="submit" type="submit" value="<?php echo $propertyID->item($i)->getAttribute('pid'); ?>" name="submit22">something </button>
</td>
</tr>
<?php
}
?>
</form>
If you are trying to generate lots of form each with just a button then you need to put the form in a table cell like this
It might also be useful to place the data items you want to pass in hidden fields rather than try and put 2 data items in the button value
<?php
$propertyType = $xmlDom1->getElementsByTagName('PropertyType');
$rent = $xmlDom1->getElementsByTagName('rates');
$rooms = $xmlDom1->getElementsByTagName('rooms');
//$server = $xmlDom1->getElementsByTagName('server');
$propertyServer = $xmlDom1->getElementsByTagName('Property');
$propertyID = $xmlDom1->getElementsByTagName('Property');
$imageURL = $xmlDom1->getElementsByTagName('url');
$imageAlt = $xmlDom1->getElementsByTagName('altText');
$server = $propertyID->item($i)->getAttribute('server');
echo '<table><th>Type:</th><th>Rent:</th><th>Rooms:</th><th>Server</th>';
$records = $xmlDom1->documentElement->childNodes;
for ($i = 0; $i < $records->length; $i++) {
echo "<tr><td>".$propertyType->item($i)->nodeValue."</td>";
echo "<td>".$rent->item($i)->nodeValue."</td>";
echo "<td>".$rooms->item($i)->nodeValue."</td>";
echo "<td>".$propertyServer->item($i)->getAttribute('Server')."</td>";
echo '<td><img src="data:image/jpeg;base64,'.$imageURL->item($i)->nodeValue.'" alt="'.$imageAlt->item($i)->nodeValue.'"></img></td>';
$pid = $propertyID->item($i)->getAttribute('pid');
?>
<td>
<form action="level5Details.php" method="get" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="pid" value="<?php echo $pid;?>">
<input type="hidden" name="server" value="<?php echo $server;?>">
<button class="submit" type="submit" value="submit" name="submit22">something</button>
</form>
</td>
</tr>
<?php
}
?>
If you just want the button to carry all the data and have only one form you will have to package the 2 data items into one string and sent it as the value of the button
<?php
$propertyType = $xmlDom1->getElementsByTagName('PropertyType');
$rent = $xmlDom1->getElementsByTagName('rates');
$rooms = $xmlDom1->getElementsByTagName('rooms');
//$server = $xmlDom1->getElementsByTagName('server');
$propertyServer = $xmlDom1->getElementsByTagName('Property');
$propertyID = $xmlDom1->getElementsByTagName('Property');
$imageURL = $xmlDom1->getElementsByTagName('url');
$imageAlt = $xmlDom1->getElementsByTagName('altText');
$server = $propertyID->item($i)->getAttribute('server');
echo '<form action="level5Details.php" method="get" enctype="application/x-www-form-urlencoded">';
echo '<table><th>Type:</th><th>Rent:</th><th>Rooms:</th><th>Server</th>';
$records = $xmlDom1->documentElement->childNodes;
for ($i = 0; $i < $records->length; $i++) {
echo "<tr><td>".$propertyType->item($i)->nodeValue."</td>";
echo "<td>".$rent->item($i)->nodeValue."</td>";
echo "<td>".$rooms->item($i)->nodeValue."</td>";
echo "<td>".$propertyServer->item($i)->getAttribute('Server')."</td>";
echo '<td><img src="data:image/jpeg;base64,'.$imageURL->item($i)->nodeValue.'" alt="'.$imageAlt->item($i)->nodeValue.'"></img></td>';
$dataPackage = $propertyID->item($i)->getAttribute('pid') . ':' . $server;
?>
<td>
<button class="submit" type="submit" value="<?php echo $dataPackage;?>" name="submit22">something</button>
</td>
</tr>
<?php
}
</table>
</form>
?>
Now in the receiving form unpack the data for use
<?php
// usual checks for things existing
list($pid, $server) = explode(':', $_GET['submit22'];

How to Update Value Based on the Displayed row in MySQL and PHP

I'm trying to update my data in MySQL database using the displayed data from it. But I haven't much luck in figuring out what I'm doing wrong. I don't know how can I pass my data from my $rows in order for me to use it in my UPDATE SQL statement.
I just want to complete all the data before I clicked the save button.
Please see attached image for the output..
And also, I got a warning message like this.
WHenever I Clicked the Save Data button..
Notice: Undefined variable: reason in C:\xampp\htdocs\BTR\get_forms.php on line 109
Notice: Array to string conversion in C:\xampp\htdocs\BTR\get_forms.php on line 109
Can someone enlighten me.. How to do this.? Thank you..
<?php
require 'config.php';
$form_type = $_POST['form_type'];
if ($form_type == 'MCCV-F2'){
$region = $_POST['region'];
$province = $_POST['province'];
$municipality = $_POST['municipality'];
$barangay = $_POST['barangay'];
$period = $_POST['period'];
$form_type = $_POST['form_type'];
echo "NON COMPLIANT IN EDUCATION<br>";
echo "<br><br>MUNICIPALITY: ".$municipality;
echo "<br><br>BARANGAY: ".$barangay;
echo "<br><br>PERIOD: ".$period;
?>
<form name="get_forms_f2" action="" method="post">
<br><br>
<center><table border = 1 style =2 width=1800>
<tr>
<td><center><b>Household ID </center></td>
<td><center><b>Member ID </center></td>
<td><center><b>Name</center></td>
<td><center><b>Sex</center></td>
<td><center><b>HH Status</center></td>
<td><center><b>Grade Level </center></td>
<td><center><b>School ID</center></td>
<td><center><b>Name Of Dominant School</center></td>
<td><center><b>CV Remarks</center></td>
<td><center><b>Reason</center></td>
<td><center><b>Other Reason</center></td>
<td><center><b>Intervention</center></td>
</tr>
<?php
$sql = "SELECT A.family_id, A.barangay, A.person_id, A.gender, A.family_status, A.current_grade_level,
A.school_facility_id, A.school_facility_name, A.municipality, CONCAT(B.last_name, ', ',B.first_name) as 'name',
B.person_id,B.cv_remarks, B.reason, B.other_reason, B.intervention, B.status FROM roster AS A RIGHT JOIN compliance AS B ON A.person_id = B.person_id
WHERE B.period='$period' AND B.form_type='$form_type' AND A.municipality='$municipality' AND A.barangay='$barangay'";
$query=$conn->prepare($sql);
$query->execute();
$result= $query->fetchALL(PDO::FETCH_ASSOC);
$count=(int)$query->rowCount();
foreach ($result as $row){
$person_id[] = $row['person_id'];
echo "<tr>";
echo "<td>".$row['family_id']."</td>";
echo "<td>".$row['person_id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['gender']."</td>";
echo "<td>".$row['family_status']."</td>";
echo "<td>".$row['current_grade_level']."</td>";
echo "<td>".$row['school_facility_id']."</td>";
echo "<td>".$row['school_facility_name']."</td>";
echo "<td><input type='text' name='cv_remarks[]' value='".$row['cv_remarks']."'></td>";
echo "<td><select name='reason[]'>";
if (is_null($row['reason'])){
$sql2= "SELECT reason_code, reason_desc FROM reasons WHERE form_type ='2' ORDER BY reason_code ASC";
echo "<option value=''>SELECT REASON FOR Non-Compliance</option>";
foreach($conn->query($sql2) as $row2){
echo "<option value='".$row2['reason_desc']."'>".$row2['reason_code']." - ".$row2['reason_desc']."</option>";
}
}
if (!is_null($row['reason'])){
$sql2= "SELECT reason_code, reason_desc FROM reasons WHERE form_type ='2' ORDER BY reason_code ASC";
echo "<option value='".$row['reason']."'>".$row['reason']." (SELECTED)"."</option>";
foreach($conn->query($sql2) as $row2){
echo "<option value='".$row2['reason_desc']."'>".$row2['reason_code']." - ".$row2['reason_desc']."</option>";
}
}
echo "</select></td>";
echo "<td><input type='text' name='other_reason[]' value='".$row['other_reason']."'></td>";
echo "<td><input type='text' name='intervention[]' value='".$row['intervention']."'></td>";
echo "</tr>";
}
}
?>
</table></center><br><br>
<input type="submit" name="submit" value="Save Data">
<?php
$sql3 = "UPDATE compliance SET reason='{$reason}' WHERE person_id='{$person_id}' AND form_type='$form_type' AND period='$period'";
$query = $conn->prepare($sql3);
$query->execute();
?>
</form>
I have posted with the answer of how to update form with an array variable as a whole.
I have kept person,reason as array since you have added that alone as array().
<?php
require 'config.php';
if(isset($_POST['submit']))
{
for ($i=0; $i<count($_POST['person_id']); $i++)
{
$sql3 = "UPDATE compliance SET reason='".$_POST['reason'][$i]."' WHERE person_id='".$_POST['person_id'][$i]."' AND form_type='".$_POST['form_type']."' AND period='".$_POST['period']."'";
$query = $conn->prepare($sql3);
$query->execute();
}// end of For
}// end of IF
$form_type = $_POST['form_type'];
if ($form_type == 'MCCV-F2'){
$region = $_POST['region'];
$province = $_POST['province'];
$municipality = $_POST['municipality'];
$barangay = $_POST['barangay'];
$period = $_POST['period'];
echo "NON COMPLIANT IN EDUCATION<br>";
echo "<br><br>MUNICIPALITY: ".$municipality;
echo "<br><br>BARANGAY: ".$barangay;
echo "<br><br>PERIOD: ".$period;
?>
<form name="get_forms_f2" action="" method="post">
<br><br>
<center><table border = 1 style =2 width=1800>
<tr>
<td><center><b>Household ID </center></td>
<td><center><b>Member ID </center></td>
<td><center><b>Name</center></td>
<td><center><b>Sex</center></td>
<td><center><b>HH Status</center></td>
<td><center><b>Grade Level </center></td>
<td><center><b>School ID</center></td>
<td><center><b>Name Of Dominant School</center></td>
<td><center><b>CV Remarks</center></td>
<td><center><b>Reason</center></td>
<td><center><b>Other Reason</center></td>
<td><center><b>Intervention</center></td>
</tr>
<?php
$sql = "SELECT A.family_id, A.barangay, A.person_id, A.gender, A.family_status, A.current_grade_level,
A.school_facility_id, A.school_facility_name, A.municipality, CONCAT(B.last_name, ', ',B.first_name) as 'name',
B.person_id,B.cv_remarks, B.reason, B.other_reason, B.intervention, B.status FROM roster AS A RIGHT JOIN compliance AS B ON A.person_id = B.person_id
WHERE B.period='$period' AND B.form_type='$form_type' AND A.municipality='$municipality' AND A.barangay='$barangay'";
$query=$conn->prepare($sql);
$query->execute();
$result= $query->fetchALL(PDO::FETCH_ASSOC);
$count=(int)$query->rowCount();
foreach ($result as $row){
?>
<input type="hidden" name="person_id[]" value="<?php echo $row['person_id'];?>">
<input type="hidden" name="form_type" value="<?php echo $form_type; ?>">
<input type="hidden" name="period" value="<?php echo $period; ?>">
<?php
echo "<tr>";
echo "<td>".$row['family_id']."</td>";
echo "<td>".$row['person_id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['gender']."</td>";
echo "<td>".$row['family_status']."</td>";
echo "<td>".$row['current_grade_level']."</td>";
echo "<td>".$row['school_facility_id']."</td>";
echo "<td>".$row['school_facility_name']."</td>";
echo "<td><input type='text' name='cv_remarks[]' value='".$row['cv_remarks']."'></td>";
echo "<td><select name='reason[]'>";
if (is_null($row['reason'])){
$sql2= "SELECT reason_code, reason_desc FROM reasons WHERE form_type ='2' ORDER BY reason_code ASC";
echo "<option value=''>SELECT REASON FOR Non-Compliance</option>";
foreach($conn->query($sql2) as $row2){
echo "<option value='".$row2['reason_desc']."'>".$row2['reason_code']." - ".$row2['reason_desc']."</option>";
}
}
if (!is_null($row['reason'])){
$sql2= "SELECT reason_code, reason_desc FROM reasons WHERE form_type ='2' ORDER BY reason_code ASC";
echo "<option value='".$row['reason']."'>".$row['reason']." (SELECTED)"."</option>";
foreach($conn->query($sql2) as $row2){
echo "<option value='".$row2['reason_desc']."'>".$row2['reason_code']." - ".$row2['reason_desc']."</option>";
}
}
echo "</select></td>";
echo "<td><input type='text' name='other_reason' value='".$row['other_reason']."'></td>";
echo "<td><input type='text' name='intervention' value='".$row['intervention']."'></td>";
echo "</tr>";
}
}// end of MCCV-F2 form
?>
</table>
</center>
<br><br>
<input type="submit" name="submit" value="Save Data">
</form>
Hope so this would solve your problem br. have a try and let me know if any hindrance you find.

value is not appearing in the drop downlist

I have a php code that add/delete new row (tr)to the html table. One column(td) has text field and second column(td) has a drop down. Dropdown source is mysql table.
First row(tr) value are coming correctly. But dropdonwn list is null when I add new row(tr)
code is:
<html>
<head>
<title></title>
<style type="text/css">
input {
display: block; /* makes one <input> per line */
}
</style>
</head>
<?php
include 'dbconnection\dbconnection.php'; // Database connection
$count=1;
if(isset($_POST['btnadd']) == "ADD NEW ITEM") {
// add 1 to the row counter
if (isset($_POST['count'])) $count = $_POST['count'] + 1;
// set value for first load
else $count = 1;
}
if(isset($_POST['btnremove']) == "DELTE ITEM") {
// decrement the row counter
$count = $_POST['count'] - 1;
// set minimum row number
if ($count < 1) $count = 1;
}
?>
<body>
<!-- call same file on submit -->
<form name="form1" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php
$cdquery="select cmc_id,cmc_name from cat_main_category";
$result2=mysqli_query($conn,$cdquery) or die(mysqli_error());
echo '<table>';
// print $count rows
for ($i=1; $i<=$count; $i++) {
echo ' <tr> <td> <input type="text" name="text'.$i.'" align="center"> </td>';
echo '<td> <select id="basicgroup'.$i.'" name="basicgroup'.$i.'" onchange=reload(this.form)>';
echo '<option value=0>Select</option>';
while ($row=mysqli_fetch_array($result2)) {
$cdTitle=$row["cmc_name"];
$id=$row["cmc_id"];
//if($id==#$basicgroup){
echo "<option selected value=$id>
$cdTitle
</option>";
/*}
else{echo "<option value=$id>
$cdTitle
</option>""."<BR>";;*/
}
echo '</select></td></tr> ';
}
?>
</table>
<!-- you only need one set of buttons and only one counter for this script
because every button would do the same -->
<input type="submit" name="btnadd" id="btnadd" value="ADD NEW ITEM" >
<input type="submit" name="btnremove" id="btnremove" value="DELETE ITEM">
<input type="hidden" name="count" value="<?php echo $count; ?>">
</form>
</body>
</html>
After you executed MySQL query:
$result2=mysqli_query($conn,$cdquery) or die(mysqli_error());
Save the results in the array like:
$categories = [];
while ($row=mysqli_fetch_array($result2)) {
$categories[$row["cmc_id"]] = $row["cmc_name"]
}
Then in your main loop:
for ($i=1; $i<=$count; $i++) {
echo ' <tr> <td> <input type="text" name="text'.$i.'" align="center"> </td>';
echo '<td> <select id="basicgroup'.$i.'" name="basicgroup'.$i.'" onchange=reload(this.form)>';
echo '<option value=0>Select</option>';
foreach ($categories as $id => $cdTitle) {
echo "<option selected value=$id>
$cdTitle
</option>";
}
echo '</select></td></tr>';
}
You current problem is on the first iteration you exhausting your MySQL query with mysqli_fetch_array and second select is empty
Change
<?php
$cdquery="select cmc_id,cmc_name from cat_main_category";
$result2=mysqli_query($conn,$cdquery) or die(mysqli_error());
echo '<table>';
for ($i=1; $i<=$count; $i++) {
echo '<tr><td><input type="text" name="text'.$i.'" align="center"></td>';
echo '<td><select id="basicgroup'.$i.'" name="basicgroup'.$i.'" onchange=reload(this.form)>';
echo '<option value=0>Select</option>';
while ($row=mysqli_fetch_array($result2)) {
$cdTitle=$row["cmc_name"];
$id=$row["cmc_id"];
echo "<option selected value=$id>$cdTitle</option>";
}
echo '</select></td></tr>';
}
?>
</table>
To
<?php
echo '<table>';
for ($i=1; $i<=$count; $i++) {
$cdquery="select cmc_id,cmc_name from cat_main_category";
$result2=mysqli_query($conn,$cdquery) or die(mysqli_error());
echo '<tr><td><input type="text" name="text'.$i.'" align="center"></td>';
echo '<td><select id="basicgroup'.$i.'" name="basicgroup'.$i.'" onchange=reload(this.form)>';
echo '<option value=0>Select</option>';
while ($row=mysqli_fetch_array($result2)) {
$cdTitle=$row["cmc_name"];
$id=$row["cmc_id"];
echo "<option selected value=$id>$cdTitle</option>";
}
echo '</select></td></tr>';
}
?>
</table>
Put,
$cdquery="select cmc_id,cmc_name from cat_main_category";
$result2=mysqli_query($conn,$cdquery) or die(mysqli_error());
inside for loop.

Send data to form using link

I don't know to do the script, when click link, it will send data to form. What im trying to do is . When user click link data will appear at the form. below is my link. generated from database.
<div id="menu_bar" region="west" split="true" title="Pages listing" style="width:200px;padding:10px;">
<?php
$parent = mysql_query("select * from pages where parent = 0");
echo "<ul id='sitemap'>";
while($row = mysql_fetch_array($parent)){
$parent_id = $row['id'];
$parent_name = $row['name'];
echo "<li><a href='#' onclick='editPage()'>$parent_name ($parent_id)</a>";
echo "<ul>";
$child = mysql_query("select * from pages where parent = '$parent_id'");
while($row = mysql_fetch_array($child)){
$child_id = $row['id'];
$child_name = $row['name'];
echo "<li><a href='list2.php?id=$child_id' onclick='editPage()'>$child_name ($child_id)</a></li>";
}
echo "</ul>";
}
echo "</li>";
echo "</ul>";
?>
</div>
And the form.
Basic Information
Name:
Parent:
Order:
Body:
Special:
Please help me, im still in programming field. im using PHP, JSON,JQUERY, EASY-UI.
Thanks
If you want to edit page detail in new page then no need to call onclick='editPage()' instead of that pass the page url in href.
<?php
$parent = mysql_query("select * from pages where parent = 0");
echo "<ul id='sitemap'>";
while($row = mysql_fetch_array($parent)){
$parent_id = $row['id'];
$parent_name = $row['name'];
echo "<li><a href='edit_page.php?id=".$row['id']."' >$parent_name ($parent_id)</a>";
echo "<ul>";
$child = mysql_query("select * from pages where parent = '$parent_id'");
while($row = mysql_fetch_array($child)){
$child_id = $row['id'];
$child_name = $row['name'];
echo "<li><a href='edit_page.php?id=".$row['id']."' >$child_name ($child_id)</a></li>";
}
echo "</ul>";
}
echo "</li>";
echo "</ul>";
?>
edit page code should be like this
<?php
$id = $_REQUEST['id'];
//use ur table name here
//I am considering that ur table contain all the required information
$result = mysql_query("select * from table where id='".$id."'");
$row = mysql_fetch_assoc($result);
?>
<form>
Name <input type="text" name="name" id="name" value="<?php echo $row['name']; ?>" />
Parent <input type="text" name="name" id="name" value="<?php echo $row['parent']; ?>" />
Order <input type="text" name="name" id="name" value="<?php echo $row['order']; ?>" />
Body <input type="text" name="name" id="name" value="<?php echo $row['body_text']; ?>" />
Special <input type="text" name="name" id="name" value="<?php echo $row['special']; ?>" />
</form>
hope this will help you.

Categories