Jump to content

Search With View, Edit, Delete Function


phpNOvice

Recommended Posts

Good day Php Friends,

 

i have manage to make a searchbox which displayed the student according to their first name. But after it is being displayed i added with view, edit, delete links.

 

Now my problem is when i click the links it will not direct to the specific student. here are the code for your reference.

 

Admin_Home.php

</head>
<?php include 'Header.php';?>
<body>
<script language="javascript" type="text/javascript">

function ajaxFunction(){
 var ajaxRequest;  
 
 try{
   // Opera 8.0+, Firefox, Safari
   ajaxRequest = new XMLHttpRequest();
 }catch (e){
   // Internet Explorer Browsers
   try{
      ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
   }catch (e) {
      try{
         ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
      }catch (e){
         
         alert("Your browser broke!");
         return false;
      }
   }
 }


 ajaxRequest.onreadystatechange = function(){
   if(ajaxRequest.readyState == 4){
      var ajaxDisplay = document.getElementById('ajaxDiv');
      ajaxDisplay.innerHTML = ajaxRequest.responseText;
   }
 }

 var first_name = document.getElementById('first_name').value;

 var queryString = "?first_name=" + first_name ;
 ajaxRequest.open("GET", "ajax.php" + 
                              queryString, true);
 ajaxRequest.send(null); 
}

</script>


<table width="547" align="center">
		<tr>
			<td width="135"><button class="submit" type="submit">
		       <span class="style8"><a href="Admin_Home.php">Home</a>
		       </button>
		       </span></span></td>
			<td width="173"><button class='submit' type='submit'>
			  <span class="style8"><a href="Admin_Add_Student.php">Add Learner </a>
		      </button>
	          </span></span></td>
			<td width="126"><button class="submit" type="submit">
			  <span class="style8"><a href="index.php">Logout</a>
		      </button>
	          </span></span></td>
		</tr>
</table>

<div class="center">
<form name='myForm' align='center'>
<span class="style5">First Name:</span> 
<input type='text' id='first_name' class="lab" />  
       
<input type='button' class="search" onclick='ajaxFunction()' value='Search Learner'/>
</form>
</div>

<div class="style4" id='ajaxDiv'>
</div>
<p> </p>
<p> </p>

</body>
 </html>

ajax.php

include 'Connect.php';
 //Connect to MySQL Server
mysql_connect($host, $dbusername, $dbpassword);
 //Select Database
mysql_select_db($dbname) or die(mysql_error());
 // Retrieve data from Query 

 $first_name = $_GET['first_name'];
 // Escape User Input to help prevent SQL Injection
$first_name = mysql_real_escape_string($first_name);

 
$query = "SELECT * FROM student_information WHERE first_name = '$first_name'";

 
 
$qry_result = mysql_query($query) or die(mysql_error());
  
$display_string = "<table border='1' cellpadding='10' cellspacing='1' align='center'>";
$display_string .= "<tr align='center'>";
$display_string .= "<th>LR Number</th>";
$display_string .= "<th>F i r s t   N a m e</th>";
$display_string .= "<th>L a s t   N a m e</th>";
$display_string .= "<th>Grade</th>";
$display_string .= "<th>Section</th>";    
$display_string .= "<th>View</th>";  
$display_string .= "<th>Update</th>";
$display_string .= "<th>Delete</th>";
$display_string .= "</tr>";

// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)){
 $display_string .= "<tr>";
 $display_string .= "<td>$row[LRN]</td>";
 $display_string .= "<td>$row[first_name]</td>";
 $display_string .= "<td>$row[last_name]</td>";
 $display_string .= "<td>$row[grade]</td>";
 $display_string .= "<td>$row[section]</td>";
 $display_string .= "<td><a href='View_Profile.php'>View</a> </td>";
 $display_string .= "<td><a href='Admin_Edit_Student_Info.php'>Update</a></td>";
 $display_string .= "<td><a href='Admin_Delete_Student.php'>Delete</a></td>";
 $display_string .= "</tr>";
 
}

$display_string .= "</table>";
echo $display_string;


?>

i think i miss some codes on the ajax.php VIEW/EDIT/DELETE reference links. Please correct and give me some suggestions. If you need other codes in my page which is necessary just tell me so that i can post it.

Link to comment
Share on other sites

Hi,

 

From your code:

