Kai Jones Kai Jones - 2 years ago 48
MySQL Question

Store query result as php variable

Before you spam as duplicate I have read through around 20-30 posts on this site about how to do this as well as others and I can't get mine to work so thats why i am asking the question.

I have the following code:

$lookupID = "SELECT ID FROM dungeon WHERE Name = '$loc'";
$result = mysqli_query($connection, $lookupID);
$row = mysqli_fetch_row($result);
$locID = $row['ID'];

$query = "INSERT INTO boss (ID, Name, Type, Location, LocationID, Difficulty) VALUES ('0', '$boss', '$type', '$loc', '$locID', '$diff')";

The purpose for the lookupID is to based upon the $loc value lookup in the other table what the locID value associated with it is and set $locID to that number. Currently when I run the query I get the following:

Error: INSERT INTO boss (ID, Name, Type, Location, LocationID, Difficulty) VALUES ('0', 'Godzilla', 'Lizard', 'Black Rock Hold', '', '4')

With the locID variable giving no value and so causing the error. Im sure its something simple and stupid I am doing but I am new to php and mysql so I hope you forgive me.

Answer Source

The mysqli_fetch_row function returns the array with enumerated keys, so you should use

$locID = $row[0];

If you want, you can use mysqli_fetch_assoc to get the row with associative keys instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download