Jump to content

PHP/MySQL add record problem


meretrix

Recommended Posts

I'm starting a small business and I've never used php before.  I used oracle in college and some mysql, but I'm struggling getting php to work for me.  I'm trying to add records to a table I've already created.  I'm using a localhost mysql install before I fully deploy.

 

Here is the code:

 

addrecord.php

<?php
if ((!$_POST[firstname]) || (!$_POST[lastname]) || (!$_POST[phone1])) { header( "Location: http://127.0.0.1/addcustomer.php"); exit; } 

include 'config.php';
include 'opendb.php';
$table_name = "customer";


$sql = "INSERT INTO $table_name (firstname, lastname, phone1, phone2, fax, email) VALUES ('$_POST[firstname]', '$_POST[lastname]', '$_POST[phone1]', '$_POST[phone2]', '$_POST[fax]', '$_POST[email]')"; 
$result = @mysql_query($sql,$connection) or die(mysql_error());
?>
<HTML>
<HEAD>
<TITLE>Add a Record</TITLE>
</HEAD>
<BODY>
<H1>Adding a Record to <? echo "$table_name"; ?></H1>
<? echo "$_POST[firstname]"; ?></P>
<? echo "$_POST[lastname]"; ?></P>
<? echo "$_POST[phone1]"; ?></P>
<? echo "$_POST[phone2]"; ?></P>
<? echo "$_POST[fax]"; ?></P>
<? echo "$_POST[email]"; ?></P>

echo "Welcome {$_POST['firstname']} thanks for filling in out form";  

<P><a href="addcustomer.html">Add Another</a></P> 
</BODY>
</HTML>

 

addcustomer.html

<?php

//include 'config.php';
//include 'opendb.php';

//$tablename='customer';


//function showerror( ) 
//{ die("Error " . mysql_errno( ) . " : " . mysql_error( ));
//} 


//function insertion($firstname, $lastname, $phone1, $phone2, $fax, $email)
//{
//		 $customer_query = "INSERT INTO $tablename VALUES(NULL, firstname, lastname, phone1, phone2, fax, email) VALUES ('$firstname', '$lastname', '$phone1', '$phone2, '$fax', '$email')";
//		 $result_id = mysql_query($customer_query) OR die($customer_query . mysql_error());
//}



?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>

<head>
  <title>Add Customer</title>
  <meta name="generator" content="">
  <meta name="description" content="">
  <meta name="keywords" content="">
</head>
<body bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#800080" alink="#ff0000">
<FORM METHOD="POST" ACTION="addrecord.php"><br>
First Name:<input name="firstname" size="13">      
Last Name:<input name="lastname">   <br>
Primary Phone Number:<input type="int" name="phone1" size="10"> <br>
Secondary Phone Number:<input type="int" name="phone2" size="10"> <br>
Fax Number:<input type="int" name="fax" size="10"> <br>
Email Address:<input name="email" size="30"> <br>
<INPUT TYPE="submit" NAME="submit" VALUE="Submit">
</form>

<!-- DONT FORGET TO VALIDATE FORM -->
<!-- IF IT PASSES, FILL THE DATABASE -->



<div style="MARGIN: 1em auto; FONT: 11px arial,sans-serif; TEXT-ALIGN: center"> </div>
</body>
</html>

 

config.php

<?php
$dbhost = 'localhost;
$dbuser = 'root';
$dbpass = '';
$dbname = 'aviation';

function showerror( )
   {
      die("Error " . mysql_errno( ) . " : " . mysql_error( ));
   }
?>

 

opendb.php

<?php
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die                      ('Error connecting to mysql');
mysql_select_db($dbname);
?>

 

I'm not getting any data from $_Post['anything'] nor is my table receiving data.  What's wrong?

Link to comment
Share on other sites

One thing I notice right away is that you are not using quotes around your $_POST['array'] names.

 

Second thing, you are not escaping any of your input before adding to the DB.  This is very dangerous because you can inject a lot of bad sql code in there and you wouldn't even know it.

Link to comment
Share on other sites

Where are you defining $connection?  (either way, it doesn't look necessary in your code...your insert syntax looks proper minus whatever that variable is).

 

When you're at addrecord.php, are you getting errors?

 

When you echo the $_POST results, do you see them?  How far in the addrecord script are you getting?

Link to comment
Share on other sites

Yeah seem fairly obvious that you're not utilised your connection properly. I point you the following (line 10 of addrecord.php):

$result = @mysql_query($sql,$connection) or die(mysql_error());

You are using the variable $connection, but in your opendb.php you are defining your connection as the variable $conn.

Which are you going to use ;)

Link to comment
Share on other sites

Where are you defining $connection?  (either way, it doesn't look necessary in your code...your insert syntax looks proper minus whatever that variable is).

 

When you're at addrecord.php, are you getting errors?

 

When you echo the $_POST results, do you see them?  How far in the addrecord script are you getting?

 

Great catch on the $conn vs $connection.  I changed the opendb.php variable to $connection. 

 

The results page (addrecord.php) shows me this:

"

Adding a Record to

 

echo "Welcome $_POST['firstname'] thanks for filling in out form";

 

Add Another

"

That's it.  So I'm still messed up somewhere.  Here is how I changed my code to include $_POST['var']

 

<?php
if ((!$_POST['firstname']) || (!$_POST['lastname']) || (!$_POST['phone1'])) { header( "Location: http://127.0.0.1/addcustomer.php"); exit; } 

include 'config.php';
include 'opendb.php';
$table_name = "customer";


$sql = "INSERT INTO $table_name (firstname, lastname, phone1, phone2, fax, email) VALUES ('$_POST[firstname]', '$_POST[lastname]', '$_POST[phone1]', '$_POST[phone2]', '$_POST[fax]', '$_POST[email]')"; 
$result = @mysql_query($sql,$connection) or die(mysql_error());
?>
<HTML>
<HEAD>
<TITLE>Add a Record</TITLE>
</HEAD>
<BODY>
<H1>Adding a Record to <? echo "$table_name"; ?></H1>
<? echo "$_POST['firstname']"; ?></P>
<? echo "$_POST['lastname']"; ?></P>
<? echo "$_POST['phone1']"; ?></P>
<? echo "$_POST['phone2']"; ?></P>
<? echo "$_POST['fax']"; ?></P>
<? echo "$_POST['email']"; ?></P>

echo "Welcome $_POST['firstname'] thanks for filling in out form";  

<P><a href="addcustomer.html">Add Another</a></P> 
</BODY>
</HTML>

Link to comment
Share on other sites

I spent the last 48 hours teaching myself php.  I got one of the learn php in 24 hours and basically worked through most of the book.  I rewrote my code (see below); however, I'm still stuck on something stupid and I can't figure out what.  Can someone see why this code is out putting this:

 

 

output:

Successfully added record:

firstname. ?>

lastname?>

phone1?>

$e

 

"; } require_once("addcustomer.html"); ?>

 

 

<?php

include 'config.php';
include 'opendb.php';
$table_name = "customer";

if ($_POST)
{
    $error = array();
    
    // Strip empty spaces and add slashes for database input
    $firstname = addslashes(trim($_POST['firstname']));
    $lastname = addslashes(trim($_POST['lastname']));
    $phone1 = addslashes(trim($_POST['phone1']));
    
    // Check for empty values or other problems here
    if (!$firstname) $error[] .= "Please enter your first name";
    if (!$lastname) $error[] .= "Please enter your last name";
    if (!$phone1) $error[] .= "Please enter your phone number";
    
    // No errors; put into database!
    if (empty($error))
    {
        $query = "INSERT INTO $table_name (firstname, lastname, phone1) VALUES ('$firstname', '$lastname', '$phone1')"; 
        $result = mysql_query($query) or die(mysql_error());
        $row = mysql_fetch_object($result);
	print "Row contains... " $row;
        
        // Close PHP and print HTML formatting - with inserted PHP variables
       ?>
        <h1>Successfully added record:</h1>
        <?php .$row->firstname. ?><br />
        <?=$row->lastname?><br />
        <?=$row->phone1?><br />
   <?php
    }
    // There were errors... print them!
    else foreach ($error as $e) print "<p>$e</p>";
} 

require_once("addcustomer.html");

?>

Link to comment
Share on other sites

You are having issues because you are constantly opening and closing PHP in between sending HTML, and you are not keeping proper track. This is common among new coders (and is frustrating for anyone to troubleshoot). Also, another thing, this code snippet:

 

        <h1>Successfully added record:</h1>
        <?php .$row->firstname. ?><br />
        <?=$row->lastname?><br />
        <?=$row->phone1?><br />
   <?php

 

Should be more like this:

 

        <h1>Successfully added record:</h1>
        <?php echo $row->firstname; ?><br />
        <?php echo $row->lastname; ?><br />
        <?php echo $row->phone1; ?><br />
   <?php

 

Although I might recommend this overall:

 

        // DO NOT Close PHP - print HTML formatting - with inserted PHP variables
        echo"<h1>Successfully added record:</h1>"
        .$row->firstname. "<br />"
        .$row->lastname. "<br />"
        .$row->phone1. "<br />";

    }
    // There were errors... print them!
    else foreach ($error as $e) print "<p>$e</p>";
}

 

Just remember that echoing HTML is fine, and allows you to embed variable calls without need for opening/closing PHP tags. You just have to learn to ESCape quotes in HTML, like this:

 

Normal HTML:

 

<table border="0" cellpadding="0" cellspacing="0">

 

ECHOed HTML:

 

<?php
echo"<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">

 

In your code above, there was nothing that needed to be ESCaped, so this was an example of what you might run into when echoing HTML.

 

PhREEEk

Link to comment
Share on other sites

You are having issues...

Should be more like this:

 

        <h1>Successfully added record:</h1>
        <?php echo $row->firstname; ?><br />
        <?php echo $row->lastname; ?><br />
        <?php echo $row->phone1; ?><br />
   <?php

 

I tried what you suggested but it just broke my code.  Here is my current re-write.  I don't know why if I don't enter any data it doesn't prompt me for firstname etc.  It also never sucessfully puts anything into my tables.

 

<?php

include 'config.php';
include 'opendb.php';
$table_name = "customer";

if (isset($_POST['submit'])) {
//THIS IS TERRIBLE CODING PRACTICE, CALL THE BUTTON subUpdate or something
    $error = ''; 
    
    // Check for empty values or other problems here
    if (!$firstname) $error .= "Please enter your first name";
    if (!$lastname) $error .= "Please enter your last name";
    if (!$phone1) $error .= "Please enter your phone number";

// Strip empty spaces and add slashes for database input
    $firstname = addslashes(trim($_POST['firstname']));
    $lastname = addslashes(trim($_POST['lastname']));
    $phone1 = addslashes(trim($_POST['phone1']));
    
    // No errors; put into database!
    if (empty($error))
    {
        $query = "INSERT INTO $table_name (firstname, lastname, phone1) VALUES ('$firstname', '$lastname', '$phone1')"; 
        $result = mysql_query($query) or die(mysql_error());
        $row = mysql_affected_rows();
	print "Row contains... " $row;
        
        // Close PHP and print HTML formatting - with inserted PHP variables
        ?> 
        <h1>Successfully added record:</h1>
        <?php echo $firstname ?><br />
        <?php echo $lastname ?><br />
        <?php echo $phone1 ?><br /> 
	<?php
    }
    // There were errors... print them!
    else {
	echo $error;
} 
}
else { 

?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>

<head>
  <title>Add Customer</title>
  <meta name="generator" content="">
  <meta name="description" content="">
  <meta name="keywords" content="">
</head>
<body bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#800080" alink="#ff0000">
<FORM METHOD="POST" ><br>
First Name:<input name="firstname" size="13">      
Last Name:<input name="lastname">   <br>
Primary Phone Number:<input type="int" name="phone1" size="10"> <br>
Secondary Phone Number:<input type="int" name="phone2" size="10"> <br>
Fax Number:<input type="int" name="fax" size="10"> <br>
Email Address:<input name="email" size="30"> <br>
<INPUT TYPE="submit" NAME="submit" VALUE="Submit">
</form>

<!-- DONT FORGET TO VALIDATE FORM -->
<!-- IF IT PASSES, FILL THE DATABASE -->



<div style="MARGIN: 1em auto; FONT: 11px arial,sans-serif; TEXT-ALIGN: center"> </div>
</body>
</html>
<?php
}
?>

