INSERT with PHP to mysql - no errors but no success

I’m having trouble getting data to actually insert into a mysql database. There are no errors, but the data never succeeds in getting to the db.

I have two files at the moment:
One is a config which has the connection code:

[php]$pdoExec = ‘’;

/CONNECT TO THE DB/
try {
$db = new PDO(‘mysql:host=localhost;dbname=familybudget;charset=utf8’,‘testun’,‘testpw’);
}
catch(Exception $e) {
echo “an error has occurred”;
}
[/php]

and the other is inside the php file where the form is located.

[php]if(isset($_POST[‘Insert’]))
{

	//SET THE VARIABLES AS ENTERED ON THE FORM
	$addDate = $_POST['addDate'];
	$addMinutes = $_POST['addMinutes'];
	$addSeconds = $_POST['addSeconds'];
	$addPay = $_POST['addPay'];
	
	//PREPARE THE INSERT OPERATION
	$pdoQuery = "INSERT INTO 'logrev'('Date', 'Minutes', 'Seconds', 'Paid') VALUES (:addDate,:addMinutes,:addSeconds,:addPay)";
	$pdoResult = $db->prepare($pdoQuery);
	
	//EXECUTE THE INSERT OPERATION
	$pdoExec = $pdoResult->execute(array(":addDate"=>$addDate, ":addMinutes"=>$addMinutes, ":addSeconds"=>$addSeconds, ":addPay"=>$addPay));
}

if($pdoExec)
{
echo ‘data good’;
}else{
echo ‘No Data Entered’;

}
[/php]

I’m not sure where to begin or read as I don’t know what’s happening. There are no errors while running it but the data just doesn’t make it into the db and the NO DATA ENTERED is kicked off every time. So the $pdoExec is failing somehow.

Any help would be greatly appreciated. I am a firm believer in the RTFM method but I’m not sure which part to read on this one. Yep, I’m a beginner! :-\

First and foremost,

PDO does not report errors by default. You have to explicitly set that.
[php]$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);[/php]

Doing this,
[php]$addDate = $_POST[‘addDate’];
$addMinutes = $_POST[‘addMinutes’];
$addSeconds = $_POST[‘addSeconds’];
$addPay = $_POST[‘addPay’];
[/php]
Is unnecessary, just use the variables that the value currently sits in. You don’t need extra for the sake of having them.

[php]INSERT INTO ‘logrev’(‘Date’, ‘Minutes’, ‘Seconds’, ‘Paid’)[/php]
Those are single quotes. You probably meant to use a tick mark, table?

[php]if(isset($_POST[‘Insert’]))[/php]
Only works if a specific field is there, meaning it is not scalable to other methods executing the same code.

Lastly,
[php]if($pdoExec)
{
echo ‘data good’;
}else{
echo ‘No Data Entered’;

} [/php]

This is outside of the if block that handles the database interaction. Meaning, it will run every time, regardless if the database was touched or not.

Update 1:
Adding the Pdo thing ($db in my case) helped me pin it down! Now I have an error finally! Well, the error was already spotted by you anyway. Which brings about a good point. I need to have a better standard on my db variable naming conventions!

Update 2:
Tick marks :o
I learn something new and unusual every single day. I would never have guessed they used tic marks in their syntax :-X

Update 3:

<input type="submit" name="Insert" value="Add Record">

I do have this further up on the page within my form and it is unique to that form. I think that’s what you were meaning? Not sure.

Update 4:

$addDate = $_POST['addDate'];

I see what you mean. I was following a bit of a tutorial and that’s what it had. Looking at it over and over again now all I see is xyz=xyz, which certainly seems pointless indeed.

Update 5:
It works thanks to your help! And now I’ve discovered a whole slew of new events I’ll have to account for like how a new entry is added every single time the page refreshes (should be easy enough to fix) and a few others.

I’ve also moved the non-nested If as you mentioned. That certainly makes a lot more sense too.

A side note from a noobie:
Years ago I had a very intelligent teacher who wanted to teach me computer hardware from start to finish. He wanted to teach the pins, the voltage levels, and the whole nine yards. And this guy was the smartest person I’ve ever met.

As a young punk kid, I wasn’t as appreciative of his desire to teach me as I should have been and I’ve always regretted that. I just want to mention that because I really do appreciate your help with this question and I want to make that known in a fashion other than “thanks bye!” which I’ve seen a lot on forums like this before in years past.

Update 3: I do have this further up on the page within my form and it is unique to that form. I think that's what you were meaning? Not sure.

Let me explain it a bit further, as I know Kevin will if I don’t!

So, isset($_POST[‘Insert’]) literally tests for that input. In a more useful system a form may not be what it used, at least not directly.

