total n00b here, first post, so please be constructive! I’ve bought a book to teach myself PHP / MySQL – and not one which is universally praised, unfortunately – so my progress is a bit erratic.
I have two tables which I want to link. I want to display all of the information held in table 1 (let’s call it Records), but ONLY once. I then want to check whether each item in Records has a match to a specific field in table 2 (UserTable) and if it does, display a ticked checkbox, or an empty checkbox if there’s no match.
The issues I’ve had to date are only displaying the items from Records where there’s a match, or displaying multiple instances of each item in Records where there are multiple matches. I’ve solved these with the code below – but I keep thinking there must be a better way to do this, perhaps with a single link?
Anyway, here are some excerpts from the code:
$sql = "SELECT * FROM Records";
$res = mysqli_query($mysqli,$sql);
while ($iteminfo = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
$recordid2 = $iteminfo['record_id'];
I’ve omitted a section which pulls out the relevant data from Records and starts to build a table, then:
$sql2 = "SELECT COUNT(*) AS matches FROM UserTable
where usertable.item = '$recordid2' and User_ID = '$current_user_id'";
$res2 = mysqli_query($mysqli, $sql2);
$matches = mysqli_fetch_array($res2, MYSQLI_ASSOC);
$matches2 = $matches['matches'];
if ($matches2) {
$output = "<input type='checkbox' name='test' checked>"; } else {
$output = "<input type='checkbox' name='test'>";
As I say, this works, but it feels a bit clumsy – I’m running a separate nested query for every item in Records, which over time could become really slow. Is there a way to run a single query for the whole which brings through all of the row info (once) and a 0 or 1 depending on whether there is a match in UserTable? I’ve tried using DISTINCT but couldn’t get it to work.
How about this:
This fetches ALL records, and also only the matching rows for the given User ID in UserTable (change the User ID to fetch details for a different user).
If a row in Record exists, but no matching row exists in UserTable, then “matches” will be NULL. Otherwise it should be a numeric value greater than zero.
Just run this in PHP to handle the checkbox stuff. (it checks for matches greater than zero, and only if found, will print out the “checked” attribute)