1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Need someone to look at some php coding for me.

Discussion in 'PHP' started by jimmyleem, Jul 3, 2009.

  1. #1
    Ok so I've been trying to learn PHP and MySQL for the past couple days, I've never really messed with any type of programming so I figured the best way would be to start a small project and so far its been great, I'm learning a lot doing the project but now I need a little help.
    My project is a very simple one but complex for me lol. I wanted to learn about databases and how to interact with them using php. So I decided to build a PSP game database. Just a simple database of my PSP games.
    I have WAMP installed on my computer so I can use PHP and MYSQL all from localhost. So I used the MySQL console to create a database called PSP, and then I created a table with 4 columns. ID, title, genre, score. The game I used as an example was Need for Speed Carbon, Racing genre, score 7. This was easy, and I was able to create a simple page displaying all the games in my database, I also created scripts to let me see all the racing games or fighting games based on genre. All easy stuff. Then I got to the point where I wanted to be able to submit games using a form on the site. I can get it to work with one input field like title, but if I want to submit title, genre, and score all on one page I get stuck. Also I'd like to note that I have NOT NULL set for all the columns, not sure how much of a difference that makes.
    I've been using a book called Build Your Own Database Driven Websites using PHP and MySQL and the example in the book he builds a joke database but only has a submit block for the joke. So if you see the word joke in my database its because i'm using alot of his code lol.
    So here is the page as I have it now

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>PSP Game Database</title>
    <meta http-equiv="content-type"
    content="text/html; charset=iso-8859-1" />
    </head>
    <body>
    <?php if (isset($_GET['addgame'])): // User wants to add a game
    ?>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    <label>Enter the game's title here:<br />
    <textarea name="title" rows="0" cols="40">
    </textarea></label><br />
    <textarea name="score" rows="1" cols="1">
    </textarea></label><br />
    <textarea name="genre" rows="1" cols="20">
    </textarea></label><br />
    <input type="submit" value="SUBMIT" />
    <label>Enter the game's score here:<br />
    
    </form>
    <?php else: // Default page display
    // Connect to the database server
    $dbcnx = @mysql_connect('localhost', 'root', '');
    if (!$dbcnx) {
    exit('<p>Unable to connect to the ' .
    'database server at this time.</p>');
    }
    // Select the psp database
    if (!@mysql_select_db('PSP')) {
    exit('<p>Unable to locate the game ' .
    'database at this time.</p>');
    }
    // If a game has been submitted,
    // add it to the database.
    if (isset($_POST['title'])) {
    $title = $_POST['title'];
    $sql = "INSERT INTO psp SET
    title='$title',
    genre='genre',
    score='score',
    ";
    if (@mysql_query($sql)) {
    echo '<p>Your game has been added.</p>';
    } else {
    echo '<p>Error adding submitted game: ' .
    mysql_error() . '</p>';
    }
    }
    echo '<p>Here are all the games in our database:</p>';
    // Request the text of all the games
    $result = @mysql_query('SELECT title FROM psp');
    if (!$result) {
    exit('<p>Error performing query: ' .
    mysql_error() . '</p>');
    }
    // Display the text of each game in a paragraph
    while ($row = mysql_fetch_array($result)) {
    echo '<p>' . $row['title'] . '</p>';
    }
    // When clicked, this link will load this page
    // with the game submission form displayed.
    echo '<p><a href="' . $_SERVER['PHP_SELF'] .
    '?addgame=1">Add a Game!</a></p>';
    endif;
    ?>
    </body>
    </html>
    
    Code (markup):
     
    jimmyleem, Jul 3, 2009 IP
  2. crath

    crath Well-Known Member

    Messages:
    661
    Likes Received:
    33
    Best Answers:
    0
    Trophy Points:
    100
    #2
    The query to insert an entry should look like

    INSERT INTO `psp` (title, genre, score) VALUES('Need for Speed', 'Racing Game', '381 points');
    Code (markup):
    Let me know if that helps :)
     
    crath, Jul 3, 2009 IP
  3. jimmyleem

    jimmyleem Guest

    Messages:
    11
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    It makes perfect sense, but how can I use the submit form on the page, Like I click that I want to add a new game, then I get 3 text boxes, one for title, genre and score. How can I use that insert query but pull the values from my form?
     
    jimmyleem, Jul 3, 2009 IP
  4. dweebsonduty

    dweebsonduty Active Member

    Messages:
    131
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    71
    Digital Goods:
    1
    #4
    In the form your field names will be title, genre and points.

    In your PHP code you will do this:

    $title = $_GET["title"];
    $genre = $_GET["genre"];
    $points = $_GET["points"];
    
    INSERT INTO `psp` (title, genre, score) VALUES('$title', '$genre', '$points');
    PHP:
     
    dweebsonduty, Jul 3, 2009 IP
  5. crath

    crath Well-Known Member

    Messages:
    661
    Likes Received:
    33
    Best Answers:
    0
    Trophy Points:
    100
    #5
    firstly, remove

    action="<?php echo $_SERVER['PHP_SELF']; ?>"

    on the form tag, dont need that, its an automatic.

    second, you are using POST on your form, which is good.

    php will be sent this, so you need to collect it to build your query. It should end up looking something like this.

    
    if(isset($_POST['title'])){ // This will only run the following code if the "title" input has been sent
         $title = htmlspecialchars($_POST['title']); // This htmlspecialchars() function will convert some sensitive characters such as " ' < and > to their HTML equivalents, so it does not mess up your query
         $genre = htmlspecialchars($_POST['genre']);
         $score = htmlspecialchars($_POST['score']);
    
         $query = "INSERT INTO `psp` (title, genre, score) VALUES('$title', '$genre', '$score');"; // This is our query, including the values that were sent from the form
         $result = mysql_query($query); // This will run the query that is stored in the variable $query, and place the result in the variable $result
         if($result){
              echo 'The game was added successfully!';
         }else{
              echo 'An error occurred while adding the game! Please try again!';
         }
    }
    PHP:
    Lets see where that gets ya

    ps: I commented most of the functions so you understand whats going on
     
    crath, Jul 3, 2009 IP
  6. jimmyleem

    jimmyleem Guest

    Messages:
    11
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    I get this now
    Forbidden

    You don't have permission to access /method="post" on this server.
     
    jimmyleem, Jul 3, 2009 IP
  7. jimmyleem

    jimmyleem Guest

    Messages:
    11
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #7
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>PSP Game Database</title>
    <meta http-equiv="content-type"
    content="text/html; charset=iso-8859-1" />
    </head>
    <body>
    <?php if (isset($_GET['addgame'])): // User wants to add a game
    ?>
    <form method="post">
    <label>Enter the game's title here:<br />
    <textarea name="title" rows="0" cols="40">
    </textarea></label><br />
    <textarea name="score" rows="1" cols="1">
    </textarea></label><br />
    <textarea name="genre" rows="1" cols="20">
    </textarea></label><br />
    <input type="submit" value="SUBMIT" />
    <label>Enter the game's score here:<br />
    
    </form>
    <?php else: // Default page display
    // Connect to the database server
    $dbcnx = @mysql_connect('localhost', 'root', '');
    if (!$dbcnx) {
    exit('<p>Unable to connect to the ' .
    'database server at this time.</p>');
    }
    // Select the psp database
    if (!@mysql_select_db('PSP')) {
    exit('<p>Unable to locate the game ' .
    'database at this time.</p>');
    }
    // If a game has been submitted,
    // add it to the database.
    if(isset($_POST['title'])){ // This will only run the following code if the "title" input has been sent
         $title = htmlspecialchars($_POST['title']); // This htmlspecialchars() function will convert some sensitive characters such as " ' < and > to their HTML equivalents, so it does not mess up your query
         $genre = htmlspecialchars($_POST['genre']);
         $score = htmlspecialchars($_POST['score']);
    
         $query = "INSERT INTO `psp` (title, genre, score) VALUES('$title', '$genre', '$score');"; // This is our query, including the values that were sent from the form
         $result = mysql_query($query); // This will run the query that is stored in the variable $query, and place the result in the variable $result
         if($result){
              echo 'The game was added successfully!';
         }else{
              echo 'An error occurred while adding the game! Please try again!';
         }
    }
    if (@mysql_query($sql)) {
    echo '<p>Your game has been added.</p>';
    } else {
    echo '<p>Error adding submitted game: ' .
    mysql_error() . '</p>';
    }
    echo '<p>Here are all the games in our database:</p>';
    // Request the text of all the games
    $result = @mysql_query('SELECT title FROM psp');
    if (!$result) {
    exit('<p>Error performing query: ' .
    mysql_error() . '</p>');
    }
    // Display the text of each game in a paragraph
    while ($row = mysql_fetch_array($result)) {
    echo '<p>' . $row['title'] . '</p>';
    }
    // When clicked, this link will load this page
    // with the game submission form displayed.
    echo '<p><a href="' . $_SERVER['PHP_SELF'] .
    '?addgame=1">Add a Game!</a></p>';
    endif;
    ?>
    </body>
    </html>
    
    Code (markup):
    Thats what I have now and when I get to the submit form it tells me that "Error adding submitted game: Query was empty" but when I click add game again it brings up the form, so I fill in the title, genre and score and hit submit and nothing happens.
     
    jimmyleem, Jul 3, 2009 IP
  8. crath

    crath Well-Known Member

    Messages:
    661
    Likes Received:
    33
    Best Answers:
    0
    Trophy Points:
    100
    #8
    1) Its good to space your code, it makes it much easier to read. You already have the comments down pat, which is good.

    2) I rewrote it a bit, and hopefully you understand it. I didn't test it because I dont have the database setup, but it should be pretty close. Let me know.

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    	<head>
    		<title>PSP Game Database</title>
    		<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    	</head>
    	<body>
    <?php
    // Connect to the server
    	$dbcnx = @mysql_connect('localhost', 'root', '');
    	if(!$dbcnx){
    		exit('<p>Unable to connect to the '.'database server at this time.</p>');
    	}
    // Select the psp database
    	if(!@mysql_select_db('PSP')){
    		exit('<p>Unable to locate the game '.'database at this time.</p>');
    	}
    
    // If the user has submitted the new game form, add it.
    	if(isset($_POST['title'])){
    		$title = htmlspecialchars($_POST['title']);
    		$genre = htmlspecialchars($_POST['genre']);
    		$score = htmlspecialchars($_POST['score']);
    
    		$query = "INSERT INTO `psp` (title, genre, score) VALUES('$title', '$genre', '$score');"; // This is our query, including the values that were sent from the form
    		$result = mysql_query($query); // This will run the query that is stored in the variable $query, and place the result in the variable $result
    		if($result){
    			echo 'The game was added successfully!';
    		}else{
    			echo 'An error occurred while adding the game! Please try again!';
    		}
    	}
    
    	if(isset($_GET['addgame'])){ // The user wants to add a game
    		echo '<form method="post">
    			<label>Enter the game\'s title here:<br />
    				<input type="text" name="title"/>
    			</label><br />
    			<label>Enter the game\'s score here:<br />
    				<input type="text" name="score"/>
    			</label><br />
    			<label>Enter the game\'s genre here:<br />
    				<input type="text" name="genre"/>
    			</label><br/>
    			<input type="submit" value="Add Game" />
    			</form>';
    	}else{ // The user doesn't want to add a game, show them the list
    		$result = mysql_query("SELECT * FROM `psp` ORDER BY `title` DESC;");
    		while($db = mysql_fetch_assoc($result)){
    			echo 'Name: '.$db['name'].'<br/>Genre: '.$db['genre'].'<br/>Score: '.$db['score'].'<br/><br/>';
    		}
    		echo '<a href="?addgame">Add Game!</a>';
    	}
    ?>
    PHP:
     
    crath, Jul 3, 2009 IP
    jimmyleem likes this.
  9. jimmyleem

    jimmyleem Guest

    Messages:
    11
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #9
    Yes that worked!! Thank you, I'm too tired to look over it now but in the morning I'll compare the code to mine to see where I went wrong. I'll rep you for this.
     
    jimmyleem, Jul 3, 2009 IP
  10. udskiii

    udskiii Peon

    Messages:
    143
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #10
    PM me if you have any other queries and I will see what I can do.........
     
    udskiii, Jul 3, 2009 IP