简体   繁体   English

MySQL PHP:如果不存在则插入,如果存在则查询第二个表,如果存在则重定向

[英]MySQL PHP: Insert if not exists, if exists query second table, if exists redirect

I have a form that submits to a database.我有一个提交到数据库的表单。 Before it is submitted, a search is done in a table for a value and if not found insert.在提交之前,会在表中搜索一个值,如果没有找到就插入。 (This part works in below code) If found, search a second table for the same value and if not found insert (Not working below) if found there as well, direct the user to a particular page. (这部分在下面的代码中工作)如果找到,在第二个表中搜索相同的值,如果没有找到插入(下面不工作),如果在那里也找到,将用户引导到特定页面。 I appreciate any help.我很感激任何帮助。 Please keep in mind I'm somewhat of a 'newbie'.请记住,我有点像“新手”。

<?php
$objConnect = mysql_connect("localhost","****","****") or die("Error 
Connect to Database");
$objDB = mysql_select_db("****");
$strSQL = "SELECT * FROM USERS WHERE Business_Name = '".$_POST["bname"]."' 
";
$objQuery = mysql_query($strSQL);
$objResult = mysql_fetch_array($objQuery);
if($objResult)
{
        echo "<b>Business</b> name exists we will redirect";
}
else
{

$strSQL = "";
$strSQL = "INSERT INTO DATA";
$strSQL .="(Business_Name)";
$strSQL .="VALUES ";
$strSQL .="('".$_POST["bname"]."') ";
$strSQL .="WHERE ('".$_POST["bname"]."') NOT EXISTS";
$objQuery = mysql_query($strSQL);
$objResult = mysql_fetch_array($objQuery);
if($objQuery)
{
    echo "We will direct to pre-filled form";
}
else
{
    echo "Name already there. We will direct to pre-filled form";
}
}
mysql_close($objConnect);
?>

Expected result: Search table if not found insert.预期结果:如果未找到插入则搜索表。 If found search second table and attempt to insert.如果找到搜索第二个表并尝试插入。 If found there to, redirect to webpage.如果在那里找到,重定向到网页。

Actual Results: First step works fine.实际结果:第一步工作正常。 If not found in first table it inserts.如果在第一个表中找不到它会插入。 If found always shows "Name already there. We will direct to pre-filled form" (see code) so it's not attempting to insert.如果找到总是显示“名称已经存在。我们将直接进入预先填写的表格”(参见代码),因此它不会尝试插入。 This last echo that contains "Name already there. We will direct to pre-filled form" was originally an error echo.最后一个包含“名称已经存在。我们将定向到预先填写的表格”的回声最初是一个错误回声。

You can use UNIQUE index value on database example您可以在数据库示例中使用唯一索引值

CREATE TABLE data (
`id` INT NOT NULL AUTO_INCREMENT,
`Business_Name` VARCHAR(200) NOT NULL,
`Address` VARCHAR(200) NOT NULL,
 PRIMARY KEY (`id`), UNIQUE (`Business_Name`)) ENGINE = InnoDB;

or you can try it或者你可以试试

INSERT INTO data (Business_Name,Address)
SELECT * FROM (SELECT 'YOOLTECH','KM4' ) AS tmp    
WHERE NOT EXISTS (SELECT Business_Name FROM data WHERE Business_Name = 'YOOLTECH') LIMIT 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM