matt136 matt136 - 1 day ago 5
HTML Question

PHP - Merging Form to Show Results on One Page Causing Issues

I previously had a HTML file containing a form separately from a PHP file containing the script which actions the form results - this worked perfectly without errors.

The problem with this is that the page would redirect to the PHP script whereas I prefer that the form results are shown on the same page so that the user can "search" again. When adding the PHP script on to the end of my HTML page and thus converting the HTML page to a PHP page, the following issues arise:

1) Error "Notice: Undefined index: product_sku in /home/craftingly/public_html/matt/matts_api.php on line 16" is shown.

2) I added an

if
statement which will echo the text "Product SKU xxx does not exist in the database." if the variable that contains the results isn't set. This now shows permanently.

Screenshot of the results:

enter image description here

I assume these errors both occur because the form hasn't been submitted yet and therefore the posted form data and script results are not yet set. The results when submitting the form are still correct for both successful and unsuccessful queries, so the question is what do I need to do to do to have these two errors hidden before the form is submitted?

Please see my code below:

<html>
<head>
<title>Matt's API</title>
<link rel="stylesheet" type="text/css" href="/matt/api.css">
</head>
<body>
Enter a product SKU to get the price
<form class="get_price" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<input type="text" name="product_sku">
<input type="submit" class="form_submit">
</form>
</body>
</html>
<?php
/* Call form Submission SKU Field */
$product_sku = $_POST['product_sku'];

/* Variables */
$callbackURL = "Edited";
$temporaryCredentialsRequestURL = "https://ts564737-container.zoeysite.com/oauth/initiate?oauth_callback=" . URLencode($callbackURL);
$adminAuthorizationURL = 'https://ts564737-container.zoeysite.com/admin/oauth_authorize';
$accessTokenRequestURL = 'https://ts564737-container.zoeysite.com/oauth/token';
$URL = 'https://ts564737-container.zoeysite.com';
$apiURL = $URL . '/api/rest';
$consumerKey = 'Edited';
$consumerSecret = 'Edited';

/* Create/Resume Session */
session_start();

if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) && $_SESSION['state'] == 1) {
$_SESSION['state'] = 0;
}

try {
/* Variables */
$authType = ($_SESSION['state'] == 2) ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI;
$oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType);
$oauthClient->enableDebug();

if (!isset($_GET['oauth_token']) && !$_SESSION['state']) {
$requestToken = $oauthClient->getRequestToken($temporaryCredentialsRequestURL);
$_SESSION['secret'] = $requestToken['oauth_token_secret'];
$_SESSION['state'] = 1;
header('Location: ' . $adminAuthorizationURL . '?oauth_token=' . $requestToken['oauth_token']);
} else if ($_SESSION['state'] == 1) {
$oauthClient->setToken($_GET['oauth_token'], $_SESSION['secret']);
$accessToken = $oauthClient->getAccessToken($accessTokenRequestURL);
$_SESSION['state'] = 2;
$_SESSION['token'] = $accessToken['oauth_token'];
$_SESSION['secret'] = $accessToken['oauth_token_secret'];
header('Location: ' . $callbackURL);
} else {
$oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);
$resourceURL = "$apiURL/products/?order=entity_id&filter[0][attribute]=sku&filter[0][in][0]=" . $product_sku;
//echo $resourceURL;
//exit;
$oauthClient->fetch($resourceURL, array(), 'GET', array('Content-Type' => 'application/json', 'Accept' => 'application/json'));
$productList = json_decode($oauthClient->getLastResponse());
}
} catch (OAuthException $e) {
echo '<pre>';print_r($e);echo '</pre>';
}

/* Get price of the product SKU */
if ($productList) {
foreach ($productList as $product) {
echo '<br><br>Price of <b>' . $product_sku . '</b> is <span style="color: #ff0000; font-weight: bold;">£' . round($product->price, 2) . '</span>';
}
} else {
echo '<br><br>Product SKU <b>' . $product_sku . '</b> does not exist in the database.';
}
?>


Please see the form page here if required: http://craftingly.hosting/matt/matts_api.php

Thank you very much in advance, you guys are great.

Answer

You have a couple options

Rather than move your code to the form (because separating logic and view is a good idea) you could store the results of the query in the session and then redirect back to the form. Make the form a PHP page and then output what is in session for the results.

//Whatever come back from your query even an array
$_SESSION['query_result'] = "...";
//You can redirect by putting
//this at the end of the script
//This url should be what you have in the browser when on the form.
$urlForForm = 'www.sitename.com/products/search';
header('Location: '.$urlForForm);

Then change the html page to a php and have in there

<?php session_start();?>
<!--HTML FORM-->
<?php
//Check that value exists
if(isset($_SESSION['query_result'])){
    //If it does output it
    echo $_SESSION['query_result'];
    //unset it so it does not keep showing up
    unset($_SESSION['query_result']);
?>

If you want to keep them together as mentioned you could check if the value is set for that index

if(isset($_POST['product_sku'])){//Do stuff with SKU}

Or rather then checking specifically for a value to be set you could use $_SERVER['REQUEST_METHOD']=='POST' as a global check on the output logic. The only way you would have a POST request method is if the form was submitted.

if($_SERVER['REQUEST_METHOD']=='POST'){
    //All your form processing and posting code.
    //Will only run when form is submitted
}
Comments