Jump to content

Saving to mysql database not working!


rocky48

Recommended Posts

You do realize that we have no idea where these line numbers are, yes?

Braces are used to group lines of php code together.  They are only needed when you have more than one line.  Example:

if(condition)
	statemtent
else
	other statement

That is how you could write a short if statement

Here is a larger one:

if (condition)
{
	statement;
	statement;	
	statement;
}
else
	statement;

Notice how I write my code.  Makes it easy to see where the braces go, yes?

Link to comment
Share on other sites

I think were almost there!

on lines 22, 23, 24 I get this Notice:

Notice: Undefined variable: POST in /homepages/30/d593365489/htdocs/MFC1066/Mac2.php on line 22

Notice: Trying to access array offset on value of type null in /homepages/30/d593365489/htdocs/MFC1066/Mac2.php on line 22

I created a Null $post ($POST=""), but then I got this for each posted variable:

Warning: Illegal string offset 'fname' in /homepages/30/d593365489/htdocs/MFC1066/Mac2.php on line 23

Notice: Uninitialized string offset: 0 in /homepages/30/d593365489/htdocs/MFC1066/Mac2.php on line 23

Still nothing written to DB!

Searching the web it seems that the POST's should be in an array, but how can you do that when there isn't a common variable?

I looked at a simple example on the web where fruit was the variable and the array was apples, pears  and oranges.

Tried this:

 array
    (
    $fname=$POST['fname'];
    $lname=$POST['lname'];
    $email=$POST['email'];
    )

But this gave the same warning!

Not sure where to go from here!

Link to comment
Share on other sites

On 10/13/2022 at 1:47 PM, rocky48 said:

With so many else statements I am very confused as to where the braces should go!

there shouldn't be else statements in the validation logic, unless they are for different validation steps for the same input, such as for the first name, where you should setup a specific message for each possible validation error telling the visitor what was wrong with the value they submitted. a required value that is empty, or it too long, or contains characters that are not permitted need three different error messages. validating independent/separate inputs is NOT mutually exclusive. you are to validate each input separately, storing any validation error in the $errors array using the field name as the array index.

by using else statements, only the first validation error will get setup and displayed, requiring the user to resubmit the form over and over for each different validation error.

also, by no longer trimming and keeping the form data as a set, in the $post array, none of the field value='...' attributes will get populated with the existing data upon an error.

you are making syntax and logic changes where none is needed.

Edited by mac_gyver
Link to comment
Share on other sites

in a copy of my original posted code, search for every place where $post exists and what related comments there are in the code. see where it is defined and initialized to an empty array? see where it is assigned a value from the array_map() call? see where elements of it are tested in the validation logic? see where elements of it are displayed in the form field value="..." attribute? do the same for the $errors variable. see where it is defined and initialized, elements of it are assigned a value in the validation logic, where it is tested after the end of the validation logic, and where it is tested and displayed in the html document? if you are not understanding and following how these two variables are being used throughout the code, you will not be able to do this activity.

Link to comment
Share on other sites

Sorry Barand I faithfully copied your entry on your previous post.

I removed the E_NOTICE by adding '& ~ E_NOTICE'

which removed any notices, but still no entries in the DB.

The entry validation is not working, as I tried not entering any data to see if the message would be displayed, but they didn't!

So it looks like the INSERT is not working.

Link to comment
Share on other sites

Looking through examples on the web I realised that the array statement syntax was wrong it should be in the format: $fname=>$_POST['fname'].

It still does not populate the DB, but there are no error messages?

Run out of ideas!

Here's the code so far (I have not posted the html part, these are the first 44 lines):

<?php

// initialization
session_start();
error_reporting(E_ALL  & ~ E_NOTICE);
ini_set('display_errors','1');
// why not have the connection code actually make the connection too, so that you don't need another line of code?
require "conn/connect_seniorform.php";
// note: this code uses the much simpler and more modern PDO database extension
// when you make the connection -
// set the character set to match your database tables, so that no character conversion occurs over the connection 
// set the error mode to use exceptions, so that all the database statements will use exceptions (this is the default now in php8, but set it anyways)
// set emulated prepared queries to false, you want to run real prepared queries
// set the default fetch mode to assoc, so that you don't need to specify it in each fetch statement

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

