Jump to content

PHP Help & MYSQL


G3NERALCHRIS
Go to solution Solved by G3NERALCHRIS,

Recommended Posts

I am creating a website for university coursework.

<input name="submit" type="submit" class="submit_btn float_l" id="submit" formaction="add-contactme.php" value="Send" />

The above code is from my html for contact.html if that is correct. I am using a form and then a submit button.

I keep getting

Notice: Undefined index: name in C:\xampp\htdocs\hometown\hometown\add-contactme.php on line 11

Notice: Undefined index: email in C:\xampp\htdocs\hometown\hometown\add-contactme.php on line 12

Notice: Undefined index: phoneno in C:\xampp\htdocs\hometown\hometown\add-contactme.php on line 13

Notice: Undefined index: comments in C:\xampp\htdocs\hometown\hometown\add-contactme.php on line 14

 

Also if anyone could help me I would like to create a delete button after a person has added the values into the sql table, basically to the last row inputted into the database. I want to avoid using delete from contactme where name ='chris';

$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="contactme"; // Table name

mysql_connect ("$host", "$username", "$password") or die ("cannot connect server ");
mysql_select_db ("$db_name") or die ("cannot select DB");

$name = $_POST["name"];
$email = $_POST["email"];
$phoneno = $_POST["phoneno"];
$comments = $_POST["comments"];

$sql="INSERT INTO $tbl_name VALUES ('$name', '$email', '$phoneno''$comments')";
$result=mysql_query($sql);

if($result){
echo "Successful" . "
";
echo "view-contactme.php"; // link to view contact me page
}
mysql_close();
?>
Edited by G3NERALCHRIS
Link to comment
Share on other sites

At the top of your script, add the following.  This will print out all the fields you are sending in the form to the server.  What do you see?  If $_POST["phoneno"], etc are not set, you will get this error notice.  So, your issue has nothing to do with the script you are showing, but your HTML form.  Make sure the inputs have names, and always use print_r or var_dump as a reality check.

echo('<pre>'.print_r($_POST,1).'</pre>');
Link to comment
Share on other sites

 

At the top of your script, add the following.  This will print out all the fields you are sending in the form to the server.  What do you see?  If $_POST["phoneno"], etc are not set, you will get this error notice.  So, your issue has nothing to do with the script you are showing, but your HTML form.  Make sure the inputs have names, and always use print_r or var_dump as a reality check.

echo('<pre>'.print_r($_POST,1).'</pre>');

I literally have no clue what that means? Can you explain where I could put this line to make it useful in my code.

Link to comment
Share on other sites

can we see your HTML code as it appears that the php cannot find the values name, phone, etc also it might help if at the top of your php you put

$name = "";
$email = "";
$phoneno = "";
$comment = "";

this means that the variables are empty because until the forms details are entered they are empty and won't return a value for php to find an index and that should clear those errors

Link to comment
Share on other sites

I literally have no clue what that means? Can you explain where I could put this line to make it useful in my code.

Per my original post.... At the top of your script, add the following.  This will print out all the fields you are sending in the form to the server.

 

When things are not as you expect, I have found NEVER assume that the values in your variables are correct.  Always display them on the screen using print_r() or dump_var().  If your SQL isn't working, similarly just echo the query to the page, make sure it looks okay, and manually execute it using MySQL.

Link to comment
Share on other sites

can we see your HTML code as it appears that the php cannot find the values name, phone, etc also it might help if at the top of your php you put

$name = "";
$email = "";
$phoneno = "";
$comment = "";

this means that the variables are empty because until the forms details are entered they are empty and won't return a value for php to find an index and that should clear those errors

Um... Sorry but Undefined index has nothing to do with those variables!

 

The issue is the $_POST array will not be populated with the form values until the form has been submitted. PHP is reporting an undefined index because the keys name, email, phoneno, and comment does not exist in the $_POST array.

 

@G3NERALCHRIS 

 

You should be checking to make sure the data exists before using it. Example

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    // get data from post
    $name = $_POST["name"];
    $email = $_POST["email"];
    $phoneno = $_POST["phoneno"];
    $comments = $_POST["comments"];  

    // add data to the database
}

Also you should stop using the mysql_* functions they are deprecated. You should be using PDO or MySQLi with prepared statements when using user input in your queries.

Edited by Ch0cu3r
Link to comment
Share on other sites

My html code. For contact.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Contact Chris</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<!-- templatemo 301 blue ice -->
<!-- 
Blue Ice Template 
http://www.templatemo.com/preview/templatemo_301_blue_ice 
-->
<link href="templatemo_style.css" rel="stylesheet" type="text/css" />

</head>
<body>

<div id="templatemo_wrapper"> 

	<div id="templatemo_header">
	  <p><!-- end of site_title -->
    	  
  	  </p>
    	<ul id="social_box">
          <li><a href="https://www.facebook.com/christopher.deaton.399"><img src="images/facebook.png" alt="facebook" /></a></li>
            <li><a href="https://twitter.com/G3NERALCHRIS"><img src="images/twitter.png" alt="twitter" /></a></li>
            <li></li>
            <li></li>
            <li></li>                
        </ul>
        
    </div> <!-- end of templatemo_header -->
    
    <div id="templatemo_menu">
    	<div class="home"><a href="index.html"></a></div>
    	<ul>
    	  <li><a href="index.html">WHAT WE DO<span>Home</span></a></li>
    	  <li><a href="guestbook.php">Sign<span>Guestbook</span></a></li>
    	  <li><a href="about.html">WHO WE ARE<span>About Me</span></a></li>
    	  <li><a href="contact.html" class="last">ANY QUESTION?<span>Contact Me</span></a></li>
  	  </ul>
    </div> <!-- end of templatemo_menu -->
    
    <div id="templatemo_content_wrapper">
    	<div id="templatemo_content_top"></div>
        <div id="templatemo_content">
        
            <h2>Contact Me!</h2>

            <p> </p>
            <div id="contact_form">
            
              <h4>Quick Contact</h4>
                    
                    <form method="post" name="contact" action="#">
                        
                        <div class="col_w340 float_l">
                        
                            <label for="author">Name:</label> <input name="author" type="text" class="input_field" id="author" maxlength="40" />
                          	<div class="cleaner_h10"></div>
                            
                            <label for="email">Email:</label> <input name="email" type="text" class="input_field" id="email" maxlength="40" />
                          	<div class="cleaner_h10"></div>
                            
                            <label for="phone">Phone:</label> <input name="phone" type="text" class="input_field" id="phone" maxlength="40" />
                            <div class="cleaner_h10"></div>
                            
                        </div>
                        
                        <div class="col_w340 float_r">
                        
                            <label for="text">Message:</label> <textarea id="text" name="text" rows="0" cols="0" class="required"></textarea>
                            <div class="cleaner_h10"></div>
                            
                            <input name="submit" type="submit" class="submit_btn float_l" id="submit" formaction="add-contactme.php" value="Send" />
                            <input type="reset" class="submit_btn float_r" name="reset" id="reset" value="Reset" />
                            
                        </div>
                        
                   </form>

            </div>
       	  <p> </p>
            <div class="cleaner"></div>
            
        </div>
        <div id="templatemo_content_bottom"></div>
	</div>
    <div id="templatemo_footer"></div> <!-- end of templatemo_footer -->
    
</div> <!-- end of templatemo_wrapper -->    

</body>
</html>


Link to comment
Share on other sites

Your form seems to work fine.  Try adding <?php echo('<pre>'.print_r($_POST,1).'</pre>'); ?> right below the opening <body> tag, and you will see your post values.  Note that I never used the attribute formaction before, however, it seems to override the form to go to that URL (however, it doesn't validate?). Either get rid of this attribute and let your form tag define the location, or name this main file "add-contactme.php"

Link to comment
Share on other sites

Your form seems to work fine.  Try adding <?php echo('<pre>'.print_r($_POST,1).'</pre>'); ?> right below the opening <body> tag, and you will see your post values.  Note that I never used the attribute formaction before, however, it seems to override the form to go to that URL (however, it doesn't validate?). Either get rid of this attribute and let your form tag define the location, or name this main file "add-contactme.php"

 This did not work any other suggestion would be helpful. From that you told me to add <?php echo('<pre>'.print_r($_POST,1).'</pre>'); ?>

below the body in the contact.html. Unless something is going wrong. I can't not explain basically this is my second sql table and I basically used the same method but instead of hyperlinking from text in each html i have a contact section which saves the contacts in the table. Unlike my comments one which just save comments and is viewable. 

That is what I did below for guestbook. This works simple enough. But my contact page is more complicated. Unless I can create inside the html that php any suggestion.

<html>
<style type="text/css">
@import url("templatemo_style.css");
</style>
<body>My Hometown Guestbook </p>

<form action="add-guestbook.php" method="post" style="font-size: 36px">
    Name: <input type = "text" name="name"><br>
    E-mail: <input type = "text" name="email"><br>
    Comments: <input type = "text" name="comments"><br>
    <input type="submit">

</form>
</body>
</html>
Link to comment
Share on other sites

Hello Chris,

 

Maybe you know all this, and if so, tell me so and I will shut up.  The only reason I harp on it is I feel it is the number one important thing beginners need to understand.  Not understanding leads to frustration as I have personally experienced.  If you already know, disregard, otherwise...

 

There are two things that talk to each other:  the client (AKA the IE/FF/Chrome/etc browser) and the server (AKA your PHP server).

 

The client communicates to the server via three ways:

  1. GET request.  Basically includes the information in name/pairs in the URL, and is typically used when the client just wants to get more stuff.
  2. POST request.  Definitely not in the URL, but I think a header or something.  Typically used when the client wants to change the state of the server (i.e. write to the database).
  3. COOKIE request.  Used to tell the server information about who the client is.  SESSIONS are also used for this, but are just a glorified COOKIE where the real information is derived from the key given in the cookie.

The server just pumps stuff to the client.  In your case, it will probably be just HTML, however, it could also be JSON, XML, etc.

 

If you don't get this working right, nothing else will work right.  Don't worry about you SQL, etc, unless you know this is working.  The whole purpose of var_dump($_POST) or print_r($_POST) is just to know that the client is communicating to the server.  Have I made myself clear?  Get this part working before doing anything else!  If your server is attempting to access POST (or GET or COOKIE) data which doesn't exist, go back to square one, and find why it isn't being sent.

 

Hope this helps!

Link to comment
Share on other sites

looking at the HTML code you have posted your not getting the values because your asking php to collect Name, Email, Phoneno, Comments but your id / names of your inputs are Authour, Email, Phone, Text. the $_POST will be looking for the input id / name to get the post from.

if (isset($_POST['author']) && ($_POST['author'] !='')){
// get data from post
$name = $_POST["author"];
$email = $_POST["email"];
$phoneno = $_POST["phone"];
$comments = $_POST["text"]; 

// echo result
$result = $name - $email - $phoneno - $comments;
}

just put the <?php echo $result; ?> between your body tags in the HTML for testing purposes and it should display what is being sent from the form.

Edited by mik_se7
Link to comment
Share on other sites

looking at the HTML code you have posted your not getting the values because your asking php to collect Name, Email, Phoneno, Comments but your id / names of your inputs are Authour, Email, Phone, Text. the $_POST will be looking for the input id / name to get the post from.

if (isset($_POST['author']) && ($_POST['author'] !='')){
// get data from post
$name = $_POST["author"];
$email = $_POST["email"];
$phoneno = $_POST["phone"];
$comments = $_POST["text"]; 

// echo result
$result = $name - $email - $phoneno - $comments;
}

just put the <?php echo $result; ?> between your body tags in the HTML for testing purposes and it should display what is being sent from the form.

 

This does work but I put in my code like so, in  my add-contactme.php

and added that line in my html. But using command prompt it hasn't added nothing into the database itself but i does come up like so

echo "Successful" . "<BR>"; so this show Succesful when it work this show but nothing has been added to the table. Any suggestions?

if (isset($_POST['author']) && ($_POST['author'] !='')){
// get data from post
$name = $_POST["author"];
$email = $_POST["email"];
$phoneno = $_POST["phone"];
$comments = $_POST["text"];

$sql="INSERT INTO $tbl_name VALUES ('$name', '$email', '$phoneno''$comments')";
$result=mysql_query($sql);
// echo result
$result = $name - $email - $phoneno - $comments;
}
Link to comment
Share on other sites

 

 

But using command prompt it hasn't added nothing into the database itself

What? You are running your script from a desktop command window (bash terminal or cmd.exe) to test it? So you are not running it from your web browser?

 

In order for your script to add anything to the database you need run a POST HTTP request to your PHP script passing in the data for the fields named author, email, phone and text. Otherwise no data will be added to your database!

Link to comment
Share on other sites

What? You are running your script from a desktop command window (bash terminal or cmd.exe) to test it? So you are not running it from your web browser?

 

In order for your script to add anything to the database you need run a POST HTTP request to your PHP script passing in the data for the fields named author, email, phone and text. Otherwise no data will be added to your database!

I'm using xampp to run mysql and then running command prompt to see if any data has been added to the table. Can you explain how POST HTTP works and how I would go about doing this for my work please?

Link to comment
Share on other sites

Ok Ignore my last reply. I though you were using command prompt to run your code. You just confirmed you are only using it to for accessing your mysql database.

 

Can you post your current code you are using.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Contact Chris</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<!-- templatemo 301 blue ice -->
<!--
Blue Ice Template
http://www.templatemo.com/preview/templatemo_301_blue_ice
-->
<link href="templatemo_style.css" rel="stylesheet" type="text/css" />

</head>
<body>
<?php echo $result; ?>

<div id="templatemo_wrapper">

    <div id="templatemo_header">
      <p><!-- end of site_title -->
          
        </p>
        <ul id="social_box">
          <li><a href="https://www.facebook.com/christopher.deaton.399"><img src="images/facebook.png" alt="facebook" /></a></li>
            <li><a href="https://twitter.com/G3NERALCHRIS"><img src="images/twitter.png" alt="twitter" /></a></li>
            <li></li>
            <li></li>
            <li></li>                
        </ul>
        
    </div> <!-- end of templatemo_header -->
    
    <div id="templatemo_menu">
        <div class="home"><a href="index.html"></a></div>
        <ul>
          <li><a href="index.html">WHAT WE DO<span>Home</span></a></li>
          <li><a href="guestbook.php">Sign<span>Guestbook</span></a></li>
          <li><a href="about.html">WHO WE ARE<span>About Me</span></a></li>
          <li><a href="contact.html" class="last">ANY QUESTION?<span>Contact Me</span></a></li>
        </ul>
    </div> <!-- end of templatemo_menu -->
    
    <div id="templatemo_content_wrapper">
        <div id="templatemo_content_top"></div>
        <div id="templatemo_content">
        
            <h2>Contact Me!</h2>

            <p> </p>
            <div id="contact_form">
            
              <h4>Quick Contact</h4>
                    
                    <form method="post" name="contact" action="#">
                        
                        <div class="col_w340 float_l">
                        
                            <label for="author">Name:</label> <input name="author" type="text" class="input_field" id="author" maxlength="40" />
                              <div class="cleaner_h10"></div>
                            
                            <label for="email">Email:</label> <input name="email" type="text" class="input_field" id="email" maxlength="40" />
                              <div class="cleaner_h10"></div>
                            
                            <label for="phone">Phone:</label> <input name="phone" type="text" class="input_field" id="phone" maxlength="40" />
                            <div class="cleaner_h10"></div>
                            
                        </div>
                        
                        <div class="col_w340 float_r">
                        
                            <label for="text">Message:</label> <textarea id="text" name="text" rows="0" cols="0" class="required"></textarea>
                            <div class="cleaner_h10"></div>
                            
                            <input name="submit" type="submit" class="submit_btn float_l" id="submit" formaction="add-contactme.php" value="Send" />
                            <input type="reset" class="submit_btn float_r" name="reset" id="reset" value="Reset" />
                            
                        </div>
                        
                   </form>

            </div>
             <p> </p>
            <div class="cleaner"></div>
            
        </div>
        <div id="templatemo_content_bottom"></div>
    </div>
    <div id="templatemo_footer"></div> <!-- end of templatemo_footer -->
    
</div> <!-- end of templatemo_wrapper -->    

</body>
</html>
<?php
$host="localhost";         // Host name
$username="root";         // Mysql username
$password="";         // Mysql password
$db_name="test";         // Database name
$tbl_name="contactme";     // Table name

mysql_connect ("$host", "$username", "$password") or die ("cannot connect server ");
mysql_select_db ("$db_name") or die ("cannot select DB");

if (isset($_POST['author']) && ($_POST['author'] !='')){
// get data from post
$name = $_POST["author"];
$email = $_POST["email"];
$phoneno = $_POST["phone"];
$comments = $_POST["text"];

$sql="INSERT INTO $tbl_name VALUES ('$name', '$email', '$phoneno''$comments')";
$result=mysql_query($sql);
// echo result
$result = $name - $email - $phoneno - $comments;
}


if($result){
echo "Successful" . "<BR>";
echo "<a href='view-contactme.php'>View Contact Me</a>"; // link to view contact me page
}
mysql_close();
?>

This last is to view whether it works or not.

<?php
$host= "localhost";
$user = "root";
$passwd = "";
$database = "test";
$tbl_name = "contactme";

mysql_connect ($host, $user, $passwd) or  die("cannot connect server ");
mysql_select_db( $database) or die("cannot select DB");

$result=mysql_query("SELECT * FROM $tbl_name");

while($rows = mysql_fetch_array($result)){
echo $rows['name'] .  " "  .$rows['email'] .  " " .  $rows['phoneno']  .  " " .  $rows['comments'] . "<br>";
}
mysql_close();     //close database
?>

 

 

Link to comment
Share on other sites

your passing your values but not telling where you want to add them.

 

INSERT INTO table name (name,email, phone, comments) VALUES ('$name', '$email', '$phoneno''$comments')

 

 

also you have 2 $result variables i would change the query to $query rather than $result

Edited by mik_se7
Link to comment
Share on other sites

So the first block of code is contact.html?
 
The second block of code is add-contact.php? If thats correct then this line in contact.html

 <form method="post" name="contact" action="#">

should be

 <form method="post" name="contact" action="add-contact.php">

.
The code for add-contact.php should be like

<?php

$host="localhost";         // Host name
$username="root";         // Mysql username
$password="";         // Mysql password
$db_name="";         // Database name
$tbl_name="contactme";     // Table name

// using mysqli see http://php.net/mysqli for documentation
$mysqli = new mysqli("$host", "$username", "$password", "$db_name");

// if a post request has been made
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    // Simple data validation checking to make sure name, email, phone and comment exist. 

    // You should do futher checks here, ie making sure 
    //      - a name has been entered - it is not just an empty string
    //      - email address entered is a valid address 
    //      - the phone number is a valid phone number
    //      - a comment was entered - it is not just an empty string

        // set to true for now. This will be set to false if the data does not validate
        $isValidData = true;

        // used to log errors for fields that do not validate
        $errors = array();

        // check to make sure name exists in POST
        if(isset($_POST['name']))
        {
            $name = $_POST['name'];
        }
        else
        {
            // add error to $errors array
            $errors[] = 'Please enter your name';
        }

        // check to make sure email exists in POST
        if(isset($_POST['email']))
        {
            $email = $_POST['email'];
        }
        else
        {
            // add error to $errors array
            $errors[] = 'Please enter your email address';
        }

        // check to make sure phone exists in POST
        if(isset($_POST['phone']))
        {
            $phone = $_POST['phone'];
        }
        else
        {
            // add error to $errors array
            $errors[] = 'Please enter your phone number';
        }

        // check to make sure comment exists in POST
        if(isset($_POST['comment']))
        {
            $comment = $_POST['comment'];
        }
        else
        {
            // add error to $errors array
            $errors[] = 'Please enter your comment';
        }
    // end validation

    // check to make sure data did validate - nothing  should be in $errors.
    if(count($errors) != 0)
    {
        // set to false
        $isValidData = false;

        // display the error messages for fields that do not validate
        echo 'Please correct the following: <ul><li>' . implode('</li></li>', $errors) . '</li></ul>';

        // dispay the contact form again here
        include 'contactme.html';
        exit;
    }

    // only run the query if the data is valid
    if($isValidData)
    {
        // use a prepared statement for inserting data into the table
        $stmt = $mysqli->prepare("INSERT INTO $tbl_name VALUES (?, ?, ?, ?)");

        // bind the values to the query
        $stmt->bind_param('ssss', $name, 
                                  $email, 
                                  $phone, 
                                  $comment);

        // execute prepared statement
        $result = $stmt->execute();

        // make sure the statement did not return an error
        if(!$result)
        {
            // trigger error.
            trigger_error("Unable to insert data into $tbl_name in the database. " . $mysqli->error);
        }

        // check to see if the insert query did affect the table.
        if($result && $mysqli->affected_rows)
        {
            echo "Successful<BR>";
            echo "<a href='view-contactme.php'>View Contact Me</a>"; // link to view contact me page
        }
    }
}

 

As you can see there is a lot more code involved. I have added comments to all lines which explains what is happening. The code will either insert the data into the database or display basic validation errors if the data does not validate. 

Edited by Ch0cu3r
Link to comment
Share on other sites

I realize you are just testing, but this is a big no-no.  Read up on SQL injection if you don't know.  Easiest solution is to use PDO's prepared statements as Ch0cu3r describes.

 

// get data from post
$name = $_POST["author"];
$email = $_POST["email"];
$phoneno = $_POST["phone"];
$comments = $_POST["text"];

$sql="INSERT INTO $tbl_name VALUES ('$name', '$email', '$phoneno''$comments')";
$result=mysql_query($sql);

 

Link to comment
Share on other sites

So the first block of code is contact.html?

 

The second block of code is add-contact.php? If thats correct then this line in contact.html

 <form method="post" name="contact" action="#">

should be

 <form method="post" name="contact" action="add-contact.php">

.

The code for add-contact.php should be like

<?php

$host="localhost";         // Host name
$username="root";         // Mysql username
$password="";         // Mysql password
$db_name="";         // Database name
$tbl_name="contactme";     // Table name

// using mysqli see http://php.net/mysqli for documentation
$mysqli = new mysqli("$host", "$username", "$password", "$db_name");

// if a post request has been made
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    // Simple data validation checking to make sure name, email, phone and comment exist. 

    // You should do futher checks here, ie making sure 
    //      - a name has been entered - it is not just an empty string
    //      - email address entered is a valid address 
    //      - the phone number is a valid phone number
    //      - a comment was entered - it is not just an empty string

        // set to true for now. This will be set to false if the data does not validate
        $isValidData = true;

        // used to log errors for fields that do not validate
        $errors = array();

        // check to make sure name exists in POST
        if(isset($_POST['name']))
        {
            $name = $_POST['name'];
        }
        else
        {
            // add error to $errors array
            $errors[] = 'Please enter your name';
        }

        // check to make sure email exists in POST
        if(isset($_POST['email']))
        {
            $email = $_POST['email'];
        }
        else
        {
            // add error to $errors array
            $errors[] = 'Please enter your email address';
        }

        // check to make sure phone exists in POST
        if(isset($_POST['phone']))
        {
            $phone = $_POST['phone'];
        }
        else
        {
            // add error to $errors array
            $errors[] = 'Please enter your phone number';
        }

        // check to make sure comment exists in POST
        if(isset($_POST['comment']))
        {
            $comment = $_POST['comment'];
        }
        else
        {
            // add error to $errors array
            $errors[] = 'Please enter your comment';
        }
    // end validation

    // check to make sure data did validate - nothing  should be in $errors.
    if(count($errors) != 0)
    {
        // set to false
        $isValidData = false;

        // display the error messages for fields that do not validate
        echo 'Please correct the following: <ul><li>' . implode('</li></li>', $errors) . '</li></ul>';

        // dispay the contact form again here
        include 'contactme.html';
        exit;
    }

    // only run the query if the data is valid
    if($isValidData)
    {
        // use a prepared statement for inserting data into the table
        $stmt = $mysqli->prepare("INSERT INTO $tbl_name VALUES (?, ?, ?, ?)");

        // bind the values to the query
        $stmt->bind_param('ssss', $name, 
                                  $email, 
                                  $phone, 
                                  $comment);

        // execute prepared statement
        $result = $stmt->execute();

        // make sure the statement did not return an error
        if(!$result)
        {
            // trigger error.
            trigger_error("Unable to insert data into $tbl_name in the database. " . $mysqli->error);
        }

        // check to see if the insert query did affect the table.
        if($result && $mysqli->affected_rows)
        {
            echo "Successful<BR>";
            echo "<a href='view-contactme.php'>View Contact Me</a>"; // link to view contact me page
        }
    }
}

 

