Php 为什么不将数据插入数据库?
我使用php在mysql数据库中插入数据。我是php和mysql新手,请帮助我Php 为什么不将数据插入数据库?,php,Php,我使用php在mysql数据库中插入数据。我是php和mysql新手,请帮助我 <html> <head> <title>create menu</title> </head> <h1 align="center">create menu</h1> <h2 align="center">Dont create more than 7 menu</h2><br/><
<html>
<head>
<title>create menu</title>
</head>
<h1 align="center">create menu</h1>
<h2 align="center">Dont create more than 7 menu</h2><br/><br/>
<form method="post">
<table border="2px" width="500px">
<tr>
<th colspan="2" align="center">create menu</th>
</tr>
<tr>
<td align="right">menu name</td>
<td><input type="text" name="menu"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="submit" value="create"></td>
</tr>
</table>
</form>
<?php
mysql_connect("localhost","root","");
mysql_select_db("coupons");
if(isset($_POST['submit'])){
$menu=$_POST['menu'];
$query = "insert into menu(item) values ('$menu')";
if(mysql_query($query)){
echo "<h1 align='center'>DATA INSERTED</h1>";
}
else{
echo "<h1>data not inserted</h1>";
}
}
?>
创建菜单
创建菜单
不要创建超过7个菜单
创建菜单
菜单名
首先,您使用的是哪个版本的php,因为较新版本的php不支持mysql\u connect()
。
如果您的php版本不支持此函数,则在提交时会出现错误
因此,我建议您用mysqli_xxx替换mysql_xxx(如您在这里看到的)
更换这两条线路
mysql_connect("localhost","root","");
mysql_select_db("coupons");
用这些代码行
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,"coupons");
及
使用此mysqli_xxx()更新if条件为
有关更多详细信息,请阅读您可以这样做的php代码
您的代码运行得非常好。我在我的系统上试过了。查看屏幕截图-
HTML表单提交结果-
数据库中的值-
系统上可能出现的错误-
- MySql没有运行
- 数据库名称不正确
- 您尚未提供密码
首先,您应该看看sql注入,您的代码不安全。如果您问我们为什么,mysql.*
函数在PHP5中被弃用,在PHP7中被删除。升级代码并开始使用准备好的语句。mysql已弃用=>使用pdo或mysqli
if(mysqli_query($query))
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "coupons";
try{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query=$conn->prepare("INSERT INTO menu( item) VALUES( :menu)");
$query->bindParam(':menu',$menu);
$menu=$_POST['menu'];
$query->execute();
echo "<h1 align='center'>DATA INSERTED</h1>";
}
catch(PDOException $e)
{
// roll back the transaction if something failed
$conn->rollback();
echo "Error: " . $e->getMessage();
echo "<h1>data not inserted</h1>";
}
$conn = null;
?>