Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 528
  • Last Modified:

php firstname, lastname, get form

want to add textbox 'lastname'
I know to add this line to html
<input type = "textbox" id="lastname" name = "lastname" value="" />



and this line to php
$query= "INSERT INTO NAMES (lastname) VALUES ('$lastname');
$result = mysql_query($query);



how do i change this line
isset($_GET['firstname'])?$firstname=$_GET['firstname']:$firstname="";
<!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" /></head> 
<body> 
 
<?php     
    isset($_GET['firstname'])?$firstname=$_GET['firstname']:$firstname=""; 
    if(strlen($firstname)>0) { 
        $connect = mysql_connect('localhost','root','password') or die("error to server !"); 
        mysql_select_db("database", $connect) or die("Error"); 
        $query = "INSERT INTO NAMES (firstname) VALUES ('$firstname')"; 
        $result = mysql_query($query); 
        mysql_close(); 
    } 
?> 
 
<form action="process.php" method="get"> 
<input type="textbox" id="firstname" name="firstname" value="" /> 
<input type="submit" id="but" value="Click here to save First Name to table 'name'" /> 
</form> 
</body> 
</html>

Open in new window

0
rgb192
Asked:
rgb192
  • 7
  • 2
1 Solution
 
Ray PaseurCommented:
You may be on a steep learning curve here.  Let's try to take this one bite at a time.

First, you must NEVER use the GET method to make a change to the data model.  If you're going to update a data base, choose POST, full stop.

Next, you need to learn about filtering and escaping.  Filters are used to make sure you do not put junk into your data base.  Escapes are used to allow you to insert the things you might need like the apostrophe in a name like O'Brien.
0
 
Ray PaseurCommented:
Now, looking at the instant piece of code, I would suggest that you might make your work simpler if you took all the data base connection stuff (along with our friends like session_start(), etc.) and put them into a separate script.  You can use include() to bring in that script.  If you do that you will never find yourself with a conditional connection to the data base.  Why avoid conditionals?  Because the more conditional statements you have, the more things can go wrong with your programs.
0
 
Ray PaseurCommented:
Looking at something like this...

or die("Error");

... makes me wonder, "What Error?"  So a strategy for dealing with errors should always include as much clarification and explanation as possible.  Make every error message unique!
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
igni7eCommented:
   isset($_GET['firstname'])?$firstname=$_GET['firstname']:$firstname="";
    if(strlen($firstname)>0) {
        $connect = mysql_connect('localhost','root','password') or die("error to server !");
        mysql_select_db("database", $connect) or die("Error");
        $query = "INSERT INTO NAMES (firstname, lastname) VALUES ('" . $firstname . "','" . $lastname . "')";
        $result = mysql_query($query);
        mysql_close();
    }
0
 
Ray PaseurCommented:
This is a recipe for frustration:

        $query = "INSERT INTO NAMES (firstname) VALUES ('$firstname')";
        $result = mysql_query($query);

When you execute the mysql_query() function, you get a return value in $result.  You can and MUST test the return value.  MySQL is not a "black box" and it can fail for reasons that are not even part of your program code.  If you do not test for failure and react appropriately, your programming may being making errors and you will not know of this until it is too late and your data base is damaged, so be sure to test the return value from mysql functions and deal with them appropriately.  Here is my "teaching sample" of how to do a few of the basics in PHP and MySQL.  It is not lightweight stuff, but hopefully it will give you some guidance you can use in the new year.  Please be sure to read all the man page references!  

Best, ~Ray
<?php // RAY_mysql_example.php
error_reporting(E_ALL);

// IMPORTANT PAGES FROM THE MANUALS
// MAN PAGE: http://us2.php.net/manual/en/ref.mysql.php
// MAN PAGE: http://us2.php.net/manual/en/mysql.installation.php
// MAN PAGE: http://us.php.net/manual/en/function.mysql-error.php



// CONNECTION AND SELECTION VARIABLES FOR THE DATABASE
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??";        // GET THESE FROM YOUR HOSTING COMPANY
$db_user = "??";
$db_word = "??";

// OPEN A CONNECTION TO THE DATA BASE SERVER
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-connect.php
if (!$db_connection = mysql_connect("$db_host", "$db_user", "$db_word"))
{
   $errmsg = mysql_errno() . ' ' . mysql_error();
   echo "<br/>NO DB CONNECTION: ";
   echo "<br/> $errmsg <br/>";
}

// SELECT THE MYSQL DATA BASE
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-select-db.php
if (!$db_sel = mysql_select_db($db_name, $db_connection))
{
   $errmsg = mysql_errno() . ' ' . mysql_error();
   echo "<br/>NO DB SELECTION: ";
   echo "<br/> $errmsg <br/>";
   die('NO DATA BASE');
}
// IF WE GOT THIS FAR WE CAN DO QUERIES




// ESCAPING A DATA FIELD FOR USE IN MYSQL QUERIES
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-real-escape-string.php
$safe_username = mysql_real_escape_string($_POST["username"]);




// CREATING AND SENDING A SELECT QUERY AND TESTING THE RESULTS
// MAN PAGE:http://us2.php.net/manual/en/function.mysql-query.php
$sql = "SELECT id FROM my_table WHERE username='$safe_username'";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
// MAN PAGE: http://us.php.net/manual/en/function.mysql-error.php
if (!$res)
{
   $errmsg = mysql_errno() . ' ' . mysql_error();
   echo "<br/>QUERY FAIL: ";
   echo "<br/>$sql <br/>";
   die($errmsg);
}
// IF WE GET THIS FAR, THE QUERY SUCCEEDED AND WE HAVE A RESOURCE-ID IN $res SO WE CAN NOW USE $res IN OTHER MYSQL FUNCTIONS




// DETERMINE HOW MANY ROWS OF RESULTS WE GOT
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-num-rows.php
$num = mysql_num_rows($res);
if (!$num)
{
   echo "<br/>QUERY FOUND NO DATA: ";
   echo "<br/>$sql <br/>";
}
else
{
   echo "<br/>QUERY FOUND $num ROWS OF DATA ";
   echo "<br/>$sql <br/>";
}




// ITERATE OVER THE RESULTS SET TO SHOW WHAT WE FOUND
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-fetch-assoc.php
echo "<pre>\n"; // MAKE IT EASY TO READ
while ($row = mysql_fetch_assoc($res))
{
   var_dump($row); // MAN PAGE: http://us2.php.net/manual/en/function.var-dump.php
}




// A WAY OF DETERMINING HOW MANY ROWS WE HAVE IN A TABLE
// MAN PAGE: http://us.php.net/mysql_fetch_array
$sql = "SELECT COUNT(*) FROM my_table";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
if (!$res)
{
   $errmsg = mysql_errno() . ' ' . mysql_error();
   echo "<br/>QUERY FAIL: ";
   echo "<br/>$sql <br/>";
   die($errmsg);
}
// GET THE RESULTS SET ROW IN AN ARRAY WITH A NUMERIC INDEX - POSITION ZERO IS THE COUNT
$row = mysql_fetch_array($res, MYSQL_NUM);
$num = $row[0];




// MAKING AN INSERT QUERY AND TESTING THE RESULTS
$sql = "INSERT INTO my_table (username) VALUES (\"$safe_username\")";
$res = mysql_query($sql);

// IF mysql_query() RETURNS FALSE, GET THE ERROR REASONS
if (!$res)
{
   $errmsg = mysql_errno() . ' ' . mysql_error();
   echo "<br/>QUERY FAIL: ";
   echo "<br/>$sql <br/>";
   die($errmsg);
}
// GET THE AUTO_INCREMENT ID OF THE RECORD JUST INSERTED - PER THE DB CONNECTION
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-insert-id.php
$id  = mysql_insert_id($db_connection);

Open in new window

0
 
Ray PaseurCommented:
I have not tested this (do not have your data base) but hopefully you can follow the principles.  Please post back if you have questions, ~Ray
<?php // RAY_temp_rgb192.php
error_reporting(E_ALL);

// CONNECT TO THE DATA BASE SERVER HERE

// SELECT THE DATA BASE HERE



// IF ANYTHING WAS POSTED
if (!empty($_POST["firstname"])) && !empty($_POST["lastname"]))
{

    // PURIFY THE INPUT DATA FOR USE IN QUERIES
    $fn  = mysql_real_escape_string($_POST["firstname"]);
    $ln  = mysql_real_escape_string($_POST["lastname"]);
    
    // CONSTRUCT A QUERY
    $sql = "INSERT INTO NAMES ( firstname, lastname ) VALUES ( '$fn', '$ln' )"; 
    
    // RUN THE QUERY
    $res = mysql_query($sql); 
    
    // TEST FOR SUCCESS AND ISSUE A FAILURE MESSAGE IF NEEDED
    if (!$res) die( mysql_error() );
    
    // TELL THE CLIENT YOU ARE FINISHED WITH THE TASK
    echo "ADDED $fn $ln TO NAMES";
    die("ALL DONE");
    
} // END OF PHP FORM PROCESSING, PUT UP THE HTML FORM
?> 
 
<form method="post"> 
<input name="firstname" /> 
<input name="lastname" /> 
<input type="submit" value="Click here to save First Name and Last Name to table NAME" /> 
</form>

Open in new window

0
 
rgb192Author Commented:
when i become a better programmer... I will use post

post is not working for me right now
right now, get is working for one value



this code should work for 2 values
but is working for 0 values

   isset($_GET['firstname'])?$firstname=$_GET['firstname']:$firstname="";
    if(strlen($firstname)>0) {
        $connect = mysql_connect('localhost','root','password') or die("error to server !");
        mysql_select_db("database", $connect) or die("Error");
        $query = "INSERT INTO NAMES (firstname, lastname) VALUES ('" . $firstname . "','" . $lastname . "')";
        $result = mysql_query($query);
        mysql_close();
    }
0
 
Ray PaseurCommented:
Sorry, you cannot wait... "when i become a better programmer... I will use post" - you have to use POST for what you're doing here, or you will (1) violate one of the cardinal rules of the internet and (2) write a script that can be used to pollute your data base.  

Consider this... You have a script that adds a row to the data base every time it is clicked on.  What if a client sits at his terminal clicking on it?  What if Google fetches it?  What if a hacker writes a script that calls your script 100,000,000 times?

You need to get a foundation in some of the basics of PHP and MySQL.  Please do yourself a favor and buy this book.  Work through the examples.  It is a guided tour that will make you a better programmer.
http://www.sitepoint.com/books/phpmysql4/

The difference between GET and POST is vitally important, and you must use the correct method.  You can only use GET for inquiries, not for data base updates - you have no choice about this; it is part of the architecture.
0
 
Ray PaseurCommented:
Going forward, please add this line to the top of all your scripts:

error_reporting(E_ALL);

And please post the code in the code snippet here at EE.  That way we get line numbers so we can associate the notices, warnings and error messages with the exact line of code that caused you trouble.

Best of luck with your project, and happy New Year, ~Ray
0
 
rgb192Author Commented:
worked for me...

without mysql_real_escape_string
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 7
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now