I'm trying to make a very basic comment system in PHP.
The problem is that when I submit the form, the new row doesn't get inserted in my MySQL table.
This is my code (, could someone please check what's wrong?):
<?php
$act = $_POST['act'];
if($act == 1) {
$m = $_POST['message'];
$m = strip_tags($m);
$message = mysql_real_escape_string($m);
$name = "Anonymous"; //Static username for demonstration purposes
$date = "2012-7-28"; //Static date for demonstration purposes
$con = mysql_connect("localhost","username","password");
if (!$con){die('Could not connect: ' . mysql_error());}
mysql_query("INSERT INTO comments (name, message, date) VALUES ('$name', '$message', '$date')");
mysql_close($con);
}
?>
<form action="comments.php" method="post">
<input type="text" name="message">
<input type="hidden" name="act" value="1">
<input type="submit" name="submit" value="Submit">
</form>
I think your problem rests with the escaping, or rather the 'non-escaping' of the column names. Did you know that 'date' is a function name in mySQL?
Try putting all table and column names in backticks.
mysql_query("INSERT INTO `comments` (`name`, `message`, `date`) VALUES ('$name', '$message', '$date')");
Also, for further reference, posting the error message never hurts looking for the answer.
Other than that, I can't find anything particularly wrong with your query.
Edit: DUH! I missed something obvious.
Please execute 'mysql_select_db('name_of_database'); prior to the query.
Otherwise it won't know where to look for the table you're specifying.
For the sake of completeness (as Michael Besteck pointed out), it is necessary to execute 'mysql_real_escape_string' only AFTER the connection has been established.
That is, because the 'escape_string' relies on the encoding of the connection to determine which characters need to be escaped and how.
It is neccessary to first establish the database connection because the escape function is executed my mysql.
$con = mysql_connect("localhost","username","password");
$message = mysql_real_escape_string($m);
Run the script with this code and post mysql_error
<?php
$act = $_POST['act'];
if($act == 1) {
$m = $_POST['message'];
$m = strip_tags($m);
$message = mysql_real_escape_string($m);
$name = "Anonymous"; //Static username for demonstration purposes
$date = "2012-7-28"; //Static date for demonstration purposes
$con = mysql_connect("localhost","username","password");
if (!$con){die('Could not connect: ' . mysql_error());}
mysql_query("INSERT INTO comments (name, message, date) VALUES ('$name', '$message', '$date')") or die(mysql_error());
mysql_close($con);
}
?>
<form action="comments.php" method="post">
<input type="text" name="message">
<input type="hidden" name="act" value="1">
<input type="submit" name="submit" value="Submit">
</form>
UODATE>
The working code is follows:
<?php
$act = $_POST['act'];
if($act == 1) {
$m = $_POST['message'];
$m = strip_tags($m);
$message = mysql_real_escape_string($m);
$name = "Anonymous"; //Static username for demonstration purposes
$date = "2012-7-28"; //Static date for demonstration purposes
$con = mysql_connect("localhost","username","password");
mysql_select_db('databasename');
if (!$con){die('Could not connect: ' . mysql_error());}
mysql_query("INSERT INTO comments (name, message, date) VALUES ('$name', '$message', '$date')") or die(mysql_error());
mysql_close($con);
}
?>
<form action="comments.php" method="post">
<input type="text" name="message">
<input type="hidden" name="act" value="1">
<input type="submit" name="submit" value="Submit">
</form>
Related
I know there a lot of questions on MySQL and PHP but I can't seem to find an answer simple enough for me to understand what to do and why.
Here is my form script
<form name="tickets" action="tickets98829849.php" method="get">
First Name: <input type="text" name="firstname"><br>
Last Name: <input type="text" name="lastname"><br><br>
Number of Tickets: <input type="text" name="quant"><br><br>
First and Last Name of Date: <input type="text" name="date"><br>
Date a guest? <input type="checkbox" name="guest" value="Yes">Yes<br><br>
Amount paid per ticket: <br><br>
$<input type="text" name="amount" size="2"><br>
<br><input type="submit" value="Submit"></form>
and here is my PHP script
<?php
define('DB_NAME', 'ticketpurch');
define('DB_USER', 'dbuser');
define('DB_PASSWORD', 'dbpsswd');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)
if (!$link) {
die('Could not connect: ' . mysqlerror());
}
$db_selectd = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can\'t use ' . DB_NAME . ': ' . mysqlerror());
}
$value1 = $_POST['firstname']
$value2 = $_POST['lastname']
$value3 = $_POST['quant']
$value4 = $_POST['datename']
$value5 = $_POST['guest']
$value6 = $_POST['amount']
$sql = "INSERT INTO $table ticketpurch (firstname, lastname, quant, datename, guest, amount) VALUES ('$value1', '$value2', '$value3', '$value4', '$value5', '$value6')";
$result = mysql_query($sql)
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
mysql_close();
>
When I use the form, the data does not get entered into the table. I do not get an error message. What is wrong with it for not letting me access the table and insert data? I am very new to php, so
Your form's submit method is get but you receive post method. Change it.
In form you mention method="get" change it to method="post"
It will work :)
Remove the $table from the statement. I'm assuming the correct table is ticketpurch, so all you did with $table was confuse the database. In addition, the other answers are also correct. Your form's method is "get," yet you're using $_POST to try to get the data. You should change the form to post, because get is incredibly insecure, especially if this involves purchases.
In addition, you're using deprecated functions like mysql_connect. Instead, use the PDO object. Instead of mysql_connect(), try this:
$table = "mytable";
$sql = new PDO;
$sql->__construct(DB_NAME, DB_USER, DB_PASS);
$stmnt = $sql->prepare("INSERT INTO ticketpurch (firstname, lastname, quant, datename, guest, amount) VALUES ('$value1', '$value2', '$value3', '$value4', '$value5', '$value6')";
$sql->execute($stmnt);
That will ensure that your statements are better secured against SQL injection.
Hope that helped.
Try Like this.
HTML CODE
<form name="tickets" action="tickets98829849.php" method="post">
First Name: <input type="text" name="firstname"><br>
Last Name: <input type="text" name="lastname"><br><br>
Number of Tickets: <input type="text" name="quant"><br><br>
First and Last Name of Date: <input type="text" name="date"><br>
Date a guest? <input type="checkbox" name="guest" value="Yes">Yes<br><br>
Amount paid per ticket: <br><br>
$<input type="text" name="amount" size="2"><br>
<br><input type="submit" value="Submit"></form>
tickets98829849.php code
<?php
define('DB_NAME', 'ticketpurch');
define('DB_USER', 'dbuser');
define('DB_PASSWORD', 'dbpsswd');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)
if (!$link) {
die('Could not connect: ' . mysqlerror());
}
$db_selectd = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can\'t use ' . DB_NAME . ': ' . mysqlerror());
}
$value1 = $_POST['firstname']
$value2 = $_POST['lastname']
$value3 = $_POST['quant']
$value4 = $_POST['datename']
$value5 = $_POST['guest']
$value6 = $_POST['amount']
$sql = "INSERT INTO $table ticketpurch (firstname, lastname, quant, datename, guest, amount) VALUES ('$value1', '$value2', '$value3', '$value4', '$value5', '$value6')";
$result = mysql_query($sql)
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
mysql_close();
>
If you use method="get" in the form,then receive html values using $_GET['html element name'];.But for security purpose ,we generally use method="post" in html code and receive value in action page using $_POST[];.
I have looked for the answer to my question and seeing as all programming varies I can't seem to fix my problem. I have created a php file that does in fact connect to my database. However, when I try submitting data to my database via my php webpage it won't go through. The same happens when I try to display info from my database to a webpage. Seeing as it is in fact connecting to the database, I'm not sure what the issue is. Any help is appreciated, try to dumb it down for me as much as possible when you answer. Also, I have triple-checked my database name and table names to make sure they match up with my coding. Here's my code:
Connection to database:
<?php
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PSWD', '');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'art database');
$dbcon = mysqli_connect(DB_HOST, DB_USER, DB_PSWD, DB_NAME);
?>
My form to insert data to my database:
<?php
if (isset($_POST['submitted'])) {
include('connect-mysql.php');
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$sqlinsert = "INSERT INTO users (first name, last name) VALUES ('$fname','$lname')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} //end of nested if
$newrecord = "1 record added to the database";
} // end of the main if statement
?>
<html>
<head>
<title>Insert Data into DB</title>
</head>
<body>
<hl>Insert Data into DB</hl>
<form method="post" action="insert-data.php">
<input type="hidden" name="submitted" value="true"/>
<fieldset>
<legend>New People</legend>
<label>First Name:<input type="text" name="fname" /></label>
<label>Last Name:<input type="text" name="lname" /></label>
</fieldset>
<br />
<input type="submit" value="add new person" />
</form>
<?php
echo $newrecord;
?>
</body>
</html>
The reason it's not working is because you have spaces in your columns/query.
INSERT INTO users (first name, last name)
wrap them in backticks like this:
INSERT INTO users (`first name`, `last name`)
It is not recommended to use spaces in column names or tables.
Try and use underscores instead, or remove the spaces and make the appropriate changes to your columns in your DB also, if you do.
You should also consider using:
('" . $fname . "','" . $lname . "')
instead of ('$fname','$lname')
I'm also questioning this => DEFINE ('DB_NAME', 'art database');
There is a space in between art and database. If that is the case and is in fact the name you've given your DB, do rename it to art_database and use DEFINE ('DB_NAME', 'art_database'); instead.
And do use the following for added protection:
$fname = mysqli_real_escape_string($dbcon,trim($_POST['fname']));
$lname = mysqli_real_escape_string($dbcon,trim($_POST['lname']));
Interesting article to read on protection:
How can I prevent SQL injection in PHP?
EDIT: (options)
OPTION 1, in 2 files:
First, rename your columns to firstname and lastname and use the following code and naming your file insert-data.php
DB query file (insert-data.php)
<?php
if (isset($_POST['submit'])) {
include('connect-mysql.php');
$fname = mysqli_real_escape_string($dbcon,trim($_POST['fname']));
$lname = mysqli_real_escape_string($dbcon,trim($_POST['lname']));
$sqlinsert = "INSERT INTO `users` (firstname, lastname) VALUES ('" . $fname . "','" . $lname . "')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} //end of nested if
echo "1 record added to the database";
} // end of the main if statement
?>
Then in a seperate file, your HTML form; name it db_form.php for example:
HTML form (db_form.php)
<html>
<head>
<title>Insert Data into DB</title>
</head>
<body>
<hl>Insert Data into DB</hl>
<form method="post" action="insert-data.php">
<input type="hidden" name="submitted" value="true"/>
<fieldset>
<legend>New People</legend>
<label>First Name:<input type="text" name="fname" /></label>
<label>Last Name:<input type="text" name="lname" /></label>
</fieldset>
<br />
<input type="submit" name="submit" value="add new person" />
</form>
</body>
</html>
NEW EDIT - OPTION 2, all in one file:
Use this in one page, with nothing else added:
<?php
if (isset($_POST['submit'])) {
if(empty($_POST['fname'])) {
die("Fill in the first name field.");
}
if(empty($_POST['lname'])) {
die("Fill in the last name field.");
}
include('connect-mysql.php');
$fname = mysqli_real_escape_string($dbcon,trim($_POST['fname']));
$lname = mysqli_real_escape_string($dbcon,trim($_POST['lname']));
$sqlinsert = "INSERT INTO `users` (firstname, lastname) VALUES ('" . $fname . "','" . $lname . "')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} //end of nested if
echo "1 record added to the database";
} // end of the main if statement
?>
<html>
<head>
<title>Insert Data into DB</title>
</head>
<body>
<hl>Insert Data into DB</hl>
<form method="post" action="">
<fieldset>
<legend>New People</legend>
<label>First Name:<input type="text" name="fname" /></label>
<label>Last Name:<input type="text" name="lname" /></label>
</fieldset>
<br />
<input type="submit" name="submit" value="add new person" />
</form>
<?php
echo $newrecord;
?>
</body>
</html>
I have made some changes, which is working fine for me
Where i can ignore if data is already in database
You Can try this to
<?php
if (isset($_POST['submit'])) {
include('db.inc.php');
$fname = mysqli_real_escape_string($dbcon,trim($_POST['fname']));
$lname = mysqli_real_escape_string($dbcon,trim($_POST['lname']));
// $sqlinsert = "INSERT INTO `user` (firstname, lastname) VALUES ('" . $fname . "','" . $lname . "')";
$sqlinsert = "INSERT IGNORE INTO `dbname`.`user` (`fname`, `lname`) VALUES ( '$fname', '$lname')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} //end of nested if
echo "1 record added to the database";
} // end of the main if statement
?>
Where db.inc.php is a different file in same directory for connecting database
<?php
$dbcon=mysqli_connect("localhost","dbuser","yourpassword","dbname");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
I made a form to insert and modify categories in my project.
when i hit "submit" i get the record submitted into the database but it appears empty !
and if i go to the databse field and write the text myself it will appear good in MySQL and and "????" in the browser !
here is the code i wrote:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<?php
$con = mysql_connect("localhost","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb", $con);
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
('$_POST[name]','$_POST[parent_id]','$_POST[description]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
<form action="ins.php" method="post">
category: <input type="text" name="name" /><br><br>
parent: <input type="text" name="parent_id" /><br><br>
description: <input type="text" name="description" /><br><br>
<input type="submit" />
</form>
</body>
</html>
You have to quote (using ") around your index name in your SQL request because $_POST is an array:
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
('".$_POST["name"]."','".$_POST["parent_id"]."','".$_POST["description"]."')";
But generally speaking please dont trust directly what's user are posting to your script to avoid SQL Injections. You can use mysqli::query which is way better and safer :
Mysqli
First sanitize your user input.
If you after that want to use the values from the array without all the concatenation everyone else mentions use {} around array accessors.
$sql="INSERT INTO categories (name, parent_id, description)
VALUES
('{$_POST['name']}','{$_POST['parent_id']}','{$_POST['description']}')";
To clean for example $_POST do something like this is a good start. This is a bit of my older code. As others have written use mysqli instead
function clean_array($t_array)
{
foreach($t_array as $key=>$value)
$array[$key] = mysql_real_escape_string( trim($value) );
return $t_array;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<?php
if ($_POST['action']=="doformpost") {
//only do DB insert if form is actually posted
$con = mysql_connect("localhost","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb", $con);
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
('".$_POST['name']."','".$_POST['parent_id']."','".$_POST['description']."')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
}
?>
<form action="ins.php" method="post">
<input type="hidden" name="action" id="action" value="doformpost" />
category: <input type="text" name="name" /><br><br>
parent: <input type="text" name="parent_id" /><br><br>
description: <input type="text" name="description" /><br><br>
<input type="submit" />
</form>
</body>
</html>
Try using double quotes in your statement like this:
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
("'.$_POST['name'].'","'.$_POST['parent_id'].'","'.$_POST['description'].'")";
lots of issues here.
$_POST[name] should be $_POST['name']
your query will run even if the form is not submitted.
you are using deprecated mysql_* functions. Use PDO or mysqli
Your code is vulnerable to sql injection
With all that out, here's what you need to do.
Just to verify that the form is submitted, use
if( !empty($_POST['name']) &&
!empty($_POST['parent_id']) &&
!empty($_POST['description']) )
(use isset if empty value is allowed.)
Then run the query.
In PDO, the code will look like this ->
<?php
// configuration
$dbtype = "mysql";
$dbhost = "localhost";
$dbname = "mydb";
$dbuser = "user";
$dbpass = "pass";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// query
$sql = "INSERT INTO categories (name, parent_id,description)
VALUES
(?,?,?)";
$q = $conn->prepare($sql);
$q->execute(array($_POST[name],$_POST[parent_id],$_POST[description]));
?>
This is just a start. you can use try and catch block to catch exceptions.
Before running query, check if form is submitted by !empty() or isset() as described above.
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
("'.$_POST['name'].'","'.$_POST['parent_id'].'","'.$_POST['description'].'")";
Please provide quotes while inserting values in database
I found that if you forget the simply html attribute in the <form> for METHOD="POST"... you will get blank data in your database despite all else working fine.
ie.. <form action="file.php" method=POST>
use this statement for your code
if( isset($_POST['name']) && isset($_POST['parent_id']) && isset($_POST['description']) )
//your insert query
Don't forgot about safety!
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
('".mysql_real_escape_string($_POST['name'])."','".intval($_POST['parent_id'])."','".mysql_real_escape_string($_POST['description'])."')";
And i think a problem with encodings.
launch query before you inserting a data:
$sql = 'set names `utf-8`'; (for example)
Use Below insert query to insert data , i m sure it will definitely help you.
$sql="INSERT INTO categories (name,parent_id,description)
VALUES
('".$_POST['name']."','".$_POST['parent_id']."','".$_POST['description']."')";
Try this
<?php
if(isset($_POST['submit'])) {
$con = mysql_connect("localhost","user","pass");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb", $con);
$sql="INSERT INTO categories (name, parent_id,description) VALUES
('".$_POST['name']."','".$_POST['parent_id']."','".$_POST['description']."')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
} else {
echo "1 record added";
}
mysql_close($con);
}
?>
<html>
<body>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
category: <input type="text" name="name" /><br><br>
parent: <input type="text" name="parent_id" /><br><br>
description: <input type="text" name="description" /><br><br>
<input type="submit"name="submit" value="Submit" />
</form>
</body>
</html>
Me too faced the same problem.
Proceed your insert query like this, this helped me.
$email_id = $_POST['email_id'];
$device_id = $_POST['device_id'];
***For My Sqli***
if(!empty($email_id ))
{
$result_insert = mysqli_query($db_conn,"INSERT INTO tableName (user_email, user_device_id,last_updated_by) VALUES('".$email_id."', '".$device_id."', '".$email_id."') ");
if(mysqli_affected_rows($db_conn)>0)
{
$response["success"] = 1;
$response["message"] = "Successfully Inserted";
}
else
{
$response["success"] = 0;
$response["message"] = "Problem in Inserting";
}
}
else
{
$response["success"] = 4;
$response["message"] = "Email id cannot be Blank";
}
}
///////////////////////////////////////////////////////////////////////////////
**For My Sql**
if(!empty($email_id ))
{
$result_insert = mysql_query("INSERT INTO tableName (user_email, user_device_id,last_updated_by) VALUES('".$email_id."', '".$device_id."', '".$email_id."') ");
if(mysql_affected_rows()>0)
{
$response["success"] = 1;
$response["message"] = "Successfully Inserted";
}
else
{
$response["success"] = 0;
$response["message"] = "Problem in Inserting";
}
}
else
{
$response["success"] = 4;
$response["message"] = "Email id cannot be Blank";
}
}
NOTE : here i have checked only for email.
I need to redirect submissions so that users aren't taken to a blank screen.
Here's the code for my form::
<form action="giveaway_execute.php" method="post">
First Name:
<input type="text" name="firstname" /><br />
Last Name:
<input type="text" name="lastname" /><br />
etc...
...
...
<p><input type="submit" value="Submit"/>
</p>
</form>
and here's the php for 'giveaway_execute.php' which interacts with the mySQL db (everything submits; removed password and db name for security)::
<?php
define ( 'DB_NAME','xxxx');
define ( 'DB_USER','xxxx');
define ( 'DB_PASSWORD','xxxx');
define ( 'DB_HOST','localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!link) {
die('Could not connect: ' .mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}
$value1 = $_POST['firstname'];
$value2 = $_POST['lastname'];
$value3 = $_POST['phone'];
$value4 = $_POST['street'];
$value5 = $_POST['city'];
$value6 = $_POST['state'];
$value7 = $_POST['zip'];
$value8 = $_POST['email'];
$value9 = $_POST['weddingdate'];
$sql = "INSERT INTO entrants (firstname, lastname, phone, street, city, state, zip, email, weddingdate) VALUES ('$value1', '$value2', '$value3', '$value4', '$value5', '$value6', '$value7', '$value8', '$value9')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
mysql_close();
?>
I've tried redirects on the PHP file but nothing is working. Any suggestions would be greatly appreciated.
Thank you.
You can just include another page after you're done with your database operations, or as suggested you can use a header call but be sure to use an absolute url.
Also worth noting your code is highly vulnerable to SQL injection, and it doesn't do any validation.
It's a good idea to use isset on your fields to avoid getting notices and SQL errors if fields aren't set.
Finally, it's recommended to use a library such as PDO or mysqli over the older mysql_* extension.
try
header('location:page2.php');
at the end of the file.
Replace page2.php with the actual page you want to send them to
// process.php
$db = new PDO('mysql:host=localhost;dbname=test', 'root', 'root');
if(isset($_POST['value'])){
error_log(print_r($_POST,1),0);
$db->query('INSERT INTO test (id, value) VALUES (NULL, "'.$_POST['value'].'")');
header('Location: http://google.com');
exit();
}
else {
echo "$_POST is not set.";
}
// form.php
<form action="process.php" method="post">
<input type="text" name="value">
<input type="submit" id="submit-btn" value="Submit">
</form>
Try something simpler and build from there. Also read this: http://www.php.net/manual/en/pdo.prepared-statements.php
I am trying to submit the page to itself but some reason the following code is not working. Also How can I get the table1 primary key ID back after inserting the data successfully? I have a child table which needs this ID. Thanks for any suggestions.
<?php
include('db_login.php');
$connection = mysql_connect( $db_host, $db_username, $db_password );
if (!$connection){
die ("Could not connect to the database: <br />". mysql_error());
}
// Select the database
$db_select=mysql_select_db($db_database);
if (!$db_select){
die ("Could not select the database: <br />". mysql_error());
if ($_POST['Submit'])
{
$first = $_POST["first"];
$first = mysql_real_escape_string(get_magic_quotes_gpc() ? stripslashes($first): $first);
$last = $_POST["last"];
$last = mysql_real_escape_string(get_magic_quotes_gpc() ? stripslashes($last): $last);
$insertsql = "INSERT INTO table1(FirstName,LastName) VALUES ('".$first."', '" .$last. "')";
$result1 = mysql_query($insertsql) or die(mysql_error());
}
?>
<form name="hotlineForm" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>"
method="post">
<input id="first" type="text">
<input id="last" type="text">
<input type="submit" value="Submit"></form></body>
What part isn't working on the post back? Are you not entering your if statement?
To get the ID of the last insert use the following after your $result1 = mysql_query(...):
$primary_id = mysql_insert_id()
http://php.net/manual/en/function.mysql-insert-id.php
Change your form inputs to include name attributes. Without them, your $_POST will be empty.
<input name='first' id="first" type="text">
<input name='last' id="last" type="text">
<input name='Submit' type="submit" value="Submit">
As mentioned in the comments, get_magic_quotes should not be used. You've correctly called mysql_real_escape_string() on your inputs already.
Following your insert, get the id from mysql_insert_id():
$result1 = mysql_query($insertsql) or die(mysql_error());
$new_id = myqsl_insert_id();
if ($_POST['Submit'])
I don't see a form element with this name.
try:
if (isset($_POST['first']) && isset($_POST['last']))
For getting inserted ID you can use:
mysql_insert_id();
You are missing a closing } here:
if (!$db_select){
die ("Could not select the database: <br />". mysql_error());
} <<---- Close your if statement here.
if ($_POST['Submit'])
Currently the code that does the actual work only gets called if the DB cannot be selected.
Not very useful.
This is why proper indentation is important.
If you are religious about your indentation, you will spot these kind of errors instantly.
Use a name for the input field and check if it was sents not the submit