Jump to content
Larry Ullman's Book Forums

Online Publishing - Selling Virtual Products


Recommended Posts

Hi Larry,

 

Thanks for writing effortless e-commerece. It's a demanding at times but hopefully it will pave the way to a better understanding of web programming.

 

Currently, I'm trying to create an add comment box on the page.php script for the first ecommerce site: selling virtual products.

 

Problem: I cannot pass a page's id from a form submission via server request method == post to insert information into a mysql database? I have tested this script on firefox and windows explorer with similar results.

 

My computer configuration is based on a Windows Vista OS using a localhost Apache server version 2.2.17 with PHP/5.2.10 and MySQLI Client API library version 5.0.51a.

 

Eventhough $_GET can get the page_id, a $_GET variable cannot be passed in a post submission with a hidden field. The is evident when the contents of the post array is displayed with:

'<pre>';

print_r($_POST); as no page_id is listed

Array

(

[message] => hi there

[submit_button] => Add comment

[page_id] =>

[user_id] => 1

)

 

Here is the script that does everything except pass a hidden variable to insert the page_id into the mysql database:

 

include_once('../mysql.inc.php');

//require(MYSQL);

// For storing errors:

$add_page_errors = array();

 

 

// Check for a form submission:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

 

echo '<pre>';

print_r($_POST); // this displays the contents of the array. no page_id listed

 

 

// Check for the message:

if (!empty($_POST['message'])) {

$allowed = '<div><p><span><br><a><img><h1><h2><h3><h4><ul><ol><li> <blockquote>';

$m = mysqli_real_escape_string($dbc, strip_tags($_POST['message'], $allowed));

}

else {$add_page_errors['message'] = 'Please enter a comment!'; }

 

 

if (empty($add_page_errors)) { // If everything's OK.

 

 

// validate variables

if (isset($_SESSION['user_id'], $_POST['id'])

&& filter_var($_SESSION['user_id'], FILTER_VALIDATE_INT, array('min_range' => 1))

&& filter_var($_POST['id'], FILTER_VALIDATE_INT, array('min_range' => 1))) { // Okay!

 

 

// Add the message to the database:

$r = mysqli_query($dbc, "INSERT INTO page_posts (user_id, page_id, message) VALUES ({$_SESSION['user_id']}, {$_GET['id']}, '$m')");

 

if (mysqli_num_rows($r) != 1) { // Problem!

 

$page_title = 'Error!';

include ('./includes/header.html');

echo '<p class="error">This page has been accessed in error.</p>';

include ('./includes/footer.html');

exit();

}

 

} //end of validation for user session and page id

 

} // End of $add_page_errors IF.

 

} // End of the main form submission conditional.

 

// Need the form functions script, which defines create_form_input():

require ('includes/form_functions.inc.php');

 

?>

 

<h3>Add Comment</h3>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" accept-charset="utf-8">

 

<fieldset><legend>Please leave a comment:</legend>

 

<p><label for="message"><strong>Message</strong></label><br /><?php create_form_input('message', 'textarea', $add_page_errors); ?></p>

 

<p><input type="submit" name="submit_button" value="Add comment" id="submit_button" class="formbutton" /></p>

 

<input type="hidden" name="page_id" value="<?php if (isset($_POST['id'])) echo $_POST['id']; ?>" id="page_id" /> //This is the problem code in my opinion

 

<input type="hidden" name="user_id" value="<?php if (isset($_SESSION['user_id'])) echo $_SESSION['user_id']; ?>" id="user_id" />

 

</fieldset>

 

</form>

 

I've managed to get the script to insert one row of data into the mysql database but I don't remember how!

 

Regards,

 

Andrew

Link to comment
Share on other sites

Andrew, you're absolutely right in your suspicions of where the problem is. It's in the following line:

 

<input type="hidden" name="page_id" value="<?php if (isset($_POST['id'])) echo $_POST['id']; ?>" id="page_id" /> //This is the problem code in my opinion

 

