-   Programming (
-   -   More php and mysql questions (

nazdrowie 12-13-2004 06:14 PM

More php and mysql questions
There seems to be a problem w/ the code at the bottom of the following tutorial page:

AND, I actually copied and pasted this time, replacing the 3 dots w/ the correct head and title tags at the top of the listing. Also, I corrected the variable accessing methods from say $var to $_GET[var] or $_POST[var] where necessary.

Anyway, the code displays the JokeText column of the jokes.Jokes table, but adding a joke to the db is a problem.

When the "Add a Joke!" link is clicked, we're taken to the url, which is fine and dandy, but when you click the submit value, we're again taken to the same url, never exiting the outer php 'if' statement, and thus never adding the joke to the db, 'cause it's the 'else' that's supposed to take care of that.

One solution is to place the form on the bottom of the initial page, so that it's always there, separate from the php logic, but I was wondering if there's another way, using which would preserve the way the app behaves: giving the add-a-joke form only when clicking on the "Add a Joke!" link, and then taking you 'back' to the page that displays the contents of the db.

nazdrowie 12-13-2004 07:36 PM

Here's the code, corrected to work w/ php4 (CORRECTED as in it gives no SYNTAX errors, but the PROBLEM I outlined in my first post still EXISTS):


  // If the user wants to add a joke
  if (isset($_GET[addjoke])):

<P>Type your joke here:<BR>


    // Connect to the database server
    $dbcnx = @mysql_connect("localhost", "root", "mypasswd");
    if (!$dbcnx) {
      echo( "<P>Unable to connect to the " .
            "database server at this time.</P>" );

    // Select the jokes database
    if (! @mysql_select_db("jokes") ) {
      echo( "<P>Unable to locate the joke " .
            "database at this time.</P>" );

    // If a joke has been submitted,
    // add it to the database.
    if ("SUBMIT" == $_POST[submitjoke]) {
      $sql = "INSERT INTO Jokes SET " .
            "JokeText='$_POST[joketext]', " .
      if (mysql_query($sql)) {
        echo("<P>Your joke has been added.</P>");
      } else {
        echo("<P>Error adding submitted joke: " .
            mysql_error() . "</P>");
    echo("<P> Here are all the jokes " .
        "in our database: </P>");
    // Request the text of all the jokes
    $result = mysql_query(
              "SELECT JokeText FROM Jokes");
    if (!$result) {
      echo("<P>Error performing query: " .
          mysql_error() . "</P>");
    // Display the text of each joke in a paragraph
    while ( $row = mysql_fetch_array($result) ) {
      echo("<P>" . $row["JokeText"] . "</P>");
    // When clicked, this link will load this page
    // with the joke submission form displayed.
    echo("<P><A HREF='$PHP_SELF?addjoke=1'>" .
        "Add a Joke!</A></P>");

All times are GMT -5. The time now is 06:20 PM.