$display_string .= "<td><a href='View_Profile.php'>View</a> </td>";
$display_string .= "<td><a href='Admin_Edit_Student_Info.php'>Update</a></td>";
$display_string .= "<td><a href='Admin_Delete_Student.php'>Delete</a></td>";

Your links are not working because you are not passing the user ID's into the link query-string. Something like:

$display_string .= "<td><a href='View_Profile.php?userID=$row[user_id]'>View</a> </td>";
$display_string .= "<td><a href='Admin_Edit_Student_Info.php?userID=$row[user_id]''>Update</a></td>";
$display_string .= "<td><a href='Admin_Delete_Student.php?userID=$row[user_id]''>Delete</a></td>";

... Something like that. Notes:

 

  1. I don't know what the student ID field is called, so I just put 'user_id'. You have to put in the field name that is the unique key for your student table.
  2. On the target pages (ex: Admin_Edit_Student_Info.php) I assume you have the code to parse the query-string for the student's ID.

 

Stef

Link to comment
Share on other sites

Hello Stefan,

 

Thank you for the comprehensive reply. Although i have not tried i think those are the missing codes i'm looking for. 

Regarding the code to parse the query-string for the student's ID, i am not really sure if i have it but let me show you my 

Admin_Edit_Student_Info.php codes and its handler.

 

Admin_Edit_Student_Info.php

<?php
	session_start();
	$session_id = $_SESSION['admin_id'];
	if($session_id == null){
	   header("location:Admin_Home.php");
	   die();
	}
   
   include 'Connect.php';
   $first_name = $_REQUEST['first_name'];
   $query = "select * from student_information where first_name = '$first_name'";
   $result = mysql_query($query, $link_id);
   $data = mysql_fetch_array($result);
?>	   
<html>
<head>
<link rel="stylesheet" href="Style.css" type="text/css"/>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Update Learner Info by Admin</title>
<script src="Validation.js"></script>
<script type="text/javascript">
function validation()
{
	if(document.form1.first_name.value=="")
	{
	   alert("Please enter your first name.");
	   document.form1.first_name.focus();
	   return false;
	}
	if(document.form1.last_name.value=="")
	{
	   alert("Please enter your last name.");
	   document.form1.last_name.focus();
	   return false;
	}
	if(document.form1.date_of_birth.value=="")
	{
	   alert("Please enter your date of birth.");
	   document.form1.date_of_birth.focus();
	   return false;
	}
	else
	{
	   var date = document.form1.date_of_birth.value;
	   var yes = checkDate(date);
	   if(!yes)
		{
			alert("Please Enter a valid date of birth.");
			 document.form1.date_of_birth.focus();
			 return false;
		}	
	 }
	if(document.form1.section.value=="")
	{
	   alert("Please enter Learner's Section.");
	   document.form1.section.focus();
	   return false;
	} 	 
	if(document.form1.email1.value=="")
	{
	   alert("Please enter your primary email.");
	   document.form1.email1.focus();
	   return false;
	}
	else
	{
	   var isEmail = emailValidator(document.form1.email1.value);
	   if(!isEmail)
	   {
			alert("Please enter a valid primary email.");
			document.form1.email1.focus();
			return false;
	   }
	}
	
	if(document.form1.email2.value != "")
	{
	   var isEmail = emailValidator(document.form1.email2.value);
	   if(!isEmail)
	   {
			alert("Please enter a valid secondary email.");
			document.form1.email2.focus();
			return false;
	   }
	}
	if(document.form1.address.value != "" && document.form1.address.value.length > 100){
		alert("You can enter address upto 100 characters only.")
		document.form1.address.focus();
		return false;
	}
	if(document.form1.description.value != "" && document.form1.description.value.length > 200){
		alert("You can enter description upto 200 characters only.")
		document.form1.description.focus();
		return false;
	}
}
function SetAll()
 {
   document.form1.grade.value="<?php echo $data['grade'];?>";
   var gen = "<?php echo $data['gender'];?>";
   var gend = document.form1.gender.length;
   for(var i =0; i<gend; i++)
    {
	   if(document.form1.gender[i].value == gen)
	     document.form1.gender[i].checked=true;
	}	
 }
</script> 
<style type="text/css">
<!--
#Layer1 {
	position:absolute;
	width:1087px;
	height:122px;
	z-index:1;
	left: 51px;
	top: 851px;
}
body,td,th {
	font-family: Verdana, Arial, Helvetica, sans-serif;
}
body {
	background-color: #0099FF;
}
-->
</style></head>

<body onLoad="javascript:SetAll()">
<form name="form1" method="post" action="Admin_Edit_Student_Info_Handler.php" onSubmit="return validation()">
 <input type="hidden" name="student_id" value="<?php echo $student_id; ?>;">
  <table width="100%" height="100%" >
    <tr >
      <td width="100%" height="15%" align="center"><?php include 'Header.php';?></td>
    </tr>
    <tr>
      <td width="100%" height="80%" align="center"><p class="stylesmall"> </p>
      <table width="80%"  border="1" cellpadding="2" cellspacing="0" bordercolor="#EEEEEE">
        <tr>
          <td colspan="4" align="center" bgcolor="#EEEEEE" class="stylebig">Update Student Information</td>
          </tr>
        <tr>
		  <td colspan="4" align="center"> 
		<?php  if($_GET['flag'] == "success") { ?>
		<span class="stylered">Learner Information updated successfully.</span>
        <?php } else if($_GET['flag'] == "error") {  ?>
		<span class="stylered">Error while updating learner information.Please try again</span>
        <?php }  ?>		</td>
		</tr> 
        <tr class="stylesmall">
          <td width="19%" align="left">First Name : </td>
          <td width="30%" align="left"><input name="first_name" type="text" id="first_name" value="<?php echo $data['first_name']; ?>" size="25"maxlength="20"></td>
          <td width="17%" align="left">Last name</td>
          <td width="34%" align="left"><input name="last_name" type="text" id="last_name" value="<?php echo $data['last_name'];?>" size="25" maxlength="20"></td>
        </tr>
        <tr class="stylesmall">
          <td height="29" align="left">Gender : </td>
          <td align="left"><input name="gender" type="radio" value="Male">
            Male<input name="gender" type="radio" value="Female">
            Female</td>
          <td align="left">Date Of Birth</td>
          <td align="left"><input name="date_of_birth" type="text" id="date_of_birth" size="10" maxlength="10" value="<?php echo date("d-m-Y",strtotime($data['date_of_birth']));?>">
            DD-MM-YYYY</td>
        </tr>
        <tr class="stylesmall">
          <td>Grade<span class="stylered">*</span> </td>
          <td><select name="grade" id="grade">
            <option value="">-----select-----</option>
			<option value="Grade 7">Grade 7</option>
			<option value="Grade 8">Grade 8</option>
			<option value="Grade 9">Grade 9</option>
			<option value="Grade 10">Grade 10</option>
			<option value="Grade 11">Grade 11</option>
			<option value="Grade 12">Grade 12</option>
			</select></td>
          <td>Section<span class="stylered">*</span> </td>
          <td><input name="section" type="text" id="section" value="<?php echo $data['section'];?>"  size='15' maxlength="15"></td>
        </tr>
		<tr class="stylesmall">
          <td> LRN</td>
          <td><input name="LRN" type="text" id="LRN" value="<?php echo $data['LRN'];?>" size='10' maxlength="10"></td>
          <td>Contact No</td>
          <td><input name="contact_no" type="text" id="contact_no" value="<?php echo $data['contact_no'];?>" size='15' maxlength="15"></td>
		</tr>		
        <tr class="stylesmall">
          <td align="left">Primary Email : </td>
          <td align="left"><input name="email1" type="text" id="email1" value="<?php echo $data['email1'];?>" size="25" maxlength="100"></td>
          <td align="left">Secondary Email</td>
          <td align="left"><input name="email2" type="text" id="email2" value="<?php echo $data['email2'];?>" size="25" maxlength="100"></td>
        </tr>
        <tr class="stylesmall">
          <td align="left">Address : </td>
          <td colspan="3" align="left"><textarea name="address" rows="2" cols="40"><?php echo $data['address'];?></textarea></td>
        </tr>
		<tr class="stylesmall">
          <td align="left">Description : </td>
          <td colspan="3" align="left"><textarea name="description" rows="3" cols="40"><?php echo $data['description'];?></textarea></td>
        </tr>
        <tr>
          <td colspan="4"> </td>
        </tr>
		<tr align="center" class="stylemedium" bgcolor="#EEEEEE">
		  <td colspan="4" bgcolor="#99CC33"><span class="style3">Learners Report Card</span></td>
		  </tr>
		<tr class="stylesmall">
		  <td>Upload LRN page 1 </td>
		  <td colspan="3"><input type="file" name="LRCard">
		          <span class="stylered">jpg or gif file only</span></td>
		</tr>
		<tr class="stylesmall">
		  <td>Upload LRN page 2 </td>
		  <td colspan="3"><input type="file" name="LRCard2">
		          <span class="stylered">jpg or gif file only</span></td>
		</tr>
		
        <tr>
          <td colspan="4" align="center"><input name="update" type="submit" id="update" value="Update">
            <input name="close" type="button" id="close" value="Close" onClick="self.location='Admin_Home.php'"></td>
         </tr>
      </table>
     </tr>
  </table>
