简体   繁体   English

使用html表单将数据插入表中

[英]insert data into a table using html form

I have a html form on the main page to insert data into a mysql table. 我在主页上有一个html表单,可将​​数据插入到mysql表中。

<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. 我在receiveform.php文件中使用以下代码来显示表数据,并且它可以正常工作。

<?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. 我在insertdata.php文件中使用以下代码。 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. 问题在于如何使用$ _POST数组键,它们周围应该带有引号,但这会导致以这种方式输入mysql时出现问题。 Ram Sharma's answer will work but would suggest using PDO instead for working with databases. Ram Sharma的答案会起作用,但建议使用PDO代替数据库。

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

After this line add 在此行之后添加

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

Thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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