在插入之前检查mysql表数据

时间:2013-07-04 10:36:34

标签: mysql duplicate-data

我需要知道在php脚本INSERT INTO该表之前是否可以查询和检查数据库表数据?

我已经制作了一个带有2个字段和提交按钮(POST)的html,我也没有遇到将数据添加到数据库表并获得结果的问题,但我有重复项,我不想拥有它...我希望脚本检查我的数据,输入数据,如果没有重复,则添加它。

请协助。

谢谢

代码

<?php


$con=mysqli_connect("localhost","root","Opera1","railway");


if(mysqli_connect_errno())
{
echo "Failed to connect to MySQL: ", mysqli_connect_error;
}

$data1 = $_POST['data1'];
$data2 = $_POST['data2'];



$sql="replace into pipe (data1, data2) 
values ('$data1','$data2')";



if(!mysqli_query($con,$sql))
{
die('Error : ' . mysqli_error($con));
}


echo "Record to Registraton added";

$result = mysqli_query($con,"SELECT * FROM pipe");

echo "<table border='1'>
<tr>
<th>Data1</th>
<th>Data2</th>
</tr>";

while($row = mysqli_fetch_array($result))
  {
 echo "<tr>";
  echo "<td>" . $row['data1'] . "</td>";
  echo "<td>" . $row['data2'] . "</td>";
  echo "</tr>";
  }
echo "</table><br><br>";


mysqli_close($con);


?>

3 个答案:

答案 0 :(得分:1)

       <?php


    $con=mysqli_connect("localhost","root","Opera1","railway");


    if(mysqli_connect_errno())
    {
    echo "Failed to connect to MySQL: ", mysqli_connect_error;
    }

    $data1 = $_POST['data1'];
    $data2 = $_POST['data2'];

    $sql1="select * from pipe";
    $q1=mysql_query($con, $sql1);
    $t=0;
    while($row1=mysql_fetch_array($q1))
    {

    if($row1['data1']== '$data1' || $row1['data2']=='$data2')
    {
    $t=1;
    break;
    }
    }
    if($t==1)
     { 
       echo "Duplicate Entry!";
     }
    else
    {

    $sql="replace into pipe (data1, data2) 
    values ('$data1','$data2')";



    if(!mysqli_query($con,$sql))
    {
    die('Error : ' . mysqli_error($con));
    }


    echo "Record to Registraton added";

    $result = mysqli_query($con,"SELECT * FROM pipe");

    echo "<table border='1'>
    <tr>
    <th>Data1</th>
    <th>Data2</th>
    </tr>";

    while($row = mysqli_fetch_array($result))
      {
     echo "<tr>";
      echo "<td>" . $row['data1'] . "</td>";
      echo "<td>" . $row['data2'] . "</td>";
      echo "</tr>";
      }
    echo "</table><br><br>";

    }

    mysqli_close($con);


    ?>

答案 1 :(得分:0)

如果你不想处理重复的情况,只需使用INSERT IGNORE INTO而不是INSERT INTO。它将完全像INSERT一样工作,但如果有重复项则不会失败。

答案 2 :(得分:0)

如果要消除1个笔划中的重复记录,可以使用mysql中提供的REPLACE命令(参考:http://dev.mysql.com/doc/refman/5.0/en/replace.html)。如果已存在具有相同值的行,则它将删除现有行并添加新的其他内容将插入新记录。

您甚至可以在Insert into a MySQL table or update if exists

查找其他选项