0

I have created a form that I link with PHP. I need the foreign key number to be the same with id of another table.

There is no problem of extracting data from the form and I test this on Error Session. Also no problem with foreign key connection on the database.

However, Select statement does not work. Is it about syntax in the insert statement ? Thanks.

$Connection=mysqli_connect('localhost','root','','databasename'); 

$Query="INSERT INTO musteri_ekle(tarih,musteri_ismi,urun_id) 
VALUES('$Now','$Musteri_ismi',(SELECT urun_id from urun_ekle WHERE urun_ismi='$Urun_ismi'))";

$Execute=mysqli_query($Connection,$Query);

        if($Execute){

            $_SESSION["SuccessMessage"]= "Müşteri Eklendi.";
            redirect_to("musteri_ekle.php");


} else {

     $_SESSION["ErrorMessage"]= $Urun_ismi." -- ".$Musteri_ismi;
     redirect_to("musteri_ekle.php");
        }
}

2 Answers 2

3

You can not use select inside values.

Change your code from

$Query="INSERT INTO musteri_ekle(tarih,musteri_ismi,urun_id) 
VALUES('$Now','$Musteri_ismi',(SELECT urun_id from urun_ekle WHERE urun_ismi='$Urun_ismi'))";

to below:

$Query="INSERT INTO musteri_ekle(tarih,musteri_ismi,urun_id) 
SELECT '$Now','$Musteri_ismi',urun_id from urun_ekle WHERE urun_ismi='$Urun_ismi'";
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfect ! Thanks !!
1

Alternate syntax

$Query="INSERT INTO musteri_ekle SET tarih = '$Now' ,musteri_ismi = '$Musteri_ismi' ,urun_id = (SELECT urun_id from urun_ekle WHERE urun_ismi='$Urun_ismi')";

This type of problem is discussed here MySQL INSERT INTO ... VALUES and SELECT

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.