[php]
if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’) {
// this was sent via post method,
// either by a form or a cURL request
} else if ($_SERVER[‘REQUEST_METHOD’] == ‘GET’) {
// this is for a get request
} else if ($_SERVER[‘REQUEST_METHOD’] == ‘PUT’) {
// these are all HTTP request methods that you can
// use to handle requests differently.
}
[/php]

This is a broad way to process values from a range of senders. When you develop further, code separation will start to happen. So, html and php will be in different places. Add to that the possibility where you add front-end frameworks into the mix (Angular, React) and they can directly call the backend code to process requests as well.

I will be back to check this in a bit - it certainly looks promising. As it is I was reading into how javascript might be a good option to prevent multiple form submissions but we’ll see. It’s reading time! But first… time to take the young minion to his engineering night at the school. Thanks again! I’ll be back!

Your naming convention is all over the place. It is going to cause you problems. Get in the habit of always using lowercase variables and db column names. Separate multiple_words_with_an_underscore

This is a broad way to process values from a range of senders. When you develop further, code separation will start to happen. So, html and php will be in different places. Add to that the possibility where you add front-end frameworks into the mix (Angular, React) and they can directly call the backend code to process requests as well.

Okay, so I can detect any form use whatsoever that used a POST? That’s pretty cool. As it is I have two forms on the page, one fetches results from different categories and the other is this one that NOW will add records. ;D

Yes it is. I’ve been toying with coding since BASIC on the TI-99 but I never really mastered any one language or syntax. As a result my naming conventions get to be very sporadic as I bounce from place to place. I really should just master one but I’m just not sure which one to go for. They are all interesting to me. I’ll certainly try to do as you suggested!

I was reading into how javascript might be a good option to prevent multiple form submissions

The answer for that is PRG, not Javascript.
https://en.wikipedia.org/wiki/Post/Redirect/Get

PRG does look like the way to go - I’ll definitely do some reading on that one.

The page being refreshed or submitted will be one on which I can view and add records. Because of that it could potentially receive quite a few refreshes. Luckily it’s just a small home project at the moment. So I can experiment and see how that would affect the PRG process. Thanks!

I do want to learn the proper way of doing things. Doing it with duct tape and bailing wire works for the truck, but not for this!

Just as a follow up: the below seems to work but it also seems like there could be some security holes with this? It was awesome to get steered in the PRG direction - it probably save me a lot of headaches!!

Header:
[php]<?php
if (isset($_GET[‘check’])){
header(“Location: logRev.php”);
}
?>[/php]

Main Form:

<form name="logRevAdd" action='logRev.php?check=1' method="POST">

You need to exit the script if you call a header redirect otherwise the script will keep running.

[php] <?php
if (isset($_GET[‘check’])){
header(“Location: logRev.php”);
exit();
}
?>[/php]

Like so? Does it not end when it hits the ?> ? That’s so weird.

Yes. I do it all in one like so

[php]die(header(“Location: some_page.php”));[/php]

This is driving me a bit batty as I had a very simple working script but now it’s not working.

It’s the exact same problem and I’m just not able to figure out what’s going wrong.

I have confirmed connection to a database and it displays the database data just fine. The issue is with my PRG setup. After the included db connection this all takes place on the same page.

I have this at the top:

[php] <?php
if (isset($_GET[‘check’])){
header(“Location: logRev.php”);
exit();
}
?>[/php]

Then I have a form farther down the page:

[code]





[/code]

Then below the form on the same page I have this to actually insert the records.

[php]<?php

if(isset($_POST['Insert']))
{
		
	//PREPARE THE INSERT OPERATION
	$pdoQuery = "INSERT INTO `logrev`(`Date`, `Minutes`, `Seconds`, `Paid`) VALUES (:addDate,:addMinutes,:addSeconds,:addPay)";
	$pdoResult = $db->prepare($pdoQuery);
	
	//EXECUTE THE INSERT OPERATION
	$pdoExec = $pdoResult->execute(array(":addDate"=>$_POST['addDate'], ":addMinutes"=>$_POST['addMinutes'], ":addSeconds"=>$_POST['addSeconds'], ":addPay"=>$_POST['addPay']));
	
	if($pdoExec)
	{
		echo 'Data Entered Successfully';
		
	}else{
		echo 'No Data Entered';

		 }
}

?>[/php]

The page refreshes and no form data is ever submitted to the db. Commenting out the header portion gets me back to square one where the records are created in duplicate upon every page refresh.

It seems like there should be a very simple solution but I’m just not seeing it. :-\

Post the entire script as one piece.

I had been avoiding that as I know how ugly some of it is ;D

It’s sort of a sketchpad of brainstorming and learning. My form display code is unnecessarily repetitive too. I certainly plan to clean it all up but I really just want basic functionality first haha Oh boy, here’s my dirty closet.

[code] <?php
if (isset($_GET[‘check’])){
header(“Location: logRev.php”);
exit();
}
?>

