0

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();
}
?>
0

3 Answers 3

1

zan, modify your query like this

$insertData = 'insert into sales (client, date, amount) values ("'.$_POST['client'].'", "'.$_POST['date'].'", "'.$_POST['amount'].'")';
Sign up to request clarification or add additional context in comments.

2 Comments

sql injection alert :)
indeed, mysql_ is deprecated! use mysqli or PDO instead!
1

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.

Comments

-1

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

After this line add

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

Thanks

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.