PHP PDO form doesn't return any errors and it doesn't enter data into database

Hi

I’m trying to validate a form for empty fields and then submit it if it’s ok but it doesn’t do any of this and displayes no errors.

I appreaciate all help ^^


<?php
	include("config.php");
	session_start();
?>
<?php
	// define variables and initialize with empty values
	$rateErr = $comErr = "";
	$rating = $comment = "";

	
	if ($_SERVER["REQUEST_METHOD"] == "POST") {
		if ($_POST["rating"] == "") {
			$rateErr = "Rate the app";
		}
		else {
			$rating= $_POST["rating"];
		}
	
		if (empty($_POST["comment"])) {
			$comErr = "Missing";
		}
		else {
			$comment = $_POST["comment"];
		}
	 if ($rateErr == "" && $comErr == "") {
			try {
				$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
				$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
				$sql = "INSERT INTO reviews (rating, content, appID, user) VALUES(:rating, :comment, :appID, :username)";
				
				$stmt = $con->prepare( $sql );
				$stmt->bindValue( ":rating", $rating);
				$stmt->bindValue( ":comment", $comment);
				$stmt->bindValue( ":appID", $_GET['id']);
				$stmt->bindValue( ":username", $_SESSION['username']);
				$stmt->execute();
				return "Submitted successfully";
			}catch( PDOException $e ) {
				return $e->getMessage();
			}
			}
	}

?>

<html>
	<head>
	</head>
	<body>
<form method="POST"
 action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<select name="rating">
 <option value=""></option>
 <option value="1">1</option>
 <option value="2">2</option>
 <option value="3">3</option>
 <option value="4">4</option>
 <option value="5">5</option>
</select>
<span class="error"><?php echo $rateErr;?></span>
<br />
<textarea rows="4" cols="50" name="comment"  value="<?php echo htmlspecialchars($comment);?>">

Enter text here...</textarea>
<span class="error"><?php echo $comErr;?></span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

ok the error i get is Integrity constraint violation: 1048 Column ‘appID’ cannot be null
the parameter is passed in URL and after submission it disappears so I assume that’s the problem?

Does anyone have any solution?

thx

You will need


$stmt->execute($sql);

I changed it but didn’t help. After submission the page goes blank and doesn’t show any errors :confused:
It inserts the values only if i make appID to be a possible null
It’s as if it doesn’t accept $_GET and i run var_dump on it and shows it as a normal passed id value

Ok it’s really pissing me off I have no idea. As far I established that it looks for POST variables from the form and not GET so I tried and changed my code to this (sorry for pasting it all, but there might be smth wrong that i don’t see, and there are no specific errors)

<?php 
	include("config.php");
	session_start();
 
?>

<?php
    // define variables and initialize with empty values
    $rateErr = $comErr = "";
    $rating = $comment = "";

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

        if ($_POST["rating"] == "") {
            $rateErr = "Rate the app";
        }
        else {
            $rating= $_POST["rating"];
        }

        if (empty($_POST["comment"])) {
            $comErr = "Missing";
        }
        else {
            $comment = $_POST["comment"];
        }

    }

    $appID = $appIDErr = "";

    if ($_SERVER["REQUEST_METHOD"] == "GET") {
        if (empty($_GET["id"])) {
            $appIDErr = "Missing";
        }
        else {
            $appID = $_GET["id"];
        }

    }

    if ($rateErr == "" && $comErr == "" && $appIDErr == "") {
        try {
            $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
            $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
            $sql = "INSERT INTO reviews (rating, content, appID, user) VALUES (:rating, :comment, :id, :username)";

            $stmt = $con->prepare( $sql );
            $stmt->bindValue( ":rating", $rating);
            $stmt->bindValue( ":comment", $comment);
            $stmt->bindValue( ":id", $appID);
            $stmt->bindValue( ":username", $_SESSION['username']);
            $stmt->execute();
            return "Submitted successfully";
        }
        catch( PDOException $e ) {
            echo $e->getMessage();
        }
    }