fB: Rev Log <?php include "sys/config.php"; ?>
<?php addMenu(); ?>
<div class="dbRev"><!-- ### DATA CONTAINER START ### -->
	<div class="logLeft"><!-- ### LEFT SIDE OF PAGE ### -->
		<TABLE align="right"><TR><th>.</th><th>Date</th><th>Minutes</th><th>Seconds</th><th>Paid</th></tr><!-- ### START A TABLE WITH HEADERS ### -->
			<?php 
				// INITIALIZE VARIABLES WE'LL NEED FOR REPORTS AND WHAT-NOT
				if (isset($_POST["ChooseYear"])) {
				$ChosenYear = $_POST["ChooseYear"];
				}else{  
				$ChosenYear = "All";
				}

				// INITIALIZE VARIABLES USED FOR COUNTING DATA RECIEVED FROM MYSQL DATABASE
				$totalMinutes = 0;
				$totalSeconds = 0;
				$totalTime = 0;
				$totalPay = 0;
				$optionSelected = '';

				/* #######################   CHOSEN YEAR IS 2017   ##################################### */	
				if ($ChosenYear == '2017'){ // USE THIS BRANCH IF USER SELECTED 2017 FROM FORM DROPDOWN
				$logResult= "";				// WIPE OUT LOGRESULT FOR INCOMING STRING OPS
				$optionSelected = "2017";   // SET A VAR TO SHOW USER WHAT OPTION THEY SELECTED

				// GET THE DATA FROM THE logrev TABLE ORDERED BY THE id COLUMN IN DESCENDING ORDER
				$stmt = $db->prepare("SELECT * FROM logrev WHERE YEAR(Date) = :Date ORDER BY id DESC"); //THIS IS THE SQL WE WILL RUN
				$stmt->bindValue(':Date','2017'); // TELLS THE LINE ABOVE WHAT WE MEAN BY :DATE
				$stmt->execute(); // FIRE THE MISSILES (RUN THE SQL STATEMENT WITH BINDINGS INCLUDED
				
					while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){  // LOOP THROUGH THE DATABASE GRABBING VALUES
					$logrevDate = htmlentities($row['Date']);       // ASSIGN VALUES TO VARIABLES BASED ON CURRENT ITERATION OF WHILE LOOP
					$logrevMinutes = htmlentities($row['Minutes']);
					$logrevSeconds = htmlentities($row['Seconds']);
					$logrevPaid = htmlentities($row['Paid']);
					$logrevTimestamp = htmlentities($row['timestamp']);
					
					// PUSH THE DATA OUT AND ADD UP VALUES AS WE GO TO CREATE TOTALS
					$logResult = "<TR><td class='timestamp'>" . $logrevTimestamp . "</td><TD>" . $logrevDate . "</TD><TD>" . $logrevMinutes . "</TD><TD>" . $logrevSeconds . "</TD><TD>" . $logrevPaid . "</TD></TR>";
					$totalMinutes = $totalMinutes + ($row['Minutes']); // ADD MINUTES AS WE GO
					$totalSeconds = $totalSeconds + ($row['Seconds']); // ADD SECONDS AS WE GO
					$totalPay += ($row['Paid']);            // TOTAL UP PAY COLUMN
					echo $logResult;
					}}
				
					
				/* #######################   CHOSEN YEAR IS 2016   ##################################### */	
				elseif ($ChosenYear == '2016') {
				$logResult= "";
				$optionSelected = "2016";
				
				// GET THE DATA FROM THE logrev TABLE ORDERED BY THE id COLUMN IN DESCENDING ORDER
				$stmt = $db->prepare("SELECT * FROM logrev WHERE YEAR(Date) = :Date ORDER BY id DESC"); 
				$stmt->bindValue(':Date','2016'); 
				$stmt->execute(); 
				
					while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
					$logrevDate = htmlentities($row['Date']);
					$logrevMinutes = htmlentities($row['Minutes']);
					$logrevSeconds = htmlentities($row['Seconds']);
					$logrevPaid = htmlentities($row['Paid']);
					$logrevTimestamp = htmlentities($row['timestamp']);
					$logResult = "<TR><td class='timestamp'>" . $logrevTimestamp . "</td><TD>" . $logrevDate . "</TD><TD>" . $logrevMinutes . "</TD><TD>" . $logrevSeconds . "</TD><TD>" . $logrevPaid . "</TD></TR>";
					$totalMinutes = $totalMinutes + ($row['Minutes']);
					$totalSeconds = $totalSeconds + ($row['Seconds']);
					$totalPay = $totalPay + ($row['Paid']);
					echo $logResult;
					}}
				
					
				/* #######################   CHOSEN YEAR IS CURRENT MONTH   ##################################### */	
				elseif ($ChosenYear == 'currentMonth') {
				$logResult= "";
				$optionSelected = "This Month";

				// GET THE DATA FROM THE logrev TABLE ORDERED BY THE id COLUMN IN DESCENDING ORDER
				$stmt = $db->prepare("SELECT * FROM logrev WHERE MONTH(Date) = :Month ORDER BY id DESC"); 
				$stmt->bindValue(':Month',$currentMonth); 
				$stmt->execute(); 
				
					while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
					$logrevDate = htmlentities($row['Date']);
					$logrevMinutes = htmlentities($row['Minutes']);
					$logrevSeconds = htmlentities($row['Seconds']);
					$logrevPaid = htmlentities($row['Paid']);
					$logrevTimestamp = htmlentities($row['timestamp']);
					$logResult = "<TR><td class='timestamp'>" . $logrevTimestamp . "</td><TD>" . $logrevDate . "</TD><TD>" . $logrevMinutes . "</TD><TD>" . $logrevSeconds . "</TD><TD>" . $logrevPaid . "</TD></TR>";
					$totalMinutes = $totalMinutes + ($row['Minutes']);
					$totalSeconds = $totalSeconds + ($row['Seconds']);
					$totalPay = $totalPay + ($row['Paid']);
					echo $logResult;
					}}
				
					
				/*  #######################   DEFAULT OPTION   ##################################### */		
				else {
				$logResult= "";
				$optionSelected = "All Data";
				
				$stmt = $db->query("SELECT * FROM logrev ORDER BY id DESC");
					while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
					$logrevDate = htmlentities($row['Date']);
					$logrevMinutes = htmlentities($row['Minutes']);
					$logrevSeconds = htmlentities($row['Seconds']);
					$logrevPaid = htmlentities($row['Paid']);
					$logrevTimestamp = htmlentities($row['timestamp']);
					$logResult = "<TR><td class='timestamp'>" . $logrevTimestamp . "</td><TD>" . $logrevDate . "</TD><TD>" . $logrevMinutes . "</TD><TD>" . $logrevSeconds . "</TD><TD>" . $logrevPaid . "</TD></TR>";
					$totalMinutes = $totalMinutes + ($row['Minutes']);
					$totalSeconds = $totalSeconds + ($row['Seconds']);
					$totalPay = $totalPay + ($row['Paid']);
					echo $logResult;
					}}

