我使用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/><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>";
}
}
?>
我错了,请帮助数据不插入数据库
答案 0 :(得分:1)
首先使用的是哪个版本的php,因为较新版本的php不支持mysql_connect()
。
如果你的php版本不支持这个功能,你应该在提交时出错。
所以我建议你用mysqli_xxx替换mysql_xxx(正如你在mysql_connect看到的那样)
替换这两行
mysql_connect("localhost","root","");
mysql_select_db("coupons");
使用这些代码行
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,"coupons");
并且
如果条件使用此mysqli_xxx()为
,则更新if(mysqli_query($query))
有关详情,请参阅mysqli_connect
答案 1 :(得分:0)
你可以这样做,为你的PHP代码
<?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;
?>
答案 2 :(得分:0)