// post method form processing
$status="";
$POST="";
if($_SERVER["REQUEST_METHOD"]=="POST") {

    array($fname=>$_POST['fname'],$lname=>$_POST['lname'],$email=>$_POST['email']);
    
    if(empty($fname)|| empty($lname)|| $email){
        $status="All fields are compulsory.";
    }elseif(strlen($fname)>= 255 || !preg_match("/^[a-zA-Z-'\s+$/", $fname)){
        $status="Please enter a valid name";
    }elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
        $status="Please Enter a valid email";
    }else{   
        $sql="INSERT INTO senior_dat(fname,lname,email) VALUES (:fname, :lname, :email)";
        $stmt=$pdo->prepare($sql);
        $stmt->execute(['fname'=>$fname], ['lname'=>$lname],['email'=>$email]);
        $status="Your entrys have been accepted";
        $fname="";
        $lname="";
        $email="";
        
    }
} 
// hrml document starts here...
?>

 

Link to comment
Share on other sites

They have been there all the time??

They are the php variables for the three form inputs I am trying to put into the database.

In the array the $fname are created from the $_POST[fname]

e.g.  $fname=>$_POST['fname']

Is the syntax wrong?

Link to comment
Share on other sites

mac_gyver

I have gone back to your post of 7th October and tried to follow your example.

Quote

 

<?php

// initialization
session_start();
error_reporting(E_ALL  & ~ E_NOTICE);
ini_set('display_errors','1');
// why not have the connection code actually make the connection too, so that you don't need another line of code?
require "conn/connect_seniorform.php";
// note: this code uses the much simpler and more modern PDO database extension
// when you make the connection -
// set the character set to match your database tables, so that no character conversion occurs over the connection 
// set the error mode to use exceptions, so that all the database statements will use exceptions (this is the default now in php8, but set it anyways)
// set emulated prepared queries to false, you want to run real prepared queries
// set the default fetch mode to assoc, so that you don't need to specify it in each fetch statement

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