</form>
</body>
<div id="Layer1"><img src="images/footer.png" alt="footer" width="1250" height="122"></div>
</html>

Sorry im not really sure where to place --the parse the query-string for the student's ID, so i gave you all the codes.

and this is the

 

Admin_Edit_Student_Info_Handler.php

<?php
	session_start();
	$session_id = $_SESSION['admin_id'];
	if($session_id == null){
	   header("location:Admin_Home.php");
	   die();
	}
	include 'Connect.php';
	$student_id = $_POST['student_id'];
	$first_name = $_POST['first_name'];
	$last_name = $_POST['last_name'];
	$gender = $_POST['gender'];
	$date_of_birth = date("Y-m-d",strtotime($_POST['date_of_birth']));
	$contact_no = $_POST['contact_no'];
	$grade	= $_POST['grade'];
	$section = $_POST['section'];
	$LRN = $_POST['LRN'];
	$email1 = $_POST['email1'];
	$email2 = $_POST['email2'];
	$address = $_POST['address'];
	$description = $_POST['description'];
	$LRCardname= "";
	$LRCard2name= "";		
	$flag = "";
	
  	$query = "update into student_information(student_id,student_password,first_name,last_name,registration_date,gender,date_of_birth,";
	$query .= "contact_no,grade,section,LRN,email1,email2,address,description)";
	$query .= " values('$student_id','$student_password','$first_name','$last_name',now(),'$gender','$date_of_birth',";
	$query .= "'$contact_no','$grade','$section','$LRN','$email1','$email2','$address','$description')";
  	$query .= " where student_id='$student_id'";
	$result = mysql_query($query, $link_id);
	if(mysql_error() != null){
		die(mysql_error());
	}
	if($result)
	{ 
		$flag = "success";
	}
    else
	{
		 $flag = "error"; 
  	}
	
	/*
			This block shows the start codes for the upload of the Learner Report Card.
	*/
	
	if($result){
			if($_FILES['LRCard']['name'] != ""){
				$filename = $_FILES['LRCard']['name'];
				$ext = strrchr($filename,".");
				$LRCardname = $student_id;
				$LRCardname .="_". $filename; 
				if($ext ==".jpg" || $ext ==".jpeg" || $ext ==".JPG" || $ext ==".JPEG" || $ext ==".gif" || $ext ==".GIF"){
					$size = $_FILES['LRCard']['size'];
					if($size > 0 && $size < 5000000){
						$archive_dir = "LRCards";
						$userfile_tmp_name = $_FILES['LRCard']['tmp_name'];
						if(move_uploaded_file($userfile_tmp_name, "$archive_dir/$LRCardname")){
							/*
								if LRC is successfully uploaded then LRC is stored in database.
							*/
							mysql_query("update student_information set LRCard='$LRCardname' where student_id='$student_id'", $link_id); 
							$flag = "success"; 
							if(mysql_error()!=null){
								die(mysql_error());
							}

						}
						else{
							if(file_exists('LRCard/' . $LRCardname)) {
								unlink('LRCards/' . $LRCardname); 
							}
							rollbackData();
						}
					}
					else{
						if(file_exists('LRCards/' . $LRCardname)) {
							unlink('LRCard/' . $LRCardname); 
						}
						rollbackData();
						die("You can upload LRCard of 5 MB size only. Please, try again.");
					}
				}
				else{
					if(file_exists('LRCards/' . $LRCardname)) {
						unlink('LRCards/' . $LRCardname); 
					}
					rollbackData();
					die("You can upload LRCard of .jpg, .jpeg, .gif extensions only. Please, try again. ");
				}
			} 	
		}
		else{
			$flag="error";
		}
		if($flag == "success"){
			mysql_query(" COMMIT ");
			$flag="success";
			if(mysql_error() != null){
				die(mysql_error());
			}
	    }
	/*
			This block shows the start codes for the upload of the Learner Report Card page 2.
	*/
	
	
	if($result){
			if($_FILES['LRCard2']['name'] != ""){
				$filename = $_FILES['LRCard2']['name'];
				$ext = strrchr($filename,".");
				$LRCard2name = $student_id;
				$LRCard2name .="_". $filename; 
				if($ext ==".jpg" || $ext ==".jpeg" || $ext ==".JPG" || $ext ==".JPEG" || $ext ==".gif" || $ext ==".GIF"){
					$size = $_FILES['LRCard2']['size'];
					if($size > 0 && $size < 5000000){
						$archive_dir = "LRCards2";
						$userfile_tmp_name = $_FILES['LRCard2']['tmp_name'];
						if(move_uploaded_file($userfile_tmp_name, "$archive_dir/$LRCard2name")){
							/*
								if LRC page 2 is successfully uploaded then it will be stored in database.
							*/
							mysql_query("update student_information set LRCard2='$LRCard2name' where student_id='$student_id'", $link_id); 
							$flag = "success"; 
							if(mysql_error()!=null){
								die(mysql_error());
							}

						}
						else{
							if(file_exists('LRCard2/' . $LRCardname)) {
								unlink('LRCards2/' . $LRCardname); 
							}
							rollbackData();
						}
					}
					else{
						if(file_exists('LRCards2/' . $LRCardname)) {
							unlink('LRCard2/' . $LRCardname); 
						}
						rollbackData();
						die("You can upload LRCard page 2 of 5 MB size only. Please try again.");
					}
				}
				else{
					if(file_exists('LRCards2/' . $LRCardname)) {
						unlink('LRCards2/' . $LRCardname); 
					}
					rollbackData();
					die("You can upload LRCard page 2 of .jpg, .jpeg, .gif extensions only. Please try again. ");
				}
			} 	
		}
		else{
			$flag="error";
		}
		if($flag == "success"){
			mysql_query(" COMMIT ");
			$flag="success";
			if(mysql_error() != null){
				die(mysql_error());
			}
	    }
	header("location:Admin_Edit_Student_Info.php?flag=$flag&student_id=$student_id");	  