?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
	<head>
		<title>eduApp</title>
		<link href='http://fonts.googleapis.com/css?family=Josefin+Slab:400,700' rel='stylesheet' type='text/css'>
		<link href='http://fonts.googleapis.com/css?family=Ubuntu' rel='stylesheet' type='text/css'>
		<meta name="description" content="Educational apps for Android devices, smartphones, tablets. Language learning, coding, studying, various subjects." />
		<meta name="keywords" content="Android app, educational, language learning, self study, mobile devices, smartphone, tablet" />
		<link rel="stylesheet" type="text/css" href="style.css" />
	</head>
	<body>
		<header>
			<div id="tagline">
				<h1>eduApp</h1>
				<h2>mobile knowledge feed</h2>
				<?php
				if (!$_SESSION["loggedIn"]) echo " You Are Not Logged In <a href=login.php> Login </a>";
				if ($_SESSION["loggedIn"]) echo " You are logged in as " .$_SESSION['username']. "<a href='logout.php'> Click Here </a> To Logout ";
				?>
			</div>
		</header>
		
		<nav>
			<div id="wrapper">
				<ul class="menu">
					<li><a href="index.php">Home</a></li>
					<li><a href="apps.php">Apps</a></li>
					<li><a href="#">About us</a></li>
					<li><a href="#">Contact us</a></li>
					<li><a href="#">Tutor page</a></li>
				</ul>
		</div>
		</nav>
		
		<div id="contentwrapper">
			<div id="main">
<?php

try {
	$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD ); 
	 $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

} catch (PDOException $e) {
			  echo $e->getMessage(); //catch and show the error
}

	$stmt = $con->prepare( "SELECT * FROM apps WHERE appID = :id" );
	$stmt->bindParam(":id", $_GET['id']);
	$stmt->setFetchMode(PDO::FETCH_ASSOC);
	$stmt->execute();

?>
<?php 	while( $row = $stmt->fetch()) { ?>


				<h2><?php echo $row['app_name']; ?></h2>
				<img class='float' src="<?php echo $row['picture']; ?>" alt="app image" />
				<div id='txt'><p>Category: <?php echo $row['category']; ?></p>
				<p><?php echo $row['description']; ?></p>
				<a href="<?php echo $row['link']; ?>">Download</a></div>
<?php } ?>
<?php
$stmt2 = $con->prepare("SELECT AVG(rating) FROM reviews WHERE appID = :id GROUP BY appID");
	$stmt2->bindParam(":id", $_GET['id']);
	$results = $stmt2->fetch(PDO::FETCH_ASSOC);
	$stmt2->execute();

	
	if (empty($results)) {
	echo 'No reviews added yet';
	}
	else {
	$row = $stmt2->fetch();
	echo "<p>Average rating " . $row['AVG(rating)'] . "</p>";
	}
?>

				<?php
				if ($_SESSION["loggedIn"]) {  ?>
				<!--//include("form.php");
				echo "<a href='form.php?id=".$_GET['id']."'>Add a review</a>";-->
				<form method="POST"
				 action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
				<select name="rating">
				 <option value=""></option>
				 <option value="1">1</option>
				 <option value="2">2</option>
				 <option value="3">3</option>
				 <option value="4">4</option>
				 <option value="5">5</option>
				</select>
				<input type="radio" name="sex" value="male">Submit<br>
				<span class="error"><?php echo $rateErr;?></span>
				<span class="error"><?php echo $appIDErr;?></span>
				<br />
				<textarea rows="4" cols="50" name="comment"  value="<?php echo htmlspecialchars($comment);?>">Enter text here...</textarea>
				<span class="error"><?php echo $comErr;?></span>
				<input type="submit" name="submit" value="Submit">
				</form>

				<?php }
				else {
				echo "You need to login to review this app";
				}
?>

			</div>
			<aside>
			Bo mialam goraczke i bardzo mala odpornosc na pylki
			</aside>
		</div>
		
		<footer>
		</footer>
		
	</body>
</html>

This gives me a blank page and if I remove this bit :


    $appID = $appIDErr = "";

    if ($_SERVER["REQUEST_METHOD"] == "GET") {
        if (empty($_GET["id"])) {
            $appIDErr = "Missing";
        }
        else {
            $appID = $_GET["id"];
        }

    }


It gives me again Integrity constraint violation: 1048 Column ‘appID’ cannot be null

Probably best to pick up GET id and pass as a hidden field for POST.

<?php 
    include("config.php");
    session_start(); 
