我有一个带有mysql的php,如果没有相同的信息,会将一些数据插入数据库
<?php
$id=$_POST['id'];
$guildname=$_POST['guildname'];
$level=$_POST['level'];
$score=$_POST['score'];
$guildmaster=$_POST['guildmaster'];
$con = mysql_connect("localhost", "root", "");
if (!$con)
{die('Could not connect to mysql: ' . mysql_error());}
$mydb = mysql_select_db("gunbound");
if (!$mydb)
{die('Could not connect to database: ' . mysql_error());}
$dup = mysql_query("SELECT Id FROM guildrequest WHERE Id='".$_POST['id']."'");
if(mysql_num_rows($dup) >= 1){
echo '<b>You have already ask for guild request.</b>';
}
else
{
$dup2 = mysql_query("INSERT INTO guildrequest VALUES ('$id', '$guildname', '$level', '$score', '$guildmaster')");
}
Print "<center>You have requested to join the guild.</center>";
mysql_close($con);
?>
但如果没有等于
的记录,则不会将记录添加到数据库中也不执行此操作:
$dup2 = mysql_query("INSERT INTO guildrequest VALUES ('$id', '$guildname', '$level', '$score', '$guildmaster')");
即使代码:
if(mysql_num_rows($dup) >= 1){
说他可以做插入
的动作请帮帮我
答案 0 :(得分:1)
试试这个:
<?php
$id=$_POST['id'];
$guildname=$_POST['guildname'];
$level=$_POST['level'];
$score=$_POST['score'];
$guildmaster=$_POST['guildmaster'];
$con = mysql_connect("localhost", "root", "");
if (!$con)
{die('Could not connect to mysql: ' . mysql_error());}
$mydb = mysql_select_db("gunbound");
if (!$mydb)
{die('Could not connect to database: ' . mysql_error());}
$dup = mysql_query("SELECT Id FROM guildrequest WHERE Id='".$_POST['id']."'");
if(mysql_num_rows($dup) >= 1){
echo '<b>You have already ask for guild request.</b>';
}
else
{
$dup2 = mysql_query("INSERT INTO guildrequest VALUES ('$id', '$guildname', '$level', '$score', '$guildmaster')");
return $dup2;
}
Print "<center>You have requested to join the guild.</center>";
mysql_close($con);
?>
我已将return添加到您的else语句中。我将执行你的$ dub2变量。如果你想保留变量$ dub2,那么你可以在中间执行你的查询。另一种方法是使用mysql_execute()函数。
这将是MYSQLI的等价物:
<?php
$id=$_POST['id'];
$guildname=$_POST['guildname'];
$level=$_POST['level'];
$score=$_POST['score'];
$guildmaster=$_POST['guildmaster'];
$host = "hostname";
$user = "username";
$password = "password";
$database = "database";
$con = mysqli_connect($host, $user, $password, $database);
if (!$con)
{die('Could not connect to mysql: ' . mysql_error());}
$dup = "SELECT Id FROM guildrequest WHERE Id='".$_POST['id']."'";
mysqli_query($con, $dup);
if (!$dup)
{die('Could not connect to database: ' . mysql_error());}
if(mysqli_num_rows($dup) >= 1){
echo '<b>You have already ask for guild request.</b>';
}
else
{
$dup2 = "INSERT INTO guildrequest VALUES ('$id', '$guildname', '$level', '$score', '$guildmaster')";
mysqli_query($con, $dup2);
}
Print "<center>You have requested to join the guild.</center>";
mysqli_close($con);
?>