?>

<?php $totalTime = (integer)($totalMinutes + ($totalSeconds / 60)); // CASTING RESULT TO AN INTEGER TO GET RID OF WEIRD EXTRA MATH ?>
<?php echo "

Option Selected: " . $optionSelected . "

" . "

Today is: " . $queryDate . "

TOTALS

Minutes: " . $totalMinutes . "Seconds: " . $totalSeconds . "Total Time: " . $totalTime . "Year Selected: " . $ChosenYear . "Total Paid: $" . $totalPay; ?>
 REV LOG </br>
 <form id='selYear' action='' method='POST'>
 <select name='ChooseYear'>
 <option value=''>CHOOSE A YEAR</option>
 <option value='currentMonth'>Current Month</option>
 <option value='All'>All</option>
 <option value='2017'>2017</option>
 <option value='2016'>2016</option>
 </select>
 <input type='submit' name='Submit' value='Go'>
 </form>
<?php if(isset($_POST['Insert'])) { //PREPARE THE INSERT OPERATION $pdoQuery = "INSERT INTO `logrev`(`Date`, `Minutes`, `Seconds`, `Paid`) VALUES (:addDate,:addMinutes,:addSeconds,:addPay)"; $pdoResult = $db->prepare($pdoQuery); //EXECUTE THE INSERT OPERATION $pdoExec = $pdoResult->execute(array(":addDate"=>$_POST['addDate'], ":addMinutes"=>$_POST['addMinutes'], ":addSeconds"=>$_POST['addSeconds'], ":addPay"=>$_POST['addPay'])); if($pdoExec) { echo 'Data Entered Successfully'; }else{ echo 'No Data Entered'; } } ?>
[/code]

When you set check as soon as you submit your form how is it that you expect to get past the redirect at the top of the page. It is working exactly the way you are telling it to. Your insert logic needs to be at the top if the page.

<?php if server request method equals post{ // do the add data stuff now PRG } ?>

My form is here


eyes.jpg

I was fixated on how it worked before (which I still don’t understand how it did). This way certainly makes sense. I imagine this is like an advanced guitarist hearing a student’s first chords and cringing. Sorry about that teach, I broke a string (eh? eh? see how I brought it back to programming there at the end?) ::slight_smile: [sub]sigh.[/sub]

I should add that I’ve just noticed the PHP tutorial link in the menu. I’m going to spend a lot of time there doing some reading before I ask any more questions.

Sponsor our Newsletter | Privacy Policy | Terms of Service