?>

I would really appreciate if you can add some help to me. ;)

Please have patience and just ignore all other codes which is supppose to be not included.

Edited by phpNOvice
Link to comment
Share on other sites

The issue is in your ajax.php file, specifically on these lines:

$display_string .= "<td><a href='View_Profile.php'>View</a> </td>";
$display_string .= "<td><a href='Admin_Edit_Student_Info.php'>Update</a></td>";
$display_string .= "<td><a href='Admin_Delete_Student.php'>Delete</a></td>";

I'm assuming you have some sort of unique numeric ID associated with each student? You need to edit each of the view/update/delete links to include that id. Something like this:

$display_string .= "<td><a href='View_Profile.php?id=X'>View</a> </td>";
$display_string .= "<td><a href='Admin_Edit_Student_Info.php?id=X'>Update</a></td>";
$display_string .= "<td><a href='Admin_Delete_Student.php?id=X'>Delete</a></td>";

Obviously, the "X" in each would need to be replaced with that student's id.

 

Then, on the View_Profile, Admin_Edit_Student_info and Admin_Delete_Student pages, you would get that student's ID using $_GET, and use that id to retrieve the student's info for Viewing/Editing/Deleting using the database.

 

You can see that sort of approach in my CRUD tutorial: http://www.killersites.com/community/index.php?/topic/3064-basic-php-system-view-edit-add-delete-records-with-mysqli/. In my code, you'll see that I am adding an id to my view/edit/delete links, and retrieving that id on those pages to access the correct information.

Link to comment
Share on other sites

Thank you Ben,

 

Actually i discover the killersites from on of your forum. Honestly, before i write this post i wished you would be that someone i will say giving me replies. Thanks for ample time you gave me. I have just read your reply tonight, and i'll be testing your suggestions tomorrow.

 

 