As you can see there is a lot more code involved. I have added comments to all lines which explains what is happening. The code will either insert the data into the database or display basic validation errors if the data does not validate. 

All i get now is the following? Can you explain why? Please correct the following:

  • Please enter your name
  • Please enter your comment

After adding a name, email, phoneno and comment it still comes up which that message why?

 

I do understand why the if statement is their, but still don't understand why the error is occurring still. Unless its above the given char length which I doubt. I only put 'Chris' and 'Hello' in the comments.

Edited by G3NERALCHRIS
Link to comment
Share on other sites

you need to change the code to:

 

for the name:

if(isset($_POST['author']))
{
$name = $_POST['author']

and for comments to

if(isset($_POST['text']))
{
$name = $_POST['text']

now the code should work

 

just copy and paste this section over that code:

// check to make sure name exists in POST
if(isset($_POST['author']))
{
$name = $_POST['author'];
}
else
{
// add error to $errors array
$errors[] = 'Please enter your name';
}

// check to make sure email exists in POST
if(isset($_POST['email']))
{
$email = $_POST['email'];
}
else
{
// add error to $errors array
$errors[] = 'Please enter your email address';
}

// check to make sure phone exists in POST
if(isset($_POST['phone']))
{
$phone = $_POST['phone'];
}
else
{
// add error to $errors array
$errors[] = 'Please enter your phone number';
}

// check to make sure comment exists in POST
if(isset($_POST['text']))
{
$comment = $_POST['text'];
}
else
{
// add error to $errors array
$errors[] = 'Please enter your comment';
}
// end validation
Edited by mik_se7
Link to comment
Share on other sites

 

 

Can you explain why

In your html your have named your Name field  author  and the Comment field  text  

 

You are getting those validation messages because PHP is looking for fields named name   and   comment

 

To correct the issue rename the fields in your HTML and PHP code so they match. The names you place in the square brackets for $_POST needs to match the name of the corresponding field in your HTML.

Link to comment
Share on other sites

In your html your have named your Name field  author  and the Comment field  text  

 

You are getting those validation messages because PHP is looking for fields named name   and   comment

 

To correct the issue rename the fields in your HTML and PHP code so they match. The names you place in the square brackets for $_POST needs to match the name of the corresponding field in your HTML.

Fatal error: Call to a member function bind_param() on a non-object in C:\xampp\htdocs\hometown\hometown\add-contactme.php on line 94

I have no idea what this fatal error means can you explain?

Link to comment
Share on other sites

whats on line 94 in add-contactme.php

line 94 - $stmt->bind_param('ssss', $name,

                                  $email,

                                  $phone,

                                  $comment);

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.