I can't figure out what is wrong with my edit page

I created a page in which users can be able to edit their info in the database and I can’t figure out the reason why.
These are the codes below…

I created a page in which users can be able to edit their info in the database and I can’t figure out the reason why.
These are the codes below…

    <?php 
session_start();
require_once ('connection_db.php');
$query = "SELECT * FROM joked ";
$result = mysqli_query ($db, $query);
if(!$result) {
die("Sever not available at the moment.");
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ileya</title>
</head>
<body>
<p>Welcome, <?php #echo $_SESSION['name']; ?>
<a href="insert.php">+Add new joke</a></p>
<ul>
<?php
while($joke = mysqli_fetch_assoc($result)) {?>
	<li><?php echo $joke["caption"] . '<br>';?></li>
    <?php echo $joke["content"] . '<br>';?>
    <a href="edit_joke.php?joke=<?php echo urlencode($joke['id']); ?>">Edit joke</a>
    <?php }?>
<?php mysqli_close($db);?>
<p><a href="new_admin.php">+Add new Admin</a></p>
<p><a href="logout.php">Logout</a></p>
</body>
</html>

And this page works fine but the problem is with the edit page has it display all the contents but do not save the edited version, plus it dosen’t display the messages I asked him to do

EDIT
This post has been reformatted by enclosing the code block in 3 backticks
```
on their own lines.

    <?php
require_once ('connection_db.php')'
if(isset($_GET['joke'])){
  $id = $_GET['joke'];
  $query  = "SELECT * ";
  $query .= "FROM joked ";
  $query .= "WHERE id = '{$id}' ";
  $query .= "LIMIT 1";
  $result = mysqli_query($db, $query);
  if(!$result){
	  die("cant go");	
  }
  
  if(isset($_GET['submit'])){
  $id = $_GET["id"];
  $caption = $_GET["caption"];
  $content = $_GET["content"];
  $authour_id = $_GET["authour_id"];
	
  $good =  true;
  
  if($caption ==='') {
  echo "Title can't be left blank";	
  $good = false;
  }
  if($content ==='') {
  echo "Please fill in content";
  $good = false;
  }
  if($good){
	$query  = "UPDATE joked SET ";
	$query .= "caption = '{$caption}', ";
	$query .= "content = '{$content}', ";
	$query .= "authour_id = {$authour_id} ";
	$query .= "WHERE id ={$_GET['id']} ";
	$query .= "LIMIT 1";
	$man = mysqli_query($db, $query);

	if ($man && mysqli_affected_rows($db) >= 0) {
		// Success
		$_SESSION["message"] = "joke updated.";
		header("admin_display_jokes.php");
	} else {
		// Failure
		$message = "Joke update failed.";
	}

}
} else {
	// This is probably a GET request
	
} // end: if (isset($_POST['submit']))


?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtmggl">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>input joke</title>
</head>

<body>
<?php echo $message; ?>
<p>Editing joke.</p>
<form action="edit_joke.php?joke=<?php echo urlencode($joke['id']); ?>" method = "get">
<?php while($joke = mysqli_fetch_assoc($result)){?>
<p>Joke caption:
<p>
<input type="hidden" name="id" value="<?php echo $joke['id']; ?>" /></p>
<input type="text" name="caption" value="<?php echo htmlentities($joke["caption"]); ?>" />
<p>Content:<br />
<textarea name="content" rows="20" cols="80"><?php echo htmlentities($joke["content"]); ?></textarea>
</p>
<p>
<input type="hidden" name="authour_id" value="<?php echo $joke['authour_id']; ?>" /></p>
<br />
<?php }?>
<input type="submit" name="submit" value="Edit joke" />
<?php mysqli_free_result($result);?>
<?php }?>
</form>
<a href="delete.php?joke<?php echo urlencode($joke['id']); ?>"onclick="return confirm('Are you sure?');">Delete joke</a>
</body>
</html>

But I discoverd one thing and that is that it says(in the url bar) that “undefined url(which is the action form but what I know and learn in Lynda .com, Kevin used it and it works and also Kevin Yank Sitepoint book on PHP)”

And am sorry for the way the code looks. Maybe because I copied the question from stackoverflow website as I also posted the question there

Well, you don’t really say what goes wrong, so I copied the code and attempted to run it. There are problems with it in addition to bad formatting. You may not be seeing the error message because your PHP installation has errors turned off or set so only really bad errors show. This probably won’t affect execution but your variables $joke and $message are not initialized by the time they are used. There also seem to be some missing and some missplaced closing brackets, and that will affect execution.

To turn error reporting on or set it to the max, you must edit your PHP.INI file. Look for the line that says “error_reporting” and make it say

error_reporting = E_ALL

I made some corrections and got it to run and even update the database, but some error messages are still displayed at the bottom of the form.

<?php
require_once ('connection_db.php');
$joke = array(
  'id' => 0,
  'caption' => '',
  'content' => '',
  'authour_id' => 0,
);
$message = '';

if(isset($_GET['joke'])){
  $id = $_GET['joke'];
  $query  = "SELECT * ";
  $query .= "FROM joked ";
  $query .= "WHERE id = '{$id}' ";
  $query .= "LIMIT 1";
  $result = mysqli_query($db, $query);
  if(!$result){
	  die("cant go");	
  }
}

if(isset($_GET['submit'])){
  $id = $_GET["id"];
  $caption = $_GET["caption"];
  $content = $_GET["content"];
  $authour_id = $_GET["authour_id"];
  $good =  true;

if($caption ==='') {
  echo "Title can't be left blank";	
  $good = false;
}

if($content ==='') {
  echo "Please fill in content";
  $good = false;
}

if($good){
  $query  = "UPDATE joked SET ";
  $query .= "caption = '{$caption}', ";
  $query .= "content = '{$content}', ";
  $query .= "authour_id = {$authour_id} ";
  $query .= "WHERE id ={$_GET['id']} ";
  $query .= "LIMIT 1";
  $man = mysqli_query($db, $query);
  if ($man && mysqli_affected_rows($db) >= 0) {
  	// Success
  	$_SESSION["message"] = "joke updated.";
  	header("admin_display_jokes.php");
  }
  else {
  	// Failure
  	$message = "Joke update failed.";
  }
}
} else {
	// This is probably a GET request
	
} // end: if (isset($_POST['submit']))


?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtmggl">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>input joke</title>
</head>

<body>
<?php echo $message; ?>
<p>Editing joke.</p>
<form action="edit_joke.php?joke=<?php echo urlencode($joke['id']); ?>" method = "get">
<?php while($joke = mysqli_fetch_assoc($result)){?>
  <p>Joke caption:</p>
  <p><input type="hidden" name="id" value="<?php echo $joke['id']; ?>" /></p>
  <p><input type="text" name="caption" value="<?php echo htmlentities($joke["caption"]); ?>" /></p>
  <p>Content:<br />
  <textarea name="content" rows="20" cols="80"><?php echo htmlentities($joke["content"]); ?></textarea></p>
  <p><input type="hidden" name="authour_id" value="<?php echo $joke['authour_id']; ?>" /></p>
  <p><input type="submit" name="submit" value="Edit joke" /></p>
  <?php mysqli_free_result($result);?>
<?php }?>
</form>
<a href="delete.php?joke<?php echo urlencode($joke['id']); ?>"onclick="return confirm('Are you sure?');">Delete joke</a>
</body>
</html>

Note how I formatted the HTML so every form control is on its own line. I’m not saying this is the only way, but the nicer it looks, the easier it is to understand.

Consider always using single quotes for strings in PHP unless you need to expand variables, and always using double quotes in HTML. That will look neater, which again, is easier to understand. Also, consider always using echo instead of expanding variables. But this is just general advice. It won’t make or break your code.

The best advice I can give you is to get a code editor that has a debugger! That makes an incredible difference trying to figure out what’s wrong with your code. There are two free editors that have built-in debuggers: NetBeans and CodeLobster. NetBeans is fancier than CodeLobster but it’s slower. I use CodeLobster. With a debugger, you can execute your code line by line and watch the variables change value. It’s like watching your program crash in slow motion. You go, “Ohhhh, that’s what’s wrong!”

thanks…I will try it…

its just that I was forced on so many times to change to codes

@programmer Well, first off. You need to take it slow. One way or another, you’re going to have to transition into OOP style. There are tons of things that require OOP such as prepared statements, MVC, .etc.

Now, what I suggest is take each part of your code and work with it. Here are some examples of doing so.

NOTE: This is not your actual codes, this is an example to help you better your codes.

<?php
require_once('connection_db.php');

///////////////////
// Include in DB //
///////////////////

// define("HOST", "localhost");
// define("USERNAME", "username");
// define("PASSWORD", "password");
// define("DATABASE", "database");

// $mysqli = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);
// if($mysqli->connect_error) {
//     echo "Please fix your database connections";
//     exit();
// }

///////////////////
// End Include   //
///////////////////

// All of the above inside the "Include in DB" should be included in your connection_db.php file

// You check to see which method the form was submitted. Don't use GET in this
// Because you don't want people updating your data without any limitation.
// When you allow someone to update and edit something via the $_GET parameter, you allow them to do something like this

// http://localhost/edit_joke.php?joke=Mwahahahahahahahhhah You can't sensor what I can type, I just basically screwed up your database. This isn't even a real number, the joke is set, but the joke is a long sentence that doesn't even exist&submit=Mwhaahahahaha, even more trolling because the "submit" button was set, but this isn't what was suppose to be set.

// When you are updating something in your database, you really don't want to be using $_GET because anyone with the URL can edit it such as the one I just did up there.
if($_SERVER['REQUEST_METHOD'] == "POST") {

    $url_id = isset($_GET['joke']) ? $_GET['joke'] : '0'; // You make it so that the URL joke is a digit and not a string of letters

    if(isset($url_id)) {

        if($url_id < 0) {
            // We just use 0 here because in every single database, auto increment only starts at 1. So 0 already indicates something is wrong.
            echo "The URL is lower than 0 which means that the URL doesn't exist as 0 in the DB or it isn't even a digit";
        } else {

            if($_POST['caption'] == "") {
                echo "Please don't leave the caption field empty";
            } elseif($_POST['content'] == "") {
                echo "Please don't leave the content field empty";
            } elseif($_POST['author_id'] == "") {
                echo "Author ID doesn't exist, it was modified";
            } else {

                // You shouldn't be trusting user inputs. Not everyone is nice you know. Especially if someone doesn't care if your application breaks or not
                // You also don't want to be passing a get variable inside a hidden field. Someone might just use a web dev tool and inspect your page source then change the HTML code
                // And they can change the value of the hidden field. So even though the actual ID of the particular joke we're in right now is something like
                // 1, someone might modify it as id="adfasdfadfjfajlsdjfa". Then oops, your application is broken. This is what you're going to allow your users to do
                // http://xkcd.com/327/

                $update_query = $mysqli->prepare("UPDATE joked SET caption = ?, content = ?, author_id = ? WHERE id = ? LIMIT 1");
                $update_query->bind_param("ssii", $caption, $content, $author_id, $url_id);
                $caption = $_POST['caption'];
                $content = $_POST['content'];
                $author_id = $_POST['authour_id'];

                $_SESSION["message"] = "joke updated.";
                header("admin_display_jokes.php");

            }

        }

    }

} else {

    // The form was not submitted so this must be just the first step

    // You shouldn't be using the * because if someone gets into your database, they can see anything you don't want to show them.
    // Just specify what columns you really need
    $query = $mysqli->prepare("SELECT id, joke FROM joked WHERE id = ? LIMIT 1");
    $query->bind_param("i", $joke_url);
    $joke_url = isset($_GET['joke']) ? $_GET['joke'] : '0';
    $query->execute();
    $query->store_result();

    // The row with that ID exists
    if($query->num_rows) {

        $query->bind_result($id, $joke);

        while($query->fetch()) {

            // Separating your HTML codes from your PHP codes, this makes it more easy to work with.
            // Plus since all of the HTML codes are in one file.
            require('html_file.php');

        }

    } else {

        // The row with that ID doesn't exist
        // Display your own error handler

    }

}

This isn’t your actual full code yet, but you get the point. Some may say that there is no security issues in this topic, but why not use prepare statements when there’s a WHERE clause? Prepared statements are a great way of separating what are actual SQL lines and what are just regular user inputs.

Also, I highly suggest that you don’t use the $_GET parameter if you are trying to update something. The only thing that you should actually be using the $_GET parameter for is when you are trying to retrieve the ID from the database or anything that has to do with retrieving. As you can see with the comments, someone can simply do that and then modify your database without you even knowing. Even worst, they can do something like

edit_post.php?id=2’); DROP TABLE joke;

Just like it showed on Bobby Tables. When you use $_GET, you allow users to modify anything in the URL and if you allow the $_GET parameter to update your data, then you’re allowing them to do anything they want using the $_GET parameter.

Well, if you get a lot of feedback saying you should change your codes, then it’s best to do so. If it’s not just on one site, I would take that as an advice.

are you on fb? my fb username is wonderboy4rmnigeria@yahoo.com…Pls I will like to always contact you often when I have problems in my code

I know that is frustrating, but try to focus on understanding why the changes are necessary. Focus on learning, and don’t forget that not all advice is good. Sometimes what people tell you has good intentions but is incorrect.

Good luck, and enjoy the journey! :smile:

I have downloaded the lobster. hope its easy to use as I use DreamWeaver(DW)

Thanks, that is why am also here for advice but the problem is that sitepoint dose not work on mobile

It’s easy to use but it has a different purpose than DreamWeaver. DW is mostly for HTML, while CodeLobster is a PHP editor. If you have DreamWeaver CS5, that version is supposed to be good for coding PHP, but it still doesn’t have a debugger. Coding without a debugger is almost like driving with a blindfold. However, DW does make building websites easier, so perhaps you can use both.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.