?>
<?php
    // define variables and initialize with empty values
    $rateErr = "";
    $comErr  = ""; 
	$comment = "";

    if(!isset($_SESSION['username'])){
		$comErr  = "You must be logged in to post comment";
	}else{ 
	    if ($_SERVER["REQUEST_METHOD"] == "POST") {
	        if ($_POST['rating'] == "") {
	            $rateErr = "Rate the app";
	        }
	        else {
	            $rating = $_POST['rating'];
	        }
	     
	        if (empty($_POST['comment'])) {
	            $comErr = "Missing";
	        }
	        else {
	            $comment = $_POST['comment'];
	        }
			
			if (empty($rateErr) && empty($comErr)) {
	            try {
	                $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
	                $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
	                $sql = "INSERT INTO reviews (rating, content, appID, user) VALUES(:rating, :comment, :appID, :username)";
	                
	                $stmt = $con->prepare( $sql );
	                $stmt->bindParam( ":rating", $rating);
	                $stmt->bindParam( ":comment", $comment);
	                $stmt->bindParam( ":appID", $_POST['id']);
	                $stmt->bindParam( ":username", $_SESSION['username']);
	                $stmt->execute();
	                return "Submitted successfully";
	            }catch( PDOException $e ) {
	                return $e->getMessage();
	            }
			}
	    }
	}
$id = (isset($_GET['id']) ? $_GET['id'] : '');
?>

<html>
<head>
</head>
<body>
	<form method="post" action="">
		<input type="hidden" name="id" value=<?php echo $id;?> />
		<select name="rating">
			<option value="">Select</option>
			<option value="1">1</option>
			<option value="2">2</option>
			<option value="3">3</option>
			<option value="4">4</option>
			<option value="5">5</option>
		</select>
		<span class="error"><?php echo $rateErr;?></span>
		<br />
		<textarea rows="4" cols="50" name="comment">
		<?php echo htmlspecialchars($comment);?>
		Enter text here...</textarea>
		<span class="error"><?php echo $comErr;?></span>
		<input type="submit" name="submit" value="Submit" />
	</form>
</body>
</html>

Awesome thx, it inserts the code just fine. Can you explain what $id = (isset($_GET[‘id’]) ? $_GET[‘id’] : ‘’); is exactly. If i understand it just retrieves the id value once it’s set so on a page load and assigns it to $id
I just have a problem with returning the messages like ‘successfully submitted’ cause after the submission there’s just a blank page

Glad it worked for you.

Can you explain what $id = (isset($_GET[‘id’]) ? $_GET[‘id’] : ‘’); is exactly. If i understand it just retrieves the id value once it’s set so on a page load and assigns it to $id
You got it. If is set $_GET[‘id’] ? assign variable $id as $_GET[‘id’] else : assign variable $id as ‘’ or empty value.

For the message, replace the Return line with


	                $message = "Submitted successfully";

And above the form add.


<?php
if(isset($message)){ echo $message;}
?>

The thing is this code after submission goes to URL with template.php instead of template.php?id= I guess that’s why it goes blank after submission

Anyway I tried to apply the same approach to another form (but without passed id). But this one behaves completely weird as after submission it shows no errors nor var_dumps if I use them, just a blank page with a header only. The only issue I can think of is that it doesn’t read the submit button as it’s supposed to or smth with the query? but I don’t get anything printed so it’s weird

<?php
	// define variables and initialize with empty values
	$nameErr = $comErr = $catErr =$priceErr =$linkErr ="";
	$name = $comment = $category = $price = $link = "";

	 
	if ($_SERVER["REQUEST_METHOD"] == "POST") {
		if ($_POST["name"] == "") {
			$nameErr = "Name the app";
		}
		else {
			$name= $_POST["name"];
		}
		if ($_POST["price"] == "") {
			$priceErr = "Price the app";
		}
		else {
			$price= $_POST["price"];
		}
		if ($_POST["link"] == "") {
			$linkErr = "Link the app";
		}
		else {
			$link= $_POST["link"];
		}
	 		if ($_POST["category"] == "") {
			$catErr = "Missing";
		}
		else {
			$category = $_POST["category"];
		}
		if (empty($_POST["description"])) {
			$comErr = "Missing";
		}
		else {
			$comment = $_POST["description"];
		}
	 if (empty($rateErr) && empty($comErr) && empty($catErr)&& empty($linkErr) && empty($priceErr)) {
			try {
				$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
				$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
				$sql = "INSERT INTO apps (app_name, category, price, link, description, date_added) VALUES (:name, :category, :price, :link, :description, :date)";
				
				$stmt = $con->prepare( $sql );
				$stmt->bindValue( ":name", $name);
				$stmt->bindValue( ":category", $category);
				$stmt->bindValue( ":price", $price);
				$stmt->bindValue( ":link", $link);
				$stmt->bindValue( ":description", $comment);
				$stmt->bindValue( ":date", now());
				$stmt->execute();
				return "Submitted successfully";
			}catch( PDOException $e ) {
				echo $e->getMessage();
			}
			}
var_dump($_POST);
	}

