简体   繁体   中英

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

赞,像这样修改您的查询

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

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.

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

After this line add

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

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM