我需要比较表中的2个不同列:tbl_Try(country,name)。如果有2个具有相同值的coloumns什么都不做。如果这两个列的相同值没有相同的插入。
这是与数据库的连接:
<?php
require_once("menu.php");
require_once("function.php");
?>
这是主要代码(阅读试图理解的评论)
<?php
$conn = ConnectToSql();
$query= "Select * FROM tbl_countries";
$result = mysqli_query($conn, $query)
or die("Error in query: ". mysqli_error($conn));
$choose = '';
while ($row = mysqli_fetch_assoc($result))
{
$choose .= '<option value = "'.$row['name'].'">'.$row['name'].'</option>';
}
?>
<div class="form-group">
<label class="control-label col-sm-2" for="Country">Choose a country:</label>
<div class="col-sm-5">
<select class="form-control" name ="reg_country" >
<option></option>
<?php echo $choose;?></select>
</div>
</div>
<br>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-10">
<button type="submit" name="submit" class="btn btn-default">Submit</button>
</div>
</div>
<?php
if(isset($_POST['submit']))
{
$country = $_POST['reg_country'];
$_SESSION['country'] = $country;
$query2 = "SELECT name,id FROM tbl_flowertypes ";
$result2 = mysqli_query($conn, $query2) or die("Error in query: ". mysqli_error($conn));
$result2_rows = mysqli_num_rows($result2);
//this code is not working. Need to count the 2 columns (name AND country)
// if in tbl_try there is already country:italy name:12 red roses. DO NOTHING if there is no data the same
// insert data
$query3 = "SELECT count(*) FROM tbl_try WHERE name='$_SESSION[flower_type_name]' AND country ='$_SESSION[country]' ";
$result3 = mysqli_query($conn, $query3) or die("Error in query: ". mysqli_error($conn));
$result3_rows = mysqli_num_rows($result3);
// loop counting how many record are in table flowertype and loop to insert data in tbl_try (this code is working fine)
for($i = 1; $i <= $result2_rows;$i++)
{
while($row = mysqli_fetch_assoc($result2))
{
$_SESSION['flower_type_name'] = $row['name'];
// this is the insertion of the data
$inserting = "INSERT INTO tbl_try(name,country) VALUES ('$row[name]','$_SESSION[country]')";
$result3 = mysqli_query($conn, $inserting) or die("Error in query: ". mysqli_error($conn));
}
}
}
结果需要:
数据库需要插入一次。只要表中没有相同的栏目。如果有相同的数据,那就没有了。
我需要通过显示包含一些记录的表来完成此代码,但我知道如何做到这一点。
任何建议?
答案 0 :(得分:1)
最好的方法是将这两列的唯一定义添加到DB中,如下所示:
ALTER TABLE tbl_Try
ADD UNIQUE (name, country)
然后你可以检查DB中的结果代码,并根据你现在的结果代码,如果因为大小写存储到DB,那么DB中已存在相同的名称和国家。