gpt4 book ai didi

mysql - 插入之前检查mysql表数据

转载 作者:行者123 更新时间:2023-11-29 13:45:34 24 4
gpt4 key购买 nike

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

我制作了一个包含 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);


?>

最佳答案

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


?>

关于mysql - 插入之前检查mysql表数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17468117/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com