0

I am trying to finish my question of the day script. I have a random number generator (external) which is inserted into a table daily. I take that number and pull the corresponding question from another table.

// Query 1
$query1 = "SELECT $field1 FROM $table1 WHERE id=1";
$result1 = mysqli_query($con1, $query1);

// Query 2
$query2 = "SELECT $field2 FROM $table2 WHERE QNum = $result1";
$result2 = mysqli_query($con2, $query2);

// Display question
while($row = mysqli_fetch_array($result2)) {
    echo $row['question'];
}

$result1 is pulling a random number, lets say its 9. When $result1 is used to pull the question, it doesn't work but when I replace $result1 with number 9, it works. I experimented with syntax and eventually figured it could be a problem with a string vice an integer.

I tried to cast it as an integer but it keeps assigning the value of $result1 to 1. I am at a loss. I don't understand if the string is a 9, how converting it to an integer would change its value.

I feel like I've tried everything after days of experimenting out there but I am sure it is something very simple. Please help.

2
  • Why not do it in a single query with a join? Commented Jul 31, 2014 at 4:13
  • You forgot to call mysqli_fetch_array on $result. It doesn't contain the value of the field, it contains a mysqli_result object. Commented Jul 31, 2014 at 4:15

2 Answers 2

2

You're right, it's something very simple. You need to fetch the row to get the value:

$row = mysqli_fetch_assoc($result1);
$qnum = $row[$field1];

$query2 = "SELECT $field2 FROM $table2 WHERE QNum = $qnum";

You seem to understand this in general, since you call mysql_fetch_array to get the results of the second query. Why should the first query be any different?

However, you can do all this in one query:

$query2 = "SELECT t2.$field2
           FROM $table1 t1
           JOIN $table2 t2 ON t1.$field1 = t2.QNum
           WHERE t1.id = 1";
Sign up to request clarification or add additional context in comments.

Comments

0

Have you checked whats returned in $result1 ??

it should be an object which cannot be used inside the second mysql query. First you have to get the value from that query by fetching the query.

$result1 = mysqli_query($con1, $query1);
$row = mysqli_fetch_array($result1, MYSQLI_NUM);
$random_number = $row[0];

this $random_number then can be used in the second query. hope this will fix your error.

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.