Jump to content

Recommended Posts

	if ($dbname == null)
		$host="mysql:host=localhost;charset=utf8";
	else
		$host="mysql:host=localhost;dbname=$dbname;charset=utf8";
	$options = array(PDO::ATTR_EMULATE_PREPARES => false,
			PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
			PDO::MYSQL_ATTR_FOUND_ROWS => true,
			PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
	$pdo = new PDO($host, $uid, $pswd, $options);

Where $dbname is passed into the function that I wrap all of this in.  I'll leave you to figure out the rest.

37 minutes ago, rocky48 said:

Barand - So should I change the connection code to PDO instead of mysqli?

That's what I would advise. Forget mysqli exists - PDO is a much simpler interface to use.

  • Like 1

I have the connection code working now but have an error in the PDO code for saving to the database.

its on this line: if (!$stmt->execute(['fname']=>$fname))

The error: Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ')' in ....

As far as I can see the format is correct.

Why am I getting this error?

 

You posted these lines of code once - use them as an example

	//  process the data now
	$sql = "INSERT INTO senior_dat(fname,lname,email) VALUES (:fname, :lname, :email)";
	$stmt = $pdo->prepare($sql);
	if (!$stmt->execute(['fname'=>$fname, 'lname'=>$lname,'email'=>$email]))

Note how the Array is defined inside a set of brackets and then the arguments to the Execute are defined inside of parentheses.  Your last post looks nothing like this.

Sorry but I can't see what you are saying??

All I did was remove the other variables as I had not got those in my form yet.  I was taking Mac_gyvers advice and just getting one field working first!

That was a very flippant remark Barand!

Look at it like this:

	//  process the data now
	$sql = "INSERT INTO senior_dat(fname,lname,email) VALUES (:fname, :lname, :email)";
	$stmt = $pdo->prepare($sql);
	$parms = array(
			'fname'=>$fname, 
			'lname'=>$lname,
			'email'=>$email
			);
	if (!$stmt->execute($parms)
	{

 

Ginerjm

Tried your array example, but now get an error on the echo:

$sql = "INSERT INTO senior_dat(fname,lname,email) VALUES (:fname, :lname, :email)";
	$stmt = $pdo->prepare($sql);
	$parms = array(
			'fname'=>$fname, 
			'lname'=>$lname,
			'email'=>$email
			);
	if (!$stmt->execute($parms)
	{
		echo "Insert query did not run";
		exit();
	}
	else
		echo "Your entries have been accepted";
            

What are we testing with the if statement? Is the fact that the execute either runs or not sufficient to provide a Boolean result?  

I"d like to see your error message since the problem is NOT with the echo.

The if statement is something you should do whenever you do something that relies on a proper response.  Such as a query. Or the opening of a db connection. Or the opening of an external file to be read.  Things you want to be sure that they actually happen.

And I know what your error is, but just want to see how you mis-interpreted the message.  

Edited by ginerjm

Hi ginerjm

Since the last post I have managed to get rid of the errors, but although there are no errors, nothing is input into the database.

Some of the field names did not match my database so have changed them. Was getting an undefined index notice but am ignoring that with

^ E_NOTICE.

Why does it not report that the INSERT has not worked as in the If Else statement?

Here is the code:

<!DOCTYPE html>

<html>
<?php

// initialization
session_start();
error_reporting (E_ALL ^ E_NOTICE); 
ini_set('display_errors','1');
require "conn/connect_seniorform2.php";

$post = []; // array to hold a trimmed working copy of the form data
$errors = []; // array to hold user/validation errors

// post method form processing
$status = "";
if($_SERVER["REQUEST_METHOD"] == "POST") 
{
	$fname = $_POST['fname'];
        $sname = $_POST['sname'];
        $email = $_POST['email'];
	
	if(strlen($fname)>= 255 || !preg_match("/^a-zA-Z-'\s+$/", $fname))
		$errors[] = "Please enter a valid name";
		if (count($errors) > 0)
                exit();
		//	handle the errors by resending the form back to the user and exit
	
	//***************************
	//  process the data now
	$sql = "INSERT INTO senior_dat(fname,sname,email) VALUES (:fname, :sname, :email)";
	$stmt = $pdo->prepare($sql);
	$parms = array(
			'fname'=>$fname, 
			'sname'=>$sname,
			'email'=>$email
			);
	if (!$stmt->execute($parms))
	{
		echo "Insert query did not run";
		exit();
	}
	else
		echo "Your entries have been accepted";
            
}
?>
 <h1>SENIOR RENEWAL FORM</h1>
<?php
// display any errors
if(!empty($errors))
{
	echo '<p>'; echo implode('<br>',$errors); echo '</p>';
}
?>
<form method="post">
<label><b>First Name:</b><br><input type="text" name="first_name" size="20" maxlength="40" value="<?=htmlentities($_POST['fname']??'',ENT_QUOTES)?>"></label>
<br>
<label><b>Surname:</b><br><input type="text" name="last_name" size="20" maxlength="40" value="<?=htmlentities($_POST['sname']??'',ENT_QUOTES)?>"></label>
<br>
<label><b>Email:</b><br><input type="text" name="email" size="20" maxlength="40" value="<?=htmlentities($_POST['email']??'',ENT_QUOTES)?>"></label>
<br><br>
<input type="submit" value="submit">
</form>
</html>

Any ideas why this is not posting this into the database?

May have something to do with $_POST['fname'] and $_POST['sname'] not existing anywhere.

But it can't tell you that because you stupidly turned off the notifications. (NOTE - doing that does not magically make the errors go away)

These are the notices:

Notice: Undefined index: fname in /homepages/30/d593365489/htdocs/MFC1066/senior_data3.php on line 19

Notice: Undefined index: sname in /homepages/30/d593365489/htdocs/MFC1066/senior_data3.php on line 20

How do you index these variables?  Do you use isset? not sure of the syntax ?

OR should I use Fetch?

Can you show e some examples?

I'm still chasing errors!

This is back to my old favourite:

Notice: Undefined index: fname in /homepages/30/d593365489/htdocs/MFC1066/senior_data3.php on line 19

Notice: Undefined index: sname in /homepages/30/d593365489/htdocs/MFC1066/senior_data3.php on line 20

Incidentally, why does the email line not have the same error?

As I said previously do I need 'isset', if so can you show me the correct syntax when a Post variable is involved?

The connection that Barand is asking about is you seem to have trouble understanding why the errors that you are getting on your POST vars seem haphazard to you.  When you get an error saying undefined index that means you are using an index that doesn't exist.  (An index in this case is the piece in the square brackets of an array variable name.) In this case that array is the $_POST array that is generated from your form's POST method.  Furthermore it indicates that you do not have any element declared in your form with that name= attribute.  Previously told us that you see that you changed the form name entry to first_name from fname but you are still having trouble why you are getting errors when you try and reference fname.

For a quick analysis of everything declared in your $_POST simply do an echo like this at the top of your script:

echo "POST array is<pre>",print_r($_POST,true),"</pre>";
exit();

This will show you a list of all the indices defined by your form if you type it into your script correctly.  From there you can go modify your code to use the correct names.

BTW - as Barand told you do NOT use ^NOTICE when you make your error settings.  IMHO you should always use "error_reporting(E_ALL);"

What you don't seem to be aware of is the relation between the names of your form inputs and the index names in the subsequent $_POST array

+-------------------+-----------------------+
| Form field name   |  $_POST element       |
+-------------------+-----------------------+
|   first_name      |  $_POST['first_name'] |
|   last_name       |  $_POST['last_name']  |
|   email           |  $_POST['email']      |
+-------------------+-----------------------+

which should explain why $_POST['fname'] and $_POST['sname'] are undefined but $_POST['email'] works.

Nothing cryptic about it at all, it just requires brain engagement.

Right! The POST array is empty!  So why is the data I type into the form not being POST'ed.

When I previously used php to post data to the database I used to have the form on a different file I am not familiar with the method that has been suggested with this code.

So, why does the code I have not POST properly.  Most of it I have copied from suggestions in previous posts?

I have just started an online PDO course with Udemy, so perhaps I may begin to understand PDO mush better!

23 minutes ago, rocky48 said:

So why is the data I type into the form not being POST'ed.

Probably because the code isn't correct or because you are looking at the POST data before you have submitted the form, but we aren't looking over your shoulder at your screen so can only guess based on previous experience.

The problems you are currently experiencing are basic HTML 101 and nothing to do with PDO

Hi Ginerjm

Here is the form part of the senior_data3.php:

<form method="post">
<label><b>First Name:</b><br><input type="text" name="fname" size="20" maxlength="40" value="<?=htmlentities($_POST['fname']??'',ENT_QUOTES)?>"></label>
<br>
<label><b>Surname:</b><br><input type="text" name="sname" size="20" maxlength="40" value="<?=htmlentities($_POST['sname']??'',ENT_QUOTES)?>"></label>
<br>
<label><b>Email:</b><br><input type="text" name="email" size="20" maxlength="40" value="<?=htmlentities($_POST['email']??'',ENT_QUOTES)?>"></label>
<br><br>
<input type="submit" value="submit">
</form>

Hope this helps to solve y problem!

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.