The problem is that when you first load the page, nothing is set for $_POST['id'], therefore nothing gets set for value. Essentially, value remains undefined (or perhaps it's NULL). The point is, no ID is ever set, therefore one is never sent via the POST method. Try putting in a static value for value, and test whether that gets sent properly. I can almost guarantee it will.

 

Anyway, to resolve your issue, when the page loads the first time, you need to be fetching an ID from a database, and either via the GET/POST method or Ajax, you need to take that ID retrieved from the database and set it for the hidden value.

 

Unfortunately, I cannot comment much beyond that, as I don't have the book in front of me, and I don't know exactly what you're aiming for. Regardless, that's the gist of it. Hope that helps.

  • Upvote 1
Link to comment
Share on other sites

HartleySan's explanation of why it's not working is spot on.

 

Andrew, from your post it looks like $_GET['id'] is the page id and you want to include it in the POST variables; is that correct? You can achieve that by seeding the hidden form field with that value when the page loads. Like this:

<input type="hidden" name="page_id" value="<?php echo (isset($_POST['page_id']) ? $_POST['page_id'] : $_GET['id']); ?>" id="page_id" />

This code utilizes the ternary operator, which is a shorthand way of writing an if-then conditional. There are 3 segments to this syntax: the first is the condition (isset ($_POST['page_id'])). This is the name of the hidden form field that you are checking. If it is set (meaning, the condition evaluates as true), then the segment between the ? and the : symbols is echoed. If the condition evaluates as false, the segment after the : is echoed. This is the value that was included as part of the URL. So when the page first loads, there is nothing in the POST array because you accessed the page via a link, rather than a form submission, and the id passed as part of the link will be echoed as the value of the hidden field. Once the form is submitted back to itself, the POST array will be populated, including the hidden field with its value from $_GET, and the hidden field will retain the value submitted as $_POST['page_id']. This makes the field 'sticky' in case some required form fields were not filled out by the user.

 

Hope that makes sense.

  • Upvote 1
Link to comment
Share on other sites

Thank HartleySan for your help. And thank you as well Paul. I used that line of code you suggested. You were right. Now the post array now contains the page_id variable

[_POST] => Array

(

[message] => hi

[submit_button] => Add comment

[page_id] => 2

[user_id] => 1

)

The script is still not running however. Perhaps it's a syntax error in the isset validation. I don't know whether to use $_POST['id'] or $_GET['id'] for the isset() validation procedure. If I remove the isset() validaiton procedure from the script completely I get an undefined index error. If the isset validation procedure is present in the coding, it appears to be executing okay. The problem probably lies elsewhere.

 

The major concern is an error message relating to the mysqli insert query that appears saying the page has been accessed in error. This could be an indication that the syntax of the query is wrong though there are no errors being reported. The code that is probably causing the error maybe the way the page_id is expressed in the query i.e., {$_POST['id']}. I have used {$_GET['id']}as well but the mysql table remains empty after attempting to insert these variables into the database. Perhaps the insert command requires special coding as with the form where ternary operators are used.

 

I am thinking about breaking up the mysqli insert command and the isset validation procedure by placing it on another webpage page.php instead of sending the contents of the form submission to the same page. However, using multiple pages would only be an alternative unless everything cannot be done on the same page as this reduces the clutter by having it as an include file.

Link to comment
Share on other sites

"appears saying the page has been accessed in error".

 

The problem at least start in this code:

// Add the message to the database:
$r = mysqli_query($dbc, "INSERT INTO page_posts (user_id, page_id,  message) VALUES ({$_SESSION['user_id']}, {$_GET['id']}, '$m')");

if (mysqli_num_rows($r) != 1) { // Problem!

	$page_title = 'Error!';
	include ('./includes/header.html');
	echo '<p class="error">This page has been accessed in error.</p>';
	include ('./includes/footer.html');
	exit();
}

 

The query is obviously not what you wanted - thus mysqli_num_rows is not 1. (It's likely zero)

 

Do some checks against PhpMyAdmin to check if the query is right when used manually. (Use values instead of get, session and variables.) Often, the errors can be small and hard to catch like "page_posts" should really be "page_post".

 

Hope you figure it out.

  • Upvote 1
Link to comment
Share on other sites

When using an INSERT query, you should use mysql_affected_rows(), not mysql_num_rows(). From the PHP Manual:

 

int mysql_num_rows ( resource $result ) Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().

 

So your query may be just fine, but your method of checking will always indicate it didn't work correctly.

  • Upvote 2
Link to comment
Share on other sites

Hi there,

 

Thanks Paul for noticing the error in my coding - mysqli_affected_rows is the right command to use for inserting information into the mysql database.

 

However, my Mysql data structure definitions were unique for user_id and page_id. This only allowed one row to be inserted in the database. Changing those data structures to index allowed more than one row.

 

While the inclusion of the hidden form field containing a ternary operator enabled the passing of page_id to be sent with the post request, I kept getting an UNDEFINED INDEX error message regarding the $_GET['id']; variable even after the script worked.

 

This error appeared because of my PHP error reporting settings. As the variable was not properly set, I got an UNDEFINED INDEX error. This issue was handled by including the following piece of code:

 

 

Check if $_GET['id'] is set before using it. For example: 
if (!isset($_GET['id'])) 
{
//If not isset -> set with dumy value 
$_GET['id'] = "undefine"; 
}

It's good to get it going anyway. I hope to rewrite the script using coding similar to what is contained in selling physical products on p.256 and p.75 in Larry's book Effortless E-commerce.

 

Thanks again,

 

Andrew

Link to comment
Share on other sites

 Share

×
×
  • Create New...