?>
		<div id="contentwrapper">
			<div id="main">

<form method="POST"
 action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
App name <input type="text" name="name" value="<?php echo htmlspecialchars($name);?>">
<span class="error"><?php echo $nameErr;?></span>
<br />
Price <input type="text" name="price" value="<?php echo htmlspecialchars($price);?>">
<span class="error"><?php echo $priceErr;?></span>
<br />
Download link <input type="text" name="link" value="<?php echo htmlspecialchars($link);?>">
<span class="error"><?php echo $linkErr;?></span>
<br />
<select name="category">
 <option value=""></option>
 <option value="maths">maths</option>
 <option value="driving">driving</option>
 <option value="languages">languages</option>
 <option value="literature">literature</option>
 <option value="science">science</option>
  <option value="psychology">psychology</option>
   <option value="psychology">biology</option>
<option value="IT">IT</option>
 <option value="other">Other</option>
</select>
<span class="error"><?php echo $catErr;?></span>
<br />
<textarea rows="4" cols="50" name="description"  value="<?php echo htmlspecialchars($comment);?>">
Enter text here...</textarea>
<span class="error"><?php echo $comErr;?></span>
<input type="submit" name="submit" value="Submit">
</form>

Ok i’ve updated my code and it prints the array and the page after submission is no longer blank but i can only see the header and no other content nor error so I assume that everything after if ($rateErr && $comErr && $catErr&& $linkErr && $priceErr == “”) is not executed

<?php
	// define variables and initialize with empty values
	$nameErr = $comErr = $catErr =$priceErr =$linkErr ="";
	$name = $description = $category = $price = $link = "";

	
if ($_SERVER["REQUEST_METHOD"] == "POST") {
print_r($_POST);
		if ($_POST["name"] == "") {
			$nameErr = "Name the app";
		}
		else {
			$name= $_POST["name"];
		}
		if ($_POST["price"] == "") {
			$priceErr = "Price the app";
		}
		else {
			$price= $_POST["price"];
		}
		if ($_POST["link"] == "") {
			$linkErr = "Link the app";
		}
		else {
			$link= $_POST["link"];
		}
	 	if ($_POST["category"] == "") {
			$catErr = "Missing";
		}
		else {
			$category = $_POST["category"];
		}
		if (empty($_POST["description"])) {
			$comErr = "Missing";
		}
		else {
			$description= $_POST["description"];
		}
	 if ($rateErr && $comErr && $catErr&& $linkErr && $priceErr == "") {
			try {
				$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
				$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
				$sql = "INSERT INTO apps (app_name, category, price, link, description, date_added) VALUES (:name, :category, :price, :link, :description, :date)";
				
				$stmt = $con->prepare( $sql );
				$stmt->bindValue( ":name", $name);
				$stmt->bindValue( ":category", $category);
				$stmt->bindValue( ":price", $price);
				$stmt->bindValue( ":link", $link);
				$stmt->bindValue( ":description", $description);
				$stmt->bindValue( ":date", now());
				$stmt->execute();
				echo "Submitted successfully";
			}catch( PDOException $e ) {
				echo $e->getMessage();
			}
			}

	}

?>

Try

if (empty($rateErr) && empty($comErr) && empty($catErr) && empty($linkErr) && empty($priceErr)) {

Note: make sure you have a space before and after && $catErr&&

I’ve changed it and printed the post values just after this statement. Gives me a blank page with the array which shows just fine. So i guess the problem is with mySQL, or the bound values…

Try

bindParam

doesn’t change anything :confused:

Ok figured it out it’s the bindValue(‘:date’, now()); if i remove it it will insert the data but do you know how i can implement to add the current date to a field type DATETIME

I believe now() needs to be directly in the query

$sql = "INSERT INTO apps (app_name, category, price, link, description, date_added) VALUES (:name, :category, :price, :link, :description, now())";