Jump to content

Undefined variable: _GET['id'] in C:\xampp\htdocs\myreliantservices\courtdirectoryview.php on line 42


mike3075

Recommended Posts

I am stuck on this form.  I can use <a href='courtdirectoryview.php?id={$row['id']}' target='_blank'> to pass the id number from courtdirectory.php to courtdirectoryview.php and all the data from the MySQL db is displayed correctly.  When I make changes to test the update query and I click the Update button I get the error in the title.  Line 42 is:  echo "WHY DOES THE ID NUMBER NOT SHOW UP HERE WHEN THE UPDATE BUTTON IS CLICKED: " .$_GET['id']. "<br>";  Any suggestions or advice will be greatly appreciated

<!DOCTYPE html>
  <head>
    <link rel="stylesheet" href="css/main-forcourtdirectory.css">
  </head>

  <?php
    //============================================================================================================================================================================================/
    //OPEN CONNECTION TO MYSQL ON LOCALHOST=======================================================================================================================================================/
    $dbhost = 'localhost' ;
    $username = 'root' ;
    $password = '' ;
    $conn = mysqli_connect("$dbhost", "$username", "$password");
    if (!$conn) { 
      die('Could not connect: ' . mysqli_error()); 
    }
    //CLOSE CONNECTION TO MYSQL ON LOCALHOST======================================================================================================================================================/
    //============================================================================================================================================================================================/

    //============================================================================================================================================================================================/
    //OPEN CONNECTION TO MYSQL ON LOCALHOST=======================================================================================================================================================/
    mysqli_select_db($conn, "courtdirectory");
    //CLOSE CONNECTION TO MYSQL ON LOCALHOST======================================================================================================================================================/
    //============================================================================================================================================================================================/

    //============================================================================================================================================================================================/
    // DEFINE VARIABLES AND SET EMPTY VALUES======================================================================================================================================================/
    // PROSECUTOR VARIABLES=======================================================================================================================================================================/
    $varprosecutor = $varprosecutoraddress = $varprosecutorphone = $varprosecutorfax = $varprosecutornotes = "";
    //============================================================================================================================================================================================/
    // PROSECUTOR ERROR VARIABLES=================================================================================================================================================================/
    $varprosecutorErr = $varprosecutoraddressErr = $varprosecutorphoneErr = $varprosecutorfaxErr = $varprosecutornotesErr = "";
    //============================================================================================================================================================================================/
    // OTHER VARIABLES============================================================================================================================================================================/
    $varmyid = $varipaddress = $formerror = $success = "";
    //============================================================================================================================================================================================/

    //============================================================================================================================================================================================/
    //FORM SUBMITTED WITH POST METHOD=============================================================================================================================================================/
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
    //============================================================================================================================================================================================/

      echo "WHY DOES THE ID NUMBER NOT SHOW UP HERE WHEN THE UPDATE BUTTON IS CLICKED: " .$_GET['id']. "<br>";
  
      //==========================================================================================================================================================================================/
      //START UPDATE SQL==========================================================================================================================================================================/
      //NONE OF THIS CODE WILL WORK UNTIL I CAN GET THE ID NUMBER=================================================================================================================================/

      //$result2 = mysqli_query($conn, "UPDATE courtdirectory SET prosecutor='$varprosecutor' WHERE courtdirectory.id = ($myid)") or die("Error: " . mysqli_error($conn));
      //$retval3 = mysqli_query($conn, $result2);
      //if (mysqli_query($conn, $result2)) {
      //  echo "Record updated successfully";
      //} else {
      //  echo "Error updating record: " . mysqli_error($conn);
      //}

      //END UPDATE SQL============================================================================================================================================================================/
      //==========================================================================================================================================================================================/

    }else{
      if (isset($_GET['id'])) {
        $myid = $_GET['id'];
        $varmyid = $myid;
      }
      echo "I CAN GET THE ID NUMBER FROM THE COURTDIRECTORY.PHP PAGE: " .$myid. "<br>";
      echo "I CAN SET THIS VARIABLE TO THE THE ID NUMBER: " .$varmyid. "<br>";

      echo "<body>";
    
        if (isset($_GET['id'])) {
          $myid = $_GET['id'];
        }
        $bulletinsQuery = "SELECT * FROM courtdirectory";
        $bulletins = $conn->query($bulletinsQuery);
        if (isset($_GET['id'])) {
          $myid = $_GET['id'];
        }

        echo "<form action= " .$_SERVER['PHP_SELF']. " method='post'>";
                
          echo "<table class='courtdirectorytable'>";
          echo "<tbody>";
          echo "<tr>";
          echo "<th class='county'>County</th>";
          echo "<th class='city'>City</th>";
          echo "<th class='court'>Court</th>";
          echo "<th class='judge'>Judge</th>";
          echo "<th class='address'>Address</th>";
          echo "<th class='phone'>Phone</th>";
          echo "<th class='fax'>Fax</th>";
          echo "<th class='notes'>Court Notes</th>";
          echo "</tr>";
      
          $sql2 = "SELECT * FROM courtdirectory WHERE courtdirectory.id = ($myid)";
          $retval2 = mysqli_query($conn, $sql2);
          $result2 = mysqli_query($conn, "SELECT * FROM courtdirectory WHERE courtdirectory.id = ($myid)") or die("Error: " . mysqli_error($conn));
          while($row = mysqli_fetch_array($retval2, MYSQLI_ASSOC)) {
            $varprosecutor = $row['prosecutor'];
            $varprosecutoraddress =  str_replace(',', '&#13;&#10;', $row['prosecutoraddress1']);
            $varprosecutorphone = $row['prosecutorphone'];
            $varprosecutorfax = $row['prosecutorfax'];
            $varprosecutornotes = $row['prosecutornotes'];
            $varprosecutornotes =  str_replace(['<br/>','</br>','<br />'], '&#13;&#10;', $row['prosecutornotes']);
    
            echo "<tr>";
            echo "<td class='county'>" .$row['county']. "</td>";
            echo "<td class='city'>" .$row['city']. "</td>";
            echo "<td class='court'>" .$row['court']. "</td>";
            echo "<td class='judge'>" .$row['judge']. "</td>";
            echo "<td class='address'>" .$row['address']. "</td>";
            echo "<td class='phone'>" .$row['phone']. "</td>";
            echo "<td class='fax'>" .$row['fax']. "</td>";
            echo "<td class='notes'>" .$row['notes']. "</td>";
            echo "</tr>";
            echo "</tbody>";
            echo "</table>";
            echo "</br>";
            echo "<table class='courtdirectorytable'>";
            echo "<tbody>";
            echo "<tr>";
            echo "<th class='prosecutor'>Prosecutor</th>";
            echo "<th class='prosecutoraddress'>Prosecutor Address</th>";
            echo "<th class='prosecutorphone'>Prosecutor Phone</th>";
            echo "<th class='prosecutorfax'>Prosecutor Fax</th>";
            echo "<th class='prosecutornotes'>Prosecutor Notes</th>";
            echo "</tr>";
            echo "<tr>";
            echo "<td class='prosecutor'><textarea class='prosecutor' value='$varprosecutor'>$varprosecutor</textarea></td>";
            echo "<td class='prosecutoraddress'><textarea class='prosecutoraddress' value='$varprosecutoraddress'>$varprosecutoraddress</textarea></td>";
            echo "<td class='prosecutorphone'><textarea class='prosecutorphone' value='$varprosecutorphone'>$varprosecutorphone</textarea></td>";
            echo "<td class='prosecutorfax'><textarea class='prosecutorfax' value='$varprosecutorfax'>$varprosecutorfax</textarea></td>";
            echo "<td class='prosecutornotes'><textarea class='prosecutornotes' value='$varprosecutornotes'>$varprosecutornotes</textarea></td>";
            echo "</tr>";
            echo "</tbody>";
            echo "</table>";
            echo "<table class='submitbutton'>";
            echo "<tbody>";
            echo "<tr>";
            echo "<td class='submitbutton'><button type='submit' class='courtdirectory-submit' name='submit' tabindex='6' data-submit='...Sendng'>Update</button></td>";
            echo "</tr>";
            echo "</tbody>";
            echo "</table>";
          }
        echo "</form>";
      echo "</body>";
    }
  ?>
