zan
zan

Reputation: 355

insert data into a table using html form

I have a html form on the main page to insert data into a mysql table.

<form action ="http://127.0.0.1/insertdata.php" name="salesRecords" method="post">
Client name = <input type="text" name="client" value="" /> </br>
Date of sale = <input type="text" name="date" value="" /> (YYYY-MM-DD) </br>
Value of sale = <input type="text" name="amount" value="" /> (DDDD.DD) </br>
<input type="submit" value="Submit" onclick="return validateForm();"/>

I use the following code in receiveform.php file to display the the table data and it works correctly.

<?php

//create connection
$con = mysql_connect("localhost", "admin", "password")
//query database and write out results
$sql = 'select * from sales';
$result = mysql_query($sql, $con);
echo "<table>";
while($row = mysql_fetch_array($result))
{
    echo "<tr><td>"
    echo $row['client'];
    echo "</td><td>";
    echo $row['date'];
    echo "</td><td>";
    echo $row['amount'];
    echo "</td></tr>";
}
echo "</table>";
?>

I use the following code in an insertdata.php file. However, it doesn't work properly. Can anyone help?

/Form values
$_POST['client'];
$_POST['date'];
$_POST['amount'];

//insert data into table
$insertData = 'insert into sales (client, date, amount) values
    ('$_POST[client]', '$_POST[date]', '$_POST[amount]')';

$result = mysql_query($insertData, $con);
if($result)
{
    echo 'Data inserted successfully';
}else{
    echo 'Data insertion failed: ' .mysql_error();
}
?>

Upvotes: 0

Views: 4094

Answers (3)

user7789076
user7789076

Reputation: 798

$con = mysql_connect("localhost", "admin", "password");

After this line add

$selected = mysql_select_db("db",$con) ;

Thanks

Upvotes: -1

Stuart Miller
Stuart Miller

Reputation: 657

The problem is with how you are have the $_POST array key, they should have quotes around them but this can cause problems with inputting into mysql in this way. Ram Sharma's answer will work but would suggest using PDO instead for working with databases.

Upvotes: 1

Ram Sharma
Ram Sharma

Reputation: 8809

zan, modify your query like this

$insertData = 'insert into sales (client, date, amount) values ("'.$_POST['client'].'", "'.$_POST['date'].'", "'.$_POST['amount'].'")';

Upvotes: 1

Related Questions