Solved

PHP - Record ID not passing to second page

Posted on 2014-02-28
8
1,764 Views
Last Modified: 2014-03-03
Trying to get a page to bring up the record details of the record that was clicked on.  Here is the page with the records displayed.

 <?php
error_reporting(0);

if ($_REQUEST['submit']) {
 
 
$term = $_POST['term'];
 
$XX = "<br><br><h2> <center> No Record Found, Search Again Please </center> </h2>";  
 
 $sql = mysql_query("select * from information where firstname like '%$term%'
                     or lastname like '%$term%'  or ID like '%$term%'
                     or phonenumber like '%$term%' or email like '%$term%' Order by lastname ASC")
   or die('Error in query : $sql. ' .mysql_error());
   
   
  if (empty($term)) {
   
echo '<script language="javascript">';
echo 'alert("Text field cannot be empty. Please Try it again.")';
echo '</script>';
 header( "refresh:2; url=index.php" ); 
   }
  
else if (mysql_num_rows($sql) > 0) 
{            
   $i = 1;
 while ($row = mysql_fetch_array($sql)) {
                // Print out the contents of the entry 
				
				
                echo '<tr>';
                echo '<td>' . $i . '</td>';
		echo '<td><a href="info.php?id='.$row['id'].'">'.$row['lastname'].'</a></td>';
                echo '<td>' . $row['firstname'] . '</td>';
                echo '<td>' . $row['email'] . '</td>';
                echo '<td>' . $row['phonenumber'] . '</td>';
		echo '<td> <img src="'. $row['s_img']. '" width="102" height="111"/></td>';
                $i++;
            }
 } 
else 
{
echo '<script language="javascript">';
echo 'alert("Sorry No Record Found in the Database.")';
echo '</script>';
}
}

?>      

Open in new window



And this is the second page where it is supposed to be passed but the data is not showing

<?php
   require_once('header.php');
   if(isset($_GET['id']) && !empty($_GET['id']) && is_numeric($_GET['id'])){
     $where = "WHERE `id` = '".$_GET['id']."'";
     $query1 = "SELECT * FROM `information` ".$where;	 
	 if($result = $mysql->query($query1)){
	    $row = $result->mysql_fetch_array();
	 }
   }
?>

<table class="display_field" >
			    <tr>
						<td colspan=3>
						<!-- avarat -->
						<div id="avatar">
	<img src="<?php echo $row['s_img']; ?>" width="102" height="111"/>
						
                        </div>
						<!-- /avarat -->
						</td>
						<td align="center"></td>
						<td></td>
				</tr>
			    <tr><td width="8%">Last Name </td><td align="center">:</td><td><?php echo $row['lastname']; ?></td></tr>
				<tr><td>First Name </td><td align="center">:</td><td><?php echo $row['firstname']; ?></td></tr>
				<tr><td>Email</td><td align="center">:</td><td><?php echo $row['email']; ?></td></tr>
			    <tr><td>Phone Number </td><td align="center">:</td><td><?php echo $row['phonenumber']; ?></td></tr>
	  </table>

Open in new window


Thanks
0
Comment
Question by:JohnMac328
  • 5
  • 3
8 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39896236
We have an article here at EE that explores this design pattern.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_12335-PHP-and-MySQLi-Table-Maintenance.html

From the look of the code, I would guess that you're relatively new to PHP.  Some good "anchor" learning resources are listed in this article.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39896257
Try changing the top of the second script to something like this.  Obviously I cannot test this because I do not have your data set, but this should help you get the id escaped correctly.

You're also going to be facing a data base conversion soon.  PHP is doing away with MySQL support.  This article explains why and what you must do to keep your scripts running.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

<?php
error_reporting(E_ALL);

require_once('header.php');

// IF THE id= REQUEST VARIABLE IS MISSING
if(empty($_GET['id'])) trigger_error('URL PARAMETER id= MUST BE AN INTEGER', E_USER_ERROR);

// ASSUMES THE EXISTENCE OF THE $mysql CONNECTION OBJECT
$id     = $mysql->real_escape_string($_GET['id']);

// USE THE ESCAPED VALUE TO CONSTRUCT THE QUERY
$where  = "WHERE id = '$id' LIMIT 1";
$query1 = "SELECT * FROM `information` $where";

// RUN THE QUERY AND TEST FOR SUCCESS OR FAILURE
$result = $mysql->query($query1);
if (!$result) trigger_error("FAIL: $query1 " . $mysql->error, E_USER_ERROR);

// RETRIEVE THE ROW IN THE FORM OF AN ARRAY AND DISPLAY THE DATA
$row    = $result->fetch_assoc();
var_dump($row);

Open in new window

0
 

Author Comment

by:JohnMac328
ID: 39900836
Hi Ray

Thanks for the information - I am 53 and thought I would play around with a couple of examples - one example does pass the id correctly.  I then  tried to convert another that does display records but does not pass the id to a new page.  That is where I am now - it will not pass the id - I put in your script which correctly states

Fatal error: URL PARAMETER id= MUST BE AN INTEGER in C:\inetpub\wwwroot\PHP_SearchRecordsUpdated\info.php on line 8

The field type is int for id in the information table - here are the complete pages for each - I appreciate any help

index.php
<html>
    <head>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
<style>


p {text-indent:60px;
   font-size:20px;
}
  

.textboxclass {
height: 50px;
width: 270px;
}

.text-center {
    text-align: center !important;
}

</style>
        <title>Search the Database</title>
    </head
><?php 
include('header.php');
?>

    <body>
 <script type="text/javascript">
        $(function() {
            $("#term").focus();
        });
    </script> 
 <br> 
<div class="alert alert-info"><center> <h3>Record Search System </h3></center> </div>
<br>
       <form method="post" action="" name="form1" id="form1">   
   <p>
     Type the First Name, Last Name,Phone Number, Email Address or ID Number of the User</p>
	 <br><br>
	 <p>Search Record  <input type="text" name="term" id="term" class="textboxclass" /></p> 
     
   <p> <input type="submit" button class="btn btn-primary" 
    name="submit" value="Search Record" 
   title="Click here to search record in the database.">
   </button>  </p>
   </p>
    </form>
	
	
	<div class="container">
    <div class="alert alert-success"><center> <h4>Search Record Results </h4></center> </div>
<br />

<table  class="table table-striped table-bordered">
                          
                            <thead>
						
                                <tr>
                                    <th class="text-center">Record No.</th>
                                    <th class="text-center">Last Name</th>
									<th class="text-center">First Name</th>
                                    <th class="text-center">Email Address</th>
                                    <th class="text-center">Phone Number</th>
                                 
                                </tr>
                            </thead>
                            <tbody>
					

 <?php
error_reporting(0);

if ($_REQUEST['submit']) {
 
 
$term = $_POST['term'];
 
$XX = "<br><br><h2> <center> No Record Found, Search Again Please </center> </h2>";  
 
 $result = mysql_query("select * from information where firstname like '%$term%'
                     or lastname like '%$term%'  or ID like '%$term%'
                     or phonenumber like '%$term%' or email like '%$term%' Order by lastname ASC")
   or die('Error in query : $result. ' .mysql_error());
   
   
  if (empty($term)) {
   
echo '<script language="javascript">';
echo 'alert("Text field cannot be empty. Please Try it again.")';
echo '</script>';
 header( "refresh:2; url=index.php" ); 
   }
  
else if (mysql_num_rows($result) > 0) 
{            
   $i = 1;
 while ($row = mysql_fetch_assoc($result)) {
                // Print out the contents of the entry 
				
				
                echo '<tr>';
                echo '<td>' . $i . '</td>';
				echo '<td><a href="info.php?id='.$row['id'].'">'.$row['lastname'].'</a></td>';
                echo '<td>' . $row['firstname'] . '</td>';
                echo '<td>' . $row['email'] . '</td>';
                echo '<td>' . $row['phonenumber'] . '</td>';
				echo '<td> <img src="'. $row['s_img']. '" width="102" height="111"/></td>';
                $i++;
            }
 } 
else 
{
echo '<script language="javascript">';
echo 'alert("Sorry No Record Found in the Database.")';
echo '</script>';
}
}

?>      
 
      </tbody>
       <tbody></tbody>
    </table>
  </div>

   </body>
</html>

Open in new window


Info.php


<?php
ini_set('display_errors',1);
error_reporting(E_ALL);

require_once('header.php');

// IF THE id= REQUEST VARIABLE IS MISSING
if(empty($_GET['id'])) trigger_error('URL PARAMETER id= MUST BE AN INTEGER', E_USER_ERROR);

// ASSUMES THE EXISTENCE OF THE $mysql CONNECTION OBJECT
$id     = $mysql->real_escape_string($_GET['id']);

// USE THE ESCAPED VALUE TO CONSTRUCT THE QUERY
$where  = "WHERE id = '$id' LIMIT 1";
$query1 = "SELECT * FROM `information` $where";

// RUN THE QUERY AND TEST FOR SUCCESS OR FAILURE
$result = $mysql->query($query1);
if (!$result) trigger_error("FAIL: $query1 " . $mysql->error, E_USER_ERROR);

// RETRIEVE THE ROW IN THE FORM OF AN ARRAY AND DISPLAY THE DATA
$row    = $result->fetch_assoc();
var_dump($row);
?>


<?php

   require_once('header.php');
   if(isset($_GET['id']) && !empty($_GET['id']) && is_numeric($_GET['id'])){
     $where = "WHERE `id` = '".$_GET['id']."'";
     $query1 = "SELECT * FROM `information` ".$where;	 
	 if($result = $mysqli->query($query1)){
	    $row = $result->mysql_fetch_assoc();
	 }
   }
?>
<!DOCTYPE HTML>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>Information</title>
		<link type="text/css"  rel="stylesheet" href="stylesheet.css" />
		<link type="text/css"  rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
		<script type="text/javascript" src="js/jquery.min.js"></script>
		<script type="text/javascript" src="js/jquery.Jcrop.js"></script>
	    <script type="text/javascript" src="js/jquery.form.js"></script>
		
	</head>
	<body>
	  <h1>Info</h1>
	   		  
	   <table class="display_field" >
			    <tr>
						<td colspan=3>
						<!-- avarat -->
						<div id="avatar">
						<img src="<?php echo $row['s_img']; ?>" width="102" height="111"/>
						
                        </div>
						<!-- /avarat -->
						</td>
						<td align="center"></td>
						<td></td>
				</tr>
			    <tr><td width="8%">Last Name </td><td align="center">:</td><td><?php echo $row['lastname']; ?></td></tr>
				<tr><td>First Name </td><td align="center">:</td><td><?php echo $row['firstname']; ?></td></tr>
				<tr><td>Email</td><td align="center">:</td><td><?php echo $row['email']; ?></td></tr>
			    <tr><td>Phone Number </td><td align="center">:</td><td><?php echo $row['phonenumber']; ?></td></tr>
	  </table>
			    	
	</body>
</html>

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39900949
Here is a link to the introductory tutorial on using forms with PHP.

Some explanation...

There are two commonly used request methods, GET and POST.  GET method requests are information-only requests and are idempotent.  POST method requests can change the data model.  The request method is part of the <form> tag in the method= attribute.  The default value is GET.

Each <input> control in an HTML form has two attributes that are used by the PHP action script: name= and value=.  In the request arrays (either $_GET or $_POST) the array key is the information from the name= attribute and the array value is the information from the value= attribute.

To see how this works, try these URLs:
http://www.iconoun.com/demo/temp_johnmac328.php?id=123
http://www.iconoun.com/demo/temp_johnmac328.php?id=ABCXYZ
http://www.iconoun.com/demo/temp_johnmac328.php?id=
http://www.iconoun.com/demo/temp_johnmac328.php

<?php // demo/temp_johnmac328.php
error_reporting(E_ALL);


// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28377449.html


// IF THERE IS A REQUEST
if (!empty($_GET))
{
    // IF THERE IS NO REQUEST id= ATTRIBUTE
    if (empty($_GET['id']))
    {
        trigger_error('MISSING id= URL PARAMETER', E_USER_NOTICE);
    }
    // PROCESS THE REQUEST HERE WITH ANY LOGIC THAT MAKES SENSE
    else
    {
        echo PHP_EOL . 'THE <b>id=</b> URL PARAMETER CONTAINS: <b>' . $_GET['id'] . '</b>';
    }
}

// PHP PROCESSING COMPLETE, PUT UP THE FORM FOR INPUT
?>

<form>
ENTER THE 'id' HERE:
<input name="id" />
<input type="submit" />
</form>

Open in new window

Going forward, if you're not completely, 100% certain about what a PHP function does, you can look the function up on the PHP.net web site.  Example: trigger_error().

I think if you follow the information about name= and value= back into your script you will quickly see where the confusion might be coming from.
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 

Author Comment

by:JohnMac328
ID: 39901061
I guess my confusion is coming from the fact that the original example I am trying to replicate does not use a form and passes the record id with no problems.

index.php

<?php 
 require_once('connect.php');
  $query = "SELECT * FROM `student_info`";
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Student List</title>
<link type="text/css"  rel="stylesheet" href="stylesheet.css" />
</head>
<body>
<h1>Student Record System</h1>

<br/>
<br/>
<table class="display_table">
  <thead>
    <tr>
      <th width="5%">No</th>
      <th>Student</th>
      <th width="10%" >Class</th>
    </tr>
  </thead>
  <tbody>
    <?php
                   if($result = $mysqli->query($query)){
				       $no = 1;
                        while($row = $result->fetch_assoc()){
						  echo "<tr>
						         <td>$no</td>
						         <td><a href='student_info.php?s_id=".$row['s_id']."'>".$row['name']."</a></td>
						         <td>".$row['class']."</td>
								 <td><img src='".$row['s_img']."' width='102' height='111'/></td>
                                
						       </tr>"
							   ;
						   $no++;	   
						}
                     } 
                ?>
  </tbody>
</table>
</body>
</html>

Open in new window



student_info.php

<?php
   require_once('connect.php');
   if(isset($_GET['s_id']) && !empty($_GET['s_id']) && is_numeric($_GET['s_id'])){
     $where = "WHERE `s_id` = '".$_GET['s_id']."'";
     $query1 = "SELECT * FROM `student_info` ".$where;	 
	 if($result = $mysqli->query($query1)){
	    $row = $result->fetch_assoc();
	 }
   }
     $term = (isset($_GET['term']))?$_GET['term']:'term_1';
?>
<!DOCTYPE HTML>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>Student Information</title>
		<link type="text/css"  rel="stylesheet" href="stylesheet.css" />
		<link type="text/css"  rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
		<script type="text/javascript" src="js/jquery.min.js"></script>
		<script type="text/javascript" src="js/jquery.Jcrop.js"></script>
	    <script type="text/javascript" src="js/jquery.form.js"></script>
		<script type="text/javascript" >
		  $(document).ready(function(){
		     $('#avatar').click(function(){
			    $('#profile_pic').submit(); 
			 });	 
		  });
		</script>
		
	</head>
	<body>
	  <h1>Student Record System</h1>
	   		  
	   <table class="display_field" >
			    <tr>
						<td colspan=3>
						<!-- avarat -->
						<div id="avatar">
						<img src="<?php echo $row['s_img']; ?>" width="102" height="111"/>
						</div>
						<!-- /avarat -->
						</td>
						<td align="center"></td>
						<td></td>
				</tr>
			    <tr><td width="8%">Name </td><td align="center">:</td><td><?php echo $row['name']; ?></td></tr>
				<tr><td>School </td><td align="center">:</td><td><?php echo $row['school']; ?></td></tr>
				<tr><td>Class</td><td align="center">:</td><td><?php echo $row['class']; ?></td></tr>
			    <tr><td>RollNo </td><td align="center">:</td><td><?php echo $row['roll']; ?></td></tr>
			    <tr><td>Address</td> <td align="center">:</td><td><?php echo $row['address']; ?></td></tr>
	  </table>
	     <div class="nav">
         <a href="add.php?s_id=<?php echo $_GET['s_id'];?>&term=<?php echo $term;?>">Add</a>|
         <a href="edit.php?s_id=<?php echo $_GET['s_id'];?>&term=<?php echo $term;?>">Edit</a>|
         <a href="delete.php?s_id=<?php echo $_GET['s_id'];?>">Delete</a>|
         <a href="index.php">Main</a></div>
	    
	   <table class="term_nav">
				<tr>
					<td><a href="<?php echo $_SERVER['PHP_SELF']; ?>?term=term_1&s_id=<?php echo $_GET['s_id']; ?>">First Term</a></td>
					<td><a href="<?php echo $_SERVER['PHP_SELF']; ?>?term=term_2&s_id=<?php echo $_GET['s_id']; ?>">Second Term</a></td>
					<td><a href="<?php echo $_SERVER['PHP_SELF']; ?>?term=term_3&s_id=<?php echo $_GET['s_id']; ?>">Third Term</a></td>
			   </tr>
	  </table>
			    <?php
				   $query = "SELECT * FROM `$term` ".$where;
				   if($result = $mysqli->query($query)){
				     $num = $result->num_rows;
					 if($num === 0){
					   echo '<table class="display_table"><tr><td class="empty">Not Avilable</td></tr></table>';
					 }elseif($num === 1){
					 ?>
					 <table class="display_table">
						<thead>
						<tr><th width="5%">No</th><th>Subjects</th><th width="13%">Full Marks</th><th width="13%">Marks</th><th width="18%">Percentage</th></tr>
						</thead>
						<tbody>
					 <?php
					    $rows = $result->fetch_assoc();
						 $subjects = unserialize($rows['subjects']);
						 $marks = unserialize($rows['marks']);
						 $fullmarks = unserialize($rows['full_marks']);
						 $n = 1;
						 $totalmarks = array_sum($marks);
						 $totalf_marks = array_sum($fullmarks);
						 $per = round($totalmarks*100/$totalf_marks,2);
						for($i = 0; $i < count($subjects); $i++){
						  echo "<tr>
						           <td>". $n++."</td>
								   <td>".$subjects[$i]."</td>
								   <td>".$fullmarks[$i]."</td>
								   <td>".$marks[$i]."</td>
								   <td>".round($marks[$i]*100/$fullmarks[$i],2)."%</td>
						        </tr>";
						} 
					 ?>
					 <tr>
						<th colspan = 2 align="center">Total</th>
						<th align="left" style="padding-left:15px"><?php echo $totalf_marks; ?></th>
						<th align="left" style="padding-left:15px"><?php echo $totalmarks; ?></th>
						<th align="left" style="padding-left:15px"><?php echo $per.'%' ?></th>
				    </tr>	
				</tbody>
		 </table>
		    <div class="nav"><a href="graph.php?s_id=<?php echo $_GET['s_id'];?>&term=<?php echo $term;?>">Graph</a></a></div>
					 <?php
					 }
				   }
				?>
			    	
	</body>
</html>

Open in new window

0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 39901204
Let me try to deconstruct this a little for you.  From the first code example, index.php line 3.  This says, "Select all of the columns from the table named student_info without any particular selection criteria and in any order that the db engine wants to use."

$query = "SELECT * FROM `student_info`";

Line 29 says "Retrieve each row from the results set one at a time and assign the data to an associative array named $row.  In $row the column names are the associative array keys and the column values are the array data elements

while($row = $result->fetch_assoc()){

Line 32, inside the while() loop says, "Create an HTML fragment with an anchor tag that links to "student_info.php" and give the anchor tag a GET-method request argument that is named s_id with a value equal to the contents of $row['s_id'].  This will give you a link that looks something like <a href='student_info.php?s_id=3'>Ray</a>

<td><a href='student_info.php?s_id=".$row['s_id']."'>".$row['name']."</a></td>

If you use an HTML form to create a GET request, the URL of the request will contain the request arguments.  That's why I showed you some different URLs here, so you could see how they worked.

In the most recent version of "student_info.php" lines 3 and 4 have s_id instead of id.  The original version of "student_info.php" uses id instead of s_id.

In the most recent version of "student_info.php" we find this on line 4.  It is a terribly dangerous security exposure to copy unfiltered information in a SQL statement.  See AntiPractice #19.  This is the way data bases get stolen / hacked / destroyed.  

$where = "WHERE `s_id` = '".$_GET['s_id']."'";

Same script, lines 6,7,8 say "Run the query and assign the results object to $result.  Then if there is any non-false value in $result, call the fetch_assoc() method and assign the output (an associative array) to $row.

if($result = $mysqli->query($query1)){
    $row = $result->fetch_assoc();
}


Same script, line 39 says, "Use the $row array, no matter what data is present in the variable, even if the variable is undefined.  And most importantly, do not tell me if there are any errors!"  The suppression of errors is one of PHP's worst features.  See AntiPractice #5 to understand why this is a killer for novice programmers, and what you must do to get PHP to tell you about errors.

<img src="<?php echo $row['s_img']; ?>" width="102" height="111"/>

I really think you would benefit from an introductory course in how PHP works.  A good study and reference book is Welling/Thompson.  Dependable study resources are available in this article.  Plan to spend at least a month or two learning this stuff.  There is nothing magic or "hard" about what you're trying to do, but it takes time and structured learning to know where you can "just copy stuff" and where you must exercise attention to details.

Best of luck with your project, ~Ray
0
 

Author Closing Comment

by:JohnMac328
ID: 39901229
Thanks for the info Ray - I do enjoy coldfusion very much but it is time to learn something new.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39901252
Thanks for the points.  CF and PHP handle request variables somewhat differently.  Once you see what PHP is doing, it will be pretty easy to make sense of the scripts.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Use these top 10 tips to master the art of email signature design. Create an email signature design that will easily wow recipients, promote your brand and highlight your professionalism.
Building a website can seem like a daunting task to the uninitiated but it really only requires knowledge of two basic languages: HTML and CSS.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now