This is the present situation. On the searchbox, the admin will type a certain student first name. After clicking the search button, all the students which have the same first names will all appear below in this order. (Example the searchbox found out two students with the same first name "Jane". The underlined View, Update, Delete are the link to pages.

 

                                  LRN     First Name     Last Name     Grade     Section     View     Update     Delete

                                    2          Jane                 Doe                 8                A            View      Update     Delete

                                  33          Jane                 Denice             7               C            View      Update      Delete

 

Will your code suggestion in the View/Update/Delete link be still applicable in this example knowing that the students could have same first names with different student id's? Kindly tell me my codes lines of mistakes and its correction.

 

Please be patient. 

Link to comment
Share on other sites

Hello Sir Ben,

 

I have followed you corrections and this is now my code.

$display_string .= "<td><a href='View_Profile.php?id=student_id'>View</a> </td>";
$display_string .= "<td><a href='Admin_Edit_Student_Info.php?id=student_id'>Update</a></td>";
 $display_string .= "<td><a href='Admin_Delete_Student.php?id=student_id'>Delete</a></td>";

The student_id is unique during their sign-up (they cant be registered if there is duplicate or if the student_id is already taken.) Well, im not sure if this is really you are referring to.

 

 

 

Then, on the View_Profile, Admin_Edit_Student_info and Admin_Delete_Student pages, you would get that student's ID using $_GET, and use that id to retrieve the student's info for Viewing/Editing/Deleting using the database

 

Please i'm not really sure how to do this and the $_GET,, but this are the lines of codes that may will analyze my codes.

 

Admin_Edit_Student_Info.php

   include 'Connect.php';
   $student_id = $_REQUEST['student_id'];
   $query = "select * from student_information where student_id = '$student_id'";
   $result = mysql_query($query, $link_id);
   $data = mysql_fetch_array($result);

and this one

<body onLoad="javascript:SetAll()">
<form name="form1" method="post" action="Admin_Edit_Student_Info_Handler.php" onSubmit="return validation()">
 <input type="hidden" name="student_id" value="<?php echo $student_id; ?>;">

and finally let just say what i have done crazy on this line :-)

   <tr class="stylesmall">
          <td width="19%" align="left">First Name : </td>
          <td width="30%" align="left"><input name="first_name" type="text" 
          id="first_name" value="<?php echo $data['first_name']; ?>" 
          size="25"maxlength="20">
          </td>

Probably, if il know my fault on the first_name box, i would also spot the mistake on the other box infos.

 

Hope this will help you analyze my faults.

Link to comment
Share on other sites

Overall, things look good. One thing to note:

$display_string .= "<td><a href='View_Profile.php?id=student_id'>View</a> </td>";
$display_string .= "<td><a href='Admin_Edit_Student_Info.php?id=student_id'>Update</a></td>";
$display_string .= "<td><a href='Admin_Delete_Student.php?id=student_id'>Delete</a></td>";

In this section, you can't just use the string "student_id". That needs to be a variable that holds the ID. So instead, you need to be doing something like this (assuming you have a variable $student_id):

$display_string .= "<td><a href='View_Profile.php?id=$student_id'>View</a> </td>";
$display_string .= "<td><a href='Admin_Edit_Student_Info.php?id=$student_id'>Update</a></td>";
$display_string .= "<td><a href='Admin_Delete_Student.php?id=$student_id'>Delete</a></td>";

Also, you probably want to make sure you are making sure to sanitize any data that you receive from the user/browser, just in case someone edits the URL and tries to make your application do unexpected behavior. If your student_id is numbers only, you might want to do 

$student_id = intval($_REQUEST['student_id']);

to make sure it contains an int. Alternatively, if the student text contains numbers, you should at least be running it through

$student_id = htmlentities($_REQUEST['student_id'], ENT_QUOTES);

Basically, never trust data that you retrieve from the browser in a way that a user can edit, especially if that data is then used in a database query. Always make sure that it either matches the data type you expect, or potentially troublesome characters (quotes, code, etc.) are cleaned, so you reduce unexpected behavior. If you don't, it's likely that you will accidentally allow people more access to your database than you want them to have, potentially allowing them to even delete your database. http://www.w3schools.com/sql/sql_injection.asp

Link to comment
Share on other sites

Hello Sir Ben,,

 

Thank you for the very useful tips your not just helping me what i want but your giving me what i need. I am not yet focus on webpage security this time cause im planning to review after CRUD will function will. But it is a great advantage to hear an advice from you like that. Lucky me, i have showed you some of the codes and your helping me to make it secure.

 

