0

我有一个带有 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){

说他可以做插入的动作

请帮我

4

1 回答 1

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

我已在您的 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);
?> 
于 2013-02-04T00:18:58.137 回答