I'm trying to use php to validate my form. I would like to validate a product_name box for being not empty, a price box for being numeric and having a decimal, and a quantity box for being an integer. Right now I'm getting an error:
Parse error: syntax error, unexpected T_VARIABLE in C:\Program Files\IndigoPerl\apache\htdocs\process_games.php on line 60

I don't think I have how the price is validated correct either, how would I include the decimal point? I'm not sure if the way I have the code that the information will still be added to the DB if the error message for the price & quantity comes up. Maybe I should nest them with the product name?

<?php

echo '<html>
<head><link rel="stylesheet" type="text/css" href="styles.css" />
<title>Uploading image and adding game to database...</title>
</head>
<body>
<h3>Uploading file...</h3>';

if ($_FILES['filename']['error'] > 0)
{
	echo 'Problem: ';
    	switch ($_FILES['filename']['error'])
    	{
      		case 1:  echo 'File exceeded upload_max_filesize';  break;
      		case 2:  echo 'File exceeded max_file_size';  break;
      		case 3:  echo 'File only partially uploaded';  break;
      		case 4:  echo 'No file uploaded';  break;
    	}
    	exit;
}

// put the file where we'd like it
$upfile = './images/'.$_FILES['filename']['name'];

if (is_uploaded_file($_FILES['filename']['tmp_name']))
{
     	if (!move_uploaded_file($_FILES['filename']['tmp_name'], $upfile))
     	{
        	echo 'Problem: Could not move file to destination directory';
        	exit;
     	}
}
else
{
    	echo 'Problem: Possible file upload attack. Filename: ';
    	echo $_FILES['filename']['name'];
    	exit;
}

echo '<p>File uploaded successfully<br><br>';

if (isset($_POST['description'])) {
	$description = $_POST['description'];
} else {
        $description = $_FILES['filename']['name'];
}

// show what was uploaded
echo '<p>Preview of uploaded file:<br><hr>';
echo "<a href='$upfile'>$description</a>";
echo '<br><hr>';
echo '</body></html>';

$imagename = $description;

// Set up the database connection.
require_once ('mysqli_connect.php');

if (! preg_match('/^-?\d+$/'$_POST['price'])) {
    print 'Price must be a number.';
}
if (! preg_match('/^-?\d+$/'$_POST['quantity'])) {
    print 'Quantity must be an integer.';
}

	if (!empty($_POST['product_name'])
		{
			// add new sandwich
			$product_name = $_POST['product_name];
			$quantity = $_POST['quantity'];
			$price = $_POST['price'];
			$systemid = $_POST[systemid];
			$genreid = $_POST[genreid];
			$conditionid = $_POST[conditionid];

			$query = "INSERT INTO products (productName, quanity, price, image_name, systemid, genreid, conditionid)
								   VALUES ('$product_name', '$quantity', '$price', $imagename, $systemid, $genreid, $conditionid)";

			$result = mysqli_query ($dbc, $query);
			$productid = mysqli_insert_id($dbc);
		}

		else
		{
			echo '<p>Error - All fields are required!</p>';
		}
		echo 'Productid: ' . $productid . ' ' . ' Game Name: ' . $product_name . ' ' . ' Image Name: ' .
		$imagename . ' Quantity: ' . $quantity . ' Price: ' . $price . '<br>';

?>

Dani AI

Generated

The parse error (unexpected T_VARIABLE) is a straight PHP syntax problem, not the validator logic. correctly flagged syntax mistakes in the snippet. Common causes are an unclosed parenthesis or quote, a missing comma, or an unterminated string earlier in the file — the reported line number is often a little after the real fault. First step: run a linter and turn on full error reporting so the interpreter gives the precise clue.

Enable helpful diagnostics early in the script so parse/runtime problems are visible:

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
// from the shell: php -l path/to/process_games.php  <-- quick syntax check

For validation, prefer PHP filters over brittle regex when possible. Use filter_input/filter_var to sanitize and validate, then cast only after validation. Collect errors and halt insertion until all validations pass:

<?php
$prod = trim(filter_input(INPUT_POST, 'product_name', FILTER_SANITIZE_STRING));
$priceRaw = filter_input(INPUT_POST, 'price', FILTER_DEFAULT);
$qtyRaw = filter_input(INPUT_POST, 'quantity', FILTER_DEFAULT);

$errs = [];

if ($prod === '' || $prod === null) { $errs[] = 'product_name required'; }
if (filter_var($priceRaw, FILTER_VALIDATE_FLOAT) === false) { $errs[] = 'price must be numeric'; }
if (filter_var($qtyRaw, FILTER_VALIDATE_INT) === false) { $errs[] = 'quantity must be an integer'; }

if ($errs) { foreach ($errs as $e) echo $e . "<br>"; exit; }

$price = (float)$priceRaw;
$quantity = (int)$qtyRaw;

When inserting, use prepared statements and bind parameters to prevent SQL injection and to avoid syntax mistakes from interpolated strings. Also verify file upload success and move the file before committing the DB row, or wrap both steps in application logic so a failed file move does not leave a DB row pointing to a missing image:

<?php
$stmt = $dbc->prepare(
  'INSERT INTO products (productName, quantity, price, image_name, systemid, genreid, conditionid) VALUES (?, ?, ?, ?, ?, ?, ?)'
);
$stmt->bind_param('sidsiii', $prod, $quantity, $price, $imagename, $systemid, $genreid, $conditionid);
$stmt->execute();

Also check for simple typos (column names, missing quotes in $_POST keys) when syntax errors appear. The combination of linting, filter-based validation, and prepared statements will remove the common causes seen in the original post by and the fixes suggested by .

Recommended Answers

All 2 Replies

You are missing a comma in line 60:

if (! preg_match('/^-?\d+$/',$_POST))

also php's is_numeric function should work just fine for checking if the number is numeric. For example change line 60 with:

if(!is_numeric($_POST) {
//fail
}

Also you are missing a quote on line 70: $_POST

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.