jeudi 7 mai 2015

Can you use if else statements while inserting data into mysql?

I've been trying to figure this out for awhile now. I've looked online and can't seem to find anything on this specific topic. Any help would be great.

I have a database where you can store a lead or a customer. Instead of having two tables, I want them in the same table. So on the form - you choose "customer" or "lead" and then it shows the next appropriate field to put in the business name. It should go in the database as:

customer chickens Inc.

or

lead chickens Inc.

Here is the code I've made. Am I doing something wrong?

    <?php
$servername = "localhost";
$username = "user";
$password = "pass!1";
$dbname = "data";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
//Look at what type of data we are getting and then set the correct variables.
if ($_POST['type'] == "customer") {
    $datatype = $_POST['type'];
    $company = $_POST['company_name'];
} else {
    $datatype = $_POST['type'];
    $company = $_POST['lead_name'];
}
//Process the SQL Statement
$sql = "INSERT INTO customers (datatype, company)
VALUES ('$datatype', '$company')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

Aucun commentaire:

Enregistrer un commentaire