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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.