So I have two tables, one called 'questions' and one called 'tests'. Each row in 'questions' has the columns 'id','test' and several other columns not relevant to this question. The 'tests' table has the columns 'id','name' and several others not relevant.
Basically, on my website, every time someone creates a test, a new row is created in 'tests' and its given an 'id'. From there, every question the user makes, creates a new row in the 'questions' table, each question is given an 'id' as well as 'test' column having the same number as the 'id' from the 'tests' table to which it belongs.
Yesterday we mistakenly deleted several rows from the 'tests' table, however all the questions are still in the 'questions' table, meaning we just need to find which rows in the 'questions' table have a 'test' value that isn't linked to any 'id' in the 'tests' table, so this is the .php script we came up with:
<?php
$conn = mysql_connect ('localhost', 'hidden', 'hidden') or die ('Error connecting');
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('hidden', $conn);
$sql = "SELECT * FROM questions";
$result = mysql_query($sql,$conn);
while ($row = mysql_fetch_array($result)) {
$test = $row['test'];
$questionID = $row['id'];
$sql2 = "SELECT * FROM tests where id = $test";
$result2 = mysql_query($sql2, $conn);
$row2 = mysql_fetch_array($result2);
$num_rows = mysql_num_rows($result2);
if ($num_rows == 0) {
echo "Unlinked question: $questionID (test $test) <br/>";
}
}
?>
However, it doesn't echo any "Unlinked question.. " which would help us identify which tests we have lost and need to recreate, giving them the correct 'id' to link to the 'questions' table 'test' column. Is there another way to fix this problem? And yes, we have do backup the tables, but unfortunately we only do it every other week, and most of the deleted tests were recent.
Update:
$sql = "
SELECT q.id AS QuestionID
FROM questions q
LEFT JOIN tests t
ON (q.test = t.id)
WHERE q.test IS NOT NULL AND t.id IS NULL";
$result = mysql_query($sql,$conn) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$questionID = $row['QuestionID'];
$testID = $row['test'];
echo $row;
echo "The question with the id: $questionID is not linked to the test: $testID";
}
?>