I will try putting the dollar sign now,,hoping eventually it will work this time.

Link to comment
Share on other sites

Hi Sir Ben,

 

I have tried your suggestion

$display_string .= "<td><a href='View_Profile.php?id=$student_id'>View</a> </td>";
 $display_string .= "<td><a href='Admin_Edit_Student_Info.php?id=$student_id'>Update</a></td>";
 $display_string .= "<td><a href='Delete.php?id=$student_id'>Delete</a></td>";

but instead get this notification.

 

Notice: Undefined variable: student_id in C:\xampp\htdocs\a\ajax.php on line 47

Notice: Undefined variable: student_id in C:\xampp\htdocs\a\ajax.php on line 48

Notice: Undefined variable: student_id in C:\xampp\htdocs\a\ajax.php on line 49

 

 

Obviously, i missed declaring it. A little beginner here, let's take this down piece by piece. Please teach me Sir Ben how to declare it and where to place the declaration of this variable.

 

As i have read your previous posts this is the most common questions by everyone the VIEW/EDIT/DELETE links. Hope this will also resolved some of others following this thread now.

Link to comment
Share on other sites

Hello Sir Ben, 

 

i think the issue of redirecting the file to the specific person has been SOLVED as my URL shows like this

 

http://localhost/a/Admin_Edit_Student_Info.php?id=hans

 

considering that hans is the first name of the student.  :clap:

 

 

The next problem left is the target link Admin_Edit_Student_Info.php it notifies me this 

 

Notice: Undefined index: student_id in C:\xampp\htdocs\a\Admin_Edit_Student_Info.php on line 10

include 'Connect.php';
   $student_id = htmlentities($_REQUEST['student_id'], ENT_QUOTES);
   $query = "select * from student_information where student_id = '$student_id'";
   $result = mysql_query($query, $link_id);
   $data = mysql_fetch_array($result);

the line 10 is                            $student_id = htmlentities($_REQUEST['student_id'], ENT_QUOTES);

 

May i ask again what possible cause why the data of student hans isn't supplied in the edit boxes?

Edited by phpNOvice
Link to comment
Share on other sites

If you're passing in "id" in the URL, you need to be retrieving "id", not "student_id". So: "$_REQUEST['id']".

 

All that said, you can't be passing in a student's first name in the URL -- a first name could be shared between multiple students, so you can't be sure that you are editing the right student. Instead, you should be using a numeric id that is unique per student.

Link to comment
Share on other sites

Hello Admin Ben,,

 

Nice additional information from you feels like having a class in here :-)

Thank you i appreciate it.

The edit boxes has been filled up now with previous data of the student.

 

I am now interested in your second paragraph

 

 

you should be using a numeric id that is unique per student.

I think this is now my issues.

 

Everything is going well after your last advise but when i click UPDATE , the browser shows me this notifications

 

Notice: Undefined index: id in C:\xampp\htdocs\a\Admin_Edit_Student_Info.php on line 11

Notice: Undefined index: id in C:\xampp\htdocs\a\Admin_Edit_Student_Info.php on line 12

include 'Connect.php';
    $flag = "";
    $student_id = htmlentities($_REQUEST['id'], ENT_QUOTES);
    $result = mysql_query("SELECT * FROM student_information where student_id='$_GET[id]'");
    $data = mysql_fetch_array($result);   

Do you think I missed the value of the student_id in the record i am trying to update?

Link to comment
Share on other sites

Hello Ben,

 

I've been researching how to declare that value using code in PHP.

Would you pls care to teach me,, i think this is the missing link to make this project goes well. I believe if we could assign an id variable in this UPDATE link,,the same process also happen in VIEW and DELETE links,,

Thus probably will solve the title of this thread,

 

Im asking to sahre some of your knowledge once again.

 

Very respectfully yours, 

 

Giovanne

Link to comment
Share on other sites

Can you post the full file for whichever file has this code (or roughly this code -- I'm not sure if/how it's been changes since you last posted about it):

 

$display_string .= "<td><a href='View_Profile.php?id=student_id'>View</a> </td>";
$display_string .= "<td><a href='Admin_Edit_Student_Info.php?id=student_id'>Update</a></td>";
$display_string .= "<td><a href='Admin_Delete_Student.php?id=student_id'>Delete</a></d>";
Link to comment
Share on other sites

Hi Sir Ben,

 