</html>

 

Edited by mike3075
had to change some code
Link to comment
Share on other sites

  • mike3075 changed the title to Undefined variable: _GET['id'] in C:\xampp\htdocs\myreliantservices\courtdirectoryview.php on line 42

Submit the form and look at the URL. Do you see an "id" in there?

If you want the form to submit back to the same page then remove the form's action entirely. Because the default for a form without one is to submit back to the same page.

 

And stop using PHP_SELF.

  • Like 1
Link to comment
Share on other sites

The problem with PHP_SELF is it points back to the exact same script and it's ridiculously insecure. If you want to submit to the page, remove the action or use the filename itself instead of PHP_SELF.

Maybe I'm just missing something, but why are you using POST as the request method but trying to use $_GET['id']? That might be the source of your conflict, since as far as I know, GET and POST variables on their own do not share data values. You may want to use your browser's dev console to see the submitted data.

I'd use var_dump to see what the values are before proceeding, like so:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	// This is a post request
	echo $_GET['id'] . "\n";
	var_dump($_GET['id']);
}

Then you can test if the values went through. If your values are null, that means they didn't go through.

Also, I know it's not primary feedback, but since I'm here I might as well chip in: you really should consider using PDO or prepared statements, since your concatenated SQL queries as they are right now are ripe for SQL injection.

