Search code examples
phpsqlselecttextsentence

How to store a variable from a SQL Query (PHP)


I want to Insert some data into a table and one of one I want to take it from another table.

For example :

I have 2 tables :

Clients(Client_ID,Name,etc);

Bookings(Book_ID,Client_ID(ForeignKey),Checkin,etc);

And I want to insert the Client_ID into Bookings table Where name = "john".

I think that I must store Client_ID from Clients in a variable $clientID, and when I insert into bookins will be

INSERT INTO bookings(Book_IT,Client_ID,Checkin) values ('1','$clientID','2015-02-20');

But is not working.

Can you tell how to store the Client_ID value in $clientID ?


Solution

  • Try this it will work :

    1.select client_id where name = "john"

    $sql = "SELECT Client_ID FROM clients WHERE Name = 'john'";
    $result = mysql_query($sql);
    $rs = mysql_fetch_array($result);
    
    $clientid = $rs['Client_ID'];
    

    Here, $clientid is the Client_ID of John.

    2.Insert the data in Bookings.

    INSERT INTO bookings(Book_IT,Client_ID,Checkin) values ('1','$clientid','2015-02-20');