uhhmmm i sorry i forgot to mention here, i have modified it,,it is simplier than before here are the codes.

<style type="text/css">
<!--
body,td,th {
	font-family: Verdana, Arial, Helvetica, sans-serif;
}
-->
</style>
<?php
 //Connect to MySQL Server
include 'Connect.php';
mysql_connect($host, $dbusername, $dbpassword);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
 // Escape User Input to help prevent SQL Injection
$first_name = mysql_real_escape_string(trim($_GET['first_name']));
// Retrieve data from Query  
$query = "SELECT  student_id, LRN, first_name, last_name, grade, section  FROM student_information WHERE first_name LIKE '%{$first_name}%'";     
$result = mysql_query($query) or die(mysql_error());
 //Generate the output
$searchResults = '';
if(!mysql_num_rows($result))
{
    $searchResults = "<tr><td align='center' colspan='8'><strong>No result(s) found</strong></td></tr>\n";
}
else
{
    // Insert a new row in the table for each person returned
    while($row = mysql_fetch_array($result))
    {
        $student_id = $row['student_id']; 
        $searchResults .= "<tr>\n";
        $searchResults .= "  <td>{$row['LRN']}</td>\n";
        $searchResults .= "  <td>{$row['first_name']}</td>\n";
        $searchResults .= "  <td>{$row['last_name']}</td>\n";
        $searchResults .= "  <td>{$row['grade']}</td>\n";
        $searchResults .= "  <td>{$row['section']}</td>\n";
        $searchResults .= "  <td><a href='View_Profile.php?id={$student_id}'>View</a> </td>\n";
        $searchResults .= "  <td><a href='Admin_Edit_Student_Info.php?id={$student_id}'>Update</a></td>\n";
        $searchResults .= "  <td><a href='Admin_Delete_Student.php?id={$student_id}'>Delete</a></td>\n";
        $searchResults .= "</tr>\n";
    }
}
 ?>
<html>
<head></head>
<body>
 
<table border='1' cellpadding='10' cellspacing='1' align='center'>
    <tr align='center'>
        <th>LR Number</th>
        <th>F i r s t   N a m e</th>
        <th>L a s t   N a m e</th>
        <th>Grade</th>
        <th>Section</th>
        <th>View</th>
        <th>Update</th>
        <th>Delete</th>
    </tr>
    <?php echo $searchResults; ?>
</table>
 
</body>
</html>

it's in the line 37-39 i just posted the whole codes for the benefits of the followers and viewers also in this thread.

Please advise to fix the undefined index.

Link to comment
Share on other sites

Hi Ben,

 

That codes serve as handler for Admin_Home.php i try to screenshot the browser but i can be able to post here. Apparently this is how it looks like

 

While searching for a particular student with a first name "van". 

 

With a SEARCH BAR on top after clicking SEARCH Button. 

 

This one displays below

 

LRN     First Name     Last Name     Grade     Section     View     Update     Delete

  2          van                 dam                 8                A            View      Update     Delete

 

and if we are going to click the UPDATE link we will be directed to URL

 

http://localhost/a/Admin_Edit_Student_Info.php?id=van

 

 

Hope i get your point as per info you need to know.

Link to comment
Share on other sites

OK. So if the $student_id value is "van", you need to change your database to make that student id a unique, numeric number. "van" isn't unique -- there could be other students with the name of "Van". So that's the next step -- you'd need to wipe your student_id column in the database, and set up up as a int, with auto_increment on, so that new rows will automatically contain a unique number (you'll need to update existing rows with unique numbers).

Link to comment
Share on other sites

Hello Sir Ben,

 

i have followed your advise and when im going to click the UPDATE link now it will direct me to the URL

 

http://localhost/a/Admin_Edit_Student_Info.php?id=1

 

and if i click the update button it will direct me to the URL

 

http://localhost/a/Admin_Edit_Student_Info.php?flag=success&student_id=1;

 

and the specific student infos are updated in the database.

 

But why i am still getting the same notification.

 

Notice: Undefined index: id in C:\xampp\htdocs\a\Admin_Edit_Student_Info.php on line 11

Notice: Undefined index: id in C:\xampp\htdocs\a\Admin_Edit_Student_Info.php on line 12

 

i hope this is not too much of your time but you are the only one who has followed the series of mistakes and series of solutions in this problem thread.

 

Please advise.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...