Jump to content
gedda

db insert not working - not sure why

Recommended Posts

Hi folks,  really not sure what's going on here, but for whatever reason, my insert isn't being very nice.

 

Now admittedly, I'm doing a couple of things here. i.e. sending an email plus inserting the records into the mysql db, but I actually thought that this could work together.  The insert statement appears fine, the db credentials seem fine.  

 

So if someone can cast an eye over this and see what basic error I'm doing here please.

 

<?php
 
include "config.php";
 
// Change the line below to your timezone!
date_default_timezone_set('Australia/Brisbane');
$contactdate = date('Y/m/d h:i:s a', time());
 
// check if fields passed are empty
 
if(empty($_POST['name'])   ||
    empty($_POST['email']) ||
    empty($_POST['message']) ||
 
    !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
 
    {
    echo "No arguments Provided!";
    return false;
    }
 
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
 
$link = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
 
// Attempt insert query execution
$sql = "INSERT INTO contact (name, email, message, contactdate)
        VALUES ('$name','$email_address','$message','$contactdate'";
 
if(mysqli_query($link, $sql)){
    echo "Records inserted successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
 
// create email body and send it
$to = "$emailto"; // put your email
$email_subject = "Contact form submitted by:  $name";
$email_body = "You have received a new message. \n\n".
              " Here are the details:\n \nName: $name \n ".
              "Email: $email_address\n Message \n $message \n$sql
               \n$servername\n$username\n$password\n$dbname\n$emailto";
$headers = "From: $emailto\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
 
// Close connection
mysqli_close($link);
return true;
 
?>
Edited by gedda

Share this post


Link to post
Share on other sites

Step 0: Learn the basics of PHP, especially security and proper usage of mysqli (or better yet, replace mysqli with PDO).

 

Your code is broken in all kinds of ways, and it will behave even less nicely when you actually put it on the public Internet where it will be used and abused by many different people.

  • Never trust user input, not even your own. Do not ever put raw input into critical contexts like SQL queries or e-mail headers. This will lead to syntax errors and security vulnerabilities. When you need to pass dynamic values to an SQL query, use a prepared statement with parameters. When you need to build dynamic e-mail headers, use a library like PHPMailer which takes care of proper escaping.
  • Set up proper error handling. Instead of cluttering your code with debug output (which you hopefully remove in the production version), use exceptions and/or error triggers. Both PDO and mysqli can take care of their own errors.
  • Fix your timestamp format. Instead of making up your own custom format, you need to use one which MySQL actually understands. Or even better: Let MySQL set the current timestamp.

Make the fixes, then try again. If you're still having issues, you need to be a lot more specific than “my insert isn't being very nice”.

Share this post


Link to post
Share on other sites

For your specific error, if your error reporting is not throwing any PHP errors, check your query code. It may be missing a variable or be misconfigured. Try echoing out the  $sql variable so it gives you the specific SQL it is trying to run. Then run that in your database interface alone to see if it throws an error. This can help you if the issue is in the SQL statement itself.

Share this post


Link to post
Share on other sites

This sample program, which I use as a quick test of my database functionality, may be of some help to you. (I hope my esteemed colleagues on this forum will tell us if they find any major shortcomings to this code; it may not be the best style but it gets the job done.)

<?php

/* A standalone test file to see if we can connect to the database and read and
display a table. */

/* Connect to the database. */

	try {
		$db = new PDO('mysql:host=localhost;dbname=id1556139_topics;charset=utf8', 'id1556139_henry', 'password');
		$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
		}
	catch (PDOException $excp) {
		echo "Error getting database connection: " . $excp->getMessage();
		die();
		}   

	
/* Read a simple table and store the data in an array. Display each row as it is fetched. */
	
	$debug = 0;
	
	echo "<p>This report lists all members who choose to appear in the fake member directory.\n</p>";
	echo "<p>Dashes in the table represent values that are unknown or not applicable. For example, if a comment of a member is not provided, a dash is used to stand in for the unknown value.</p>\n";

	echo "<table class='generated'>\n";
	echo "<tr class='heading'><th>ID</th><th>Name</th><th>Email</th><th>Phone</th><th>Comment</th></tr>\n";

	try {
    	/* Display table loop */	
    	$stmt = $db->query("select id, name, email, phone, ifnull(comment,'-') as comment 
    	        from Contact_Info_Fake order by id");
    	
    	while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    	  $id = $row['id']; //store the ID from the current row of the Contact_Info table
    	  $name = $row['name']; //store the member name from the current row of the Contact_Info table
    	  $phone = $row['phone']; //store the phone number from the current row of the Contact_Info table
    	  $email = $row['email']; //store the email address from the current row of the Contact_Info table
    	  $comment = $row['comment']; //store the comment from the current row of the Contact_Info table
    	  if ($debug) {
    	      echo "Fetch<br/>";
    	      echo "  ID: $id<br/>";
    	      echo "  Name: $name<br/>";
    	      echo "  Phone: $phone<br/>";
    	      echo "  Email: $email<br/>";
    	      echo "  Comment: $comment<br/>";
    	  }
    	  Write_One_Member($id, $name, $phone, $email, $comment); //write the information for a single meeting	    	    
    	}
	}
	catch (PDOException $excp) {
	    echo "Error reading table Contact_Info_Fake: " . $excp->getMessage();
	}
	echo "</table>";
		
	exit(0);


	function Write_One_Member($id, $name, $phone, $email, $comment) {

	    global $debug;
	    
	    if ($debug) {
	      echo "<p>Write_One_Member:<br/>";
	      echo "  ID: $id<br/>";
	      echo "  Name: $name<br/>";
	      echo "  Phone: $phone<br/>";
	      echo "  Email: $email<br/>";
	      echo "  Comment: $comment<br/>";
	    }
	      
	    echo "<tr><td>$id</td><td>$name</td><td>$phone</td><td>$email</td><td>$comment</td></tr>\n";
	}
	
	?>

I was going to provide the SQL to create my little test table, Contact_Info_Fake, but it seems phpMyAdmin has dropped the ability to export that information to an external file so I'm going to have to leave that part to your imagination. Ask here if you need more information about that or any aspect of my PHP code.

Edited by HenryCan

Share this post


Link to post
Share on other sites

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.