Edit: Oh, and since you gave us your MySQL credentials, you might want to change that (since now everyone knows you use the root account). 😜

Edited by Pixeel
Link to comment
Share on other sites

I am totally confused by your code here.  You have what looks like a query attempt using a unique syntax that is not mysqli but never use the results (if there are any).  You then run the same query twice but never use the 2nd set of results, so why bother?

Here is a cleaned up version of your code that may be easier to decipher, or at least easier to read that may help you code better in the future.  I really don't see why you are building 3 html tables either.

<!DOCTYPE html>
<head>
<link rel="stylesheet" href="css/main-forcourtdirectory.css">
</head>
<?php
$dbhost = 'localhost' ;
$username = 'root' ;
$password = '' ;
$conn = mysqli_connect("$dbhost", "$username", "$password");
if (!$conn) 
{ 
	die('Could not connect: ' . mysqli_error()); 
}
mysqli_select_db($conn, "courtdirectory");
$varprosecutor = $varprosecutoraddress = $varprosecutorphone = $varprosecutorfax = $varprosecutornotes = "";
$varprosecutorErr = $varprosecutoraddressErr = $varprosecutorphoneErr = $varprosecutorfaxErr = $varprosecutornotesErr = "";
$varmyid = $varipaddress = $formerror = $success = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") 
{
	echo "WHY DOES THE ID NUMBER NOT SHOW UP HERE WHEN THE UPDATE BUTTON IS CLICKED: " .$_GET['id']. "<br>";
}
else
{
	if (isset($_GET['id'])) 
	{
		$myid = $_GET['id'];
		$varmyid = $myid;
	}
	echo "I CAN GET THE ID NUMBER FROM THE COURTDIRECTORY.PHP PAGE: " .$myid. "<br>";
	echo "I CAN SET THIS VARIABLE TO THE THE ID NUMBER: " .$varmyid. "<br>";
	echo "<body>";

// WHY DO THIS AGAIN???

 if (isset($_GET['id'])) 
	{
		$myid = $_GET['id'];
	}
	$bulletinsQuery = "SELECT * FROM courtdirectory";
	//  WHAT IS THIS LINE SUPPOSED TO BE???
	//  WHAT IS THIS LINE SUPPOSED TO BE???
	//  WHAT IS THIS LINE SUPPOSED TO BE???
	$bulletins = $conn->query($bulletinsQuery);

// WHY DO THIS A 3RD TIME???

	if (isset($_GET['id'])) 
	{
		$myid = $_GET['id'];
	}
	echo "<form action= " .$_SERVER['PHP_SELF']. " method='post'>";
	echo "<table class='courtdirectorytable'>
		<tbody>
		<tr>
		<th class='county'>County</th>
		<th class='city'>City</th>
		<th class='court'>Court</th>
		<th class='judge'>Judge</th>
		<th class='address'>Address</th>
		<th class='phone'>Phone</th>
		<th class='fax'>Fax</th>
		<th class='notes'>Court Notes</th>
		</tr>";
	//   Query 1
 	$sql2 = "SELECT * FROM courtdirectory WHERE courtdirectory.id = '$myid'";
	$retval2 = mysqli_query($conn, $sql2);	//	did this query run successful???
	//   Query 2 
 	$result2 = mysqli_query($conn, "SELECT * FROM courtdirectory WHERE courtdirectory.id = '$myid'") 
				or die("Error: " . mysqli_error($conn));
	// begin loop on query 1			
	while($row = mysqli_fetch_array($retval2, MYSQLI_ASSOC)) 
	{
		$varprosecutor = $row['prosecutor'];
		$varprosecutoraddress =  str_replace(',', '&#13;&#10;', $row['prosecutoraddress1']);
		$varprosecutorphone = $row['prosecutorphone'];
		$varprosecutorfax = $row['prosecutorfax'];
		$varprosecutornotes = $row['prosecutornotes'];
		$varprosecutornotes =  str_replace(['<br/>','</br>','<br />'], '&#13;&#10;', $row['prosecutornotes']);
		//  Data from query 1 
		echo "<tr>
			<td class='county'>{$row['county']}</td>
			<td class='city'>{$row['city']}</td>
			<td class='court'>{$row['court']}</td>
			<td class='judge'>{$row['judge']}</td>
			<td class='address'>{$row['address']}</td>
			<td class='phone'>{$row['phone']}</td>
			<td class='fax'>{$row['fax']}</td>
			<td class='notes'>{$row['notes']}</td>
			</tr>
			</tbody>
			</table>
			<!-- ******************* END query 1 data results table -->
			</br>
			<!-- ******************* START A 2ND TABLE -->
			<table class='courtdirectorytable'>
			<tbody>
			<tr>
			<th class='prosecutor'>Prosecutor</th>
			<th class='prosecutoraddress'>Prosecutor Address</th>
			<th class='prosecutorphone'>Prosecutor Phone</th>
			<th class='prosecutorfax'>Prosecutor Fax</th>
			<th class='prosecutornotes'>Prosecutor Notes</th>
			</tr>
			<!--   OUTPUT MORE DATA FROM THE SAME QUERY 1 ROW -->
			<!--   OUTPUT MORE DATA FROM THE SAME QUERY 1 ROW -->
			<!--   OUTPUT MORE DATA FROM THE SAME QUERY 1 ROW -->
			<tr>
			<td class='prosecutor'>
			<textarea class='prosecutor' value='$varprosecutor'>$varprosecutor</textarea>
			</td>
			<td class='prosecutoraddress'>
			<textarea class='prosecutoraddress' value='$varprosecutoraddress'>$varprosecutoraddress</textarea>
			</td>
			<td class='prosecutorphone'>
			<textarea class='prosecutorphone' value='$varprosecutorphone'>$varprosecutorphone</textarea>
			</td>
			<td class='prosecutorfax'>
			<textarea class='prosecutorfax' value='$varprosecutorfax'>$varprosecutorfax</textarea>
			</td>
			<td class='prosecutornotes'>
			<textarea class='prosecutornotes' value='$varprosecutornotes'>$varprosecutornotes</textarea>
			</td>
			</tr>
			</tbody>
			</table>
			<!--  end table 2 -->
			<!--  start a 3rd table -->
			<table class='submitbutton'>
			<tbody>
			<tr>
			<td class='submitbutton'>
			<button type='submit' class='courtdirectory-submit' name='submit' tabindex='6' data-submit='...Sendng'>Update</button>
			</td>
			</tr>
			</tbody>
			</table>";
			//  end table 3 
	}
	echo "</form>";
	echo "</body>";
}
echo "</html>";
exit();