// post method form processing

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

  $fname=$_POST['fname'];
  $lname=$_POST['lname'];
  $email=$_POST['email'];
  
  $post=array_map('trim',$_POST);
  if($post['fname']===")
  {
    $errors['fname']= "First Name is required";
  }
 {
  $errors['lname']="Last Name is required";
 }
{
 $errors['email']="Email is required";
 }   
  if(empty($errors))
  {
    $sql="INSERT INTO senior_dat (fname,lname,email) VALUES (?,?,?)";
    $stmt=$pdo->prepare($sql);
    
    try {
        $stmt->execute([$post['fname'], $post['lname'], $post['email']);
    }catch(PDOException $e){
        if($e->errorInfo[1]==1062)
        {
            $errors['email']= "Email is already in use";
        }else{
            throw $e;
        }
    }
    if(empty($errors))
    {
        $SESSION['success_message']="Form saved OK";
        die(header("Refresh:0"));
    }
    ?>
  // html here
  <?php
  if(!empty($_SESSION['success_message']))
  {
    echo"<p>{$_SESSION['success_message']}</p>";
    unset($_SESSION['success_message']);
  }
  ?>
  <h1> SENIOR RENEWAL FORM</h1>
  <?php
  if(!empty($errors))
  {
    echo'<p>';echo implode('<br>',$errors);echo''</p>;
  }
  <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>
    <input type="submit"value="submit"
</form>
?>

 

I get this error in line 30:

$errors['fname']= "First Name is required";

Quote

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in

What am I doing wrong?

Link to comment
Share on other sites

1 hour ago, rocky48 said:

is the syntax wrong?

Just a bit.

=> is used to define key/value pairs in an array, not for assigning values to variables.

Your array isn't assigned to variable so the array definition does nothing.

try changing the array creation to

$data = array('fname'=>$_POST['fname'], 'lname'=>$_POST['lname'], 'email'=>$_POST['email'] );

then change the execute stement to

$stmt->execute($data);

 

Link to comment
Share on other sites

This line

  if($post['fname']===")

is wrong.  Please look at it.

Also - this block makes no sense:

  if($post['fname']===")
  {
    $errors['fname']= "First Name is required";
  }
 {
  $errors['lname']="Last Name is required";
 }
{
 $errors['email']="Email is required";
 }   

You start with a test on fname and produce an error message if needed.  But then you produce an error message for lname and another for email but you aren't doing anything to test those values.

Link to comment
Share on other sites

Jinergm -

Please explain! I do not have the knowledge to know how it is wrong!  I must admit the single double quote looks wrong, I only copied Mac_gyver's earlier post back on the 9th October.

Barand -

Don't understand? it has  closing quote, but doesn't have an opening quote? Tried putting a quote after the bracket, didn't think that was right!  It moved the error to line 30 but I'm sure that's not the problem?

Link to comment
Share on other sites

// initialization
session_start();
error_reporting(E_ALL);
ini_set('display_errors','1');
require "conn/connect_seniorform.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 = "";
$POST = "";	// WHAT IS THIS VARIABLE FOR?
if($_SERVER["REQUEST_METHOD"] == "POST") 
{
	$fname = $_POST['fname'],
	$lname = $_POST['lname'],
	$email = $_POST['email']
	// AS I MENTIONED IN AN EARLIER REPLY YOU HAVE A PROBLEM WITH NEXT LINE.
	if(empty($fname) || empty($lname) || $email)
		$errors[] = "All fields are compulsory.";
		// WHAT ABOUT LAST NAME CHECK???
	if(strlen($fname)>= 255 || !preg_match("/^[a-zA-Z-'\s+$/", $fname))
		$errors[] = "Please enter a valid name";
	if(!filter_var($email, FILTER_VALIDATE_EMAIL))
		$errors[] = "Please Enter a valid email";
	if (count($errors) > 0)
		//	handle the errors by resending the form back to the user and exit
	
	//***************************
	//  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]))
	{
		echo "Insert query did not run";
		exit();
	}
	else
		echo "Your entries have been accepted";
} 

This is the latest block of your code with my personal improvements.  See if you understand it.  See my comments as well.

Edited by ginerjm
Link to comment
Share on other sites

Hi ginerjm

Tried your code but it fails on this line:

    $fname = $_POST['fname'],

Error:

Parse error: syntax error, unexpected ',' in /homepages/30/d593365489/htdocs/MFC1066/senior_data2.php on line 17

I wondered if the comma's should have been semi colons, but changing that caused other errors.

Did the code run for you on your computer?

Link to comment
Share on other sites

And you really can't debug it?   

My bad - I altered your code and didn't replace the commas there with semis.  But the fact that you can't debug this tells me that you are not very knowledgeable in PHP....   These are simple assignment statements and every php statement ends with a semi.  The error message points right at the offending comma.

Link to comment
Share on other sites

I know that you use semi colons at the of some statements. I was not sure if it was part of an if statement that these lines were meant to have comas.

I had tried adding semi colons but it produced more errors.

However, I persisted and made several changes and I have sort of got it working, but something is wrong as it puts a 'input>' in the first name box.

As far as I can see the syntax is correct!

This  is the form section:

?>
 <h1> SENIOR RENEWAL FORM</h1>

 <?php if(!empty($errors))
  {
echo implode('<br>',$errors);echo'';
  }
  ?>
  <form method="post"
  <label <b>First Name: </b><br></label><input type="text" name="fname" size="20" maxlength="40"
  value=<?php "htmlentities"($post['fname']?? ENT_QUOTES)?>

    <input type="submit" value="Submit">
</form>
</html>

The ?> is after the last line that you sent me.

I tried entering my name in the input box and got a string of errors:

Quote

Notice: Undefined index: lname in /homepages/30/d593365489/htdocs/MFC1066/senior_data2.php on line 21

Notice: Undefined index: email in /homepages/30/d593365489/htdocs/MFC1066/senior_data2.php on line 22

Warning: preg_match(): Compilation failed: missing terminating ] for character class at offset 14 in /homepages/30/d593365489/htdocs/MFC1066/senior_data2.php on line 27

Notice: Undefined variable: pdo in /homepages/30/d593365489/htdocs/MFC1066/senior_data2.php on line 37

Fatal error: Uncaught Error: Call to a member function prepare() on null in /homepages/30/d593365489/htdocs/MFC1066/senior_data2.php:37 Stack trace: #0 {main} thrown in /homepages/30/d593365489/htdocs/MFC1066/senior_data2.php on line 37

I got rid of the notices, but were left with the preg_match and the Fatal Error.

Can you offer any more help?

Link to comment
Share on other sites

I think I'm gonna quit on you.  You just don't understand that you can't post stuff without SHOWING us what it relates to .  I've asked already to show us the code with the error lines indicated but you won't do it.  And you are trying to do this project that you apparently are not ready to accomplish.  (if you don't know where a semi goes you have a lot to learn.)

Good luck on your journey.

Link to comment
Share on other sites

I have now corrected the problems in the form, but have a problem in the prepare statement: Fatal error: Uncaught Error: Call to a member function prepare() on null in ...

Here is the line: $stmt = $pdo->prepare($sql);

My research on the web says that the pdo is not initialised, but the example initialises it when it logs in to the database.  I have connected to the database using require using the following code:

<?php
  $host_name = 'xxxxxxxx';
  $database = 'xxxxxx';
  $user_name = 'xxxxxxxxxx';
  $password = 'xxxxxxxxx';

  $link = new mysqli($host_name, $user_name, $password, $database);

  if ($link->connect_error) {
    die('<p>Failed to connect to MySQL: '. $link->connect_error .'</p>');
  } else {
    echo '<p>Connection to MySQL server successfully established.</p>';
  }
?>

But I have used mysqli, so is the the reason that it fails with this error?

I have not used PDO before this project, so am not sure if I need to change the connection code.  Will it work if I change the connection code that I require at the beginning of the script or is it better to put the PDO connection code at the top of main code?

Here is the complete code for my form entry to the database:

<!DOCTYPE html>

<html>
<?php

// initialization
session_start();
error_reporting (E_ALL ^ E_NOTICE); 
ini_set('display_errors','1');
require "conn/connect_seniorform.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'];
	$lname = $_POST['lname'];
	$email = $_POST['email'];
	
	if(empty($fname) || empty($lname) || $email)
		$errors[] = "All fields are compulsory.";
		// WHAT ABOUT LAST NAME CHECK???
	if(strlen($fname)>= 255 || !preg_match("/^a-zA-Z-'\s+$/", $fname))
		$errors[] = "Please enter a valid name";
	if(!filter_var($email, FILTER_VALIDATE_EMAIL))
		$errors[] = "Please Enter a valid email";
	if (count($errors) > 0)
		//	handle the errors by resending the form back to the user and exit
	
	//***************************
	//  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]))
	{
		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['first_name']??'',ENT_QUOTES)?>"></label>
<br>
<input type="submit" value="submit">
</form>
</html>

 

Link to comment
Share on other sites

On 10/7/2022 at 11:15 AM, mac_gyver said:
// note: this code uses the much simpler and more modern PDO database extension
// when you make the connection -
// set the character set to match your database tables, so that no character conversion occurs over the connection 
// set the error mode to use exceptions, so that all the database statements will use exceptions (this is the default now in php8, but set it anyways)
// set emulated prepared queries to false, you want to run real prepared queries
// set the default fetch mode to assoc, so that you don't need to specify it in each fetch statement

you are deleting the comments without even reading and understanding what they say.

Link to comment
Share on other sites

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

As I keep saying I have not used PDO before and previous databases I have written were non pdo.

I have had a go at changing the connection code, but get this error: Parse error: syntax error, unexpected ':', expecting ')' in /homepages/30/d593365489/htdocs/MFC1066/conn/connect_seniorform.php on line 7

Line 7: $pdo = new PDO(mysql:host='dbxxxxxxx.hosting-data.io;dbname=dbsxxxxxxx', $user, $pass);

I have used this example from the PHP documentation: $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);

I can't see that there is anything wrong with my modification? It suggests that the colon should be a closing bracket??

Could it be caused elsewhere in the code. I have attached the full code:

<?php
  $host_name = 'dbxxxxxxx.hosting-data.io';
  $dbname = 'dbsxxxxxx';
  $user = 'dbuxxxxx';
  $pass = 'xxxxxxxxx';

  $pdo = new PDO(mysql:host='db5010240626.hosting-data.io;dbname=dbs8678517', $user, $pass);

  if ($pdo->connect_error) {
    die('<p>Failed to connect to MySQL: '. $pdo->connect_error .'</p>');
  } else {
    echo '<p>Connection to MySQL server successfully established.</p>';
  }
?>

 

Link to comment
Share on other sites

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.