Link to comment
Share on other sites

The script below has no parse errors. It definitely has some logic errors, but you can take it from here.

 

Note: From your script above, you were checking the existence of variable BEFORE you were assigning from the POST values. I switched that around so it makes sense.

 

<?php

include 'config.php';
include 'opendb.php';

$table_name = "customer";

if (isset($_POST['submit'])) {
//THIS IS TERRIBLE CODING PRACTICE, CALL THE BUTTON subUpdate or something
    $error = ''; 
    
// Strip empty spaces and add slashes for database input
    $firstname = addslashes(trim($_POST['firstname']));
    $lastname = addslashes(trim($_POST['lastname']));
    $phone1 = addslashes(trim($_POST['phone1']));
    
    // Check for empty values or other problems here
    if (!$firstname) $error .= "Please enter your first name";
    if (!$lastname) $error .= "Please enter your last name";
    if (!$phone1) $error .= "Please enter your phone number";

    // No errors; put into database!
    if (empty($error))
    {
        $query = "INSERT INTO $table_name (firstname, lastname, phone1) VALUES ('$firstname', '$lastname', '$phone1')"; 
        $result = mysql_query($query) or die(mysql_error());
        $row = mysql_affected_rows();
	echo "<p>
Row contains... $row</p>
<p>
<h1>Successfully added record:</h1></p>
<p>
$firstname
<br />
$lastname
<br />
$phone1
<br />"; 
    } else {
   	    // There were errors... print them!
	echo $error;
} 
} else {
// else what...?
} 

?>

 

PhREEEk

Link to comment
Share on other sites

Thanks for looking again.  It did give me errors though.  Did your output not look like this:

Row contains... "$row

 

Successfully added record:

 

$firstname

$lastname

$phone1

"; } else { // There were errors... print them! echo $error; } } else { // else what...? } ?>

Link to comment
Share on other sites

Dunno what to tell you...

 

Since I don't have your database to connect to, I didn't check the db stuff. Ran it sans any variables and got it to display all 3 error messages about input, so there weren't any actual parse errors.

 

Ok, try saving this as 'test.php' or whatever and run it:

 

<?php
$row = 5;
echo "<p>
Row contains... $row</p>
<p>
<h1>Successfully added record:</h1></p>
<p>
$firstname
<br />
$lastname
<br />
$phone1
<br />";
?>

 

Results:

Row contains... 5

 

 

Successfully added record:

 

Which is correct since we did not define any input variables... not the point, point is this. Run this code:

 

$row = 5;
echo "<p>
Row contains... $row</p>
<p>
<h1>Successfully added record:</h1></p>
<p>
$firstname
<br />
$lastname
<br />
$phone1
<br />";

 

Result:

$row = 5; echo "

Row contains... $row

 

 

Successfully added record:

 

$firstname

$lastname

$phone1

";

 

Looks familiar, eh? All I did was remove the open and closing PHP tags. So double check your code. Did you copy/paste my EXACT code from above, or did you merge some stuff? For some reason, I think you have shut off PHP in the script with a rogue ?>

 

PhREEEk

Link to comment
Share on other sites

something strange is happening here.  I copied your first test exactly, and pasted it into a test.php.  This is the code again so there is no confusion:

<?php
$row = 5;
echo "<p>
Row contains... $row</p>
<p>
<h1>Successfully added record:</h1></p>
<p>
$firstname
<br />
$lastname
<br />
$phone1
<br />";
?>

 

This is the output.  What the heck is going on?  Does firefox cause this error?  Surely not.

 

Row contains... $row

 

Successfully added record:

 

$firstname

$lastname

$phone1

"; ?>

Link to comment
Share on other sites

You must have a borked PHP install, that's my only guess, and based on all of the results you have posted (from the very beginning), PHP is not behaving correctly.

 

Please list your Operating System, server type (Apache, IIS?), etc... Did you download PHP in a server package, or just the standalone core from php.net? Save this as phpinfo.php and run it, post back the results:

 

<?php
phpinfo();
?>

 

PhREEEk

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.