See my comments embedded in this code.

Also - if your query generates more than one row then you will build those 3 tables multiple times and have them all embedded inside your single form.  That's going to make any POST data pretty unpredictable.

 

Edited by ginerjm
Link to comment
Share on other sites

Also, while you should really read what @ginerjmsaid, I also have to point out that (a) you should really remove the duplicate queries and (b) there's no validation on your queries since you simply assume $retval2 exists rather than checking that it does.

And please consider giving variables slightly more meaningful names - in the long run, it'll be easier for you to understand the code you wrote.

Edited by Pixeel
  • Like 1
Link to comment
Share on other sites

I agree with Pixeel.  Why add 'var' to a name that is already known as a 'variable'?  Also using underscores to break up var names is a nice practice since it makes them much clearer to see when you are browsing thru lots and lots of code in a hurry.  An example would be 'prosecutor_fax' for instance.  Stay away from upper and lower cases though.

 

UPDATE:

Just noticed.  You are showing a lot of data in 3 tables (or a multiple of 3) all wrapped in a form with a submit button, but what is it for?  You have no inputs so there will NEVER be any POST data other than the submit button's name and value.  You asked yourself why the 'id' doesn't show up.  Well - that is why. You are using a submit button which generates a POST (per your form tag) so you need an input tag somewhere to get that id to be sent.

Edited by ginerjm
  • Like 1
Link to comment
Share on other sites

First, I want to thank everyone for their time, suggestions and recommendations.  Here are my responses to your questions, suggestions and recommendations:

requinix:

The “id” is not display after I click the Update button

 

Pixeel:

I honestly didn’t give the GET and POST methods much consideration. I will correct that.  I didn’t realize I left MySQL credentials in the code I posted.  Thank you for catching that! 

 

ginerjm:

I think there were duplicate queries and not using the results is because I was trying different things and didn’t delete or comment out the old code

Thank you for cleaning update the code for me.  It is way easier to read now.

The reason there are 3 separate tables right now is because the rows will eventually be color coded and I didn’t feel like bothering with the CSS right now

The query will eventually only generate one row

 

Pixeel:

I will remove the extra queries and insert the validation.  For right now though I know there should be certain data returned from MySQL DB.  This merely for testing.  Once everything is working I will insert the validation

I will rename the variables as I go along

 

ginerjm:

I never really thought about leaving the ‘var’ off.  I always thought it was easier to find the variables if ‘var’ was in front it

Ultimately, when a user changes data and clicks Update it will update the DB.  I set all the inputs to ‘textarea’ just so everything would be vertically aligned to the top

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  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.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.