1

I'm working on a system, and this module is supposed to echo the contents of the database.

It worked perfectly until I added some JOIN statements to it.

I've checked and tested the SQL code, and it works perfectly. What's not working is that part where I echo the content of the JOINed table.

My code looks like this:

$query = "SELECT reg_students.*, courses.*
          FROM reg_students
          JOIN courses ON reg_students.course_id = courses.course_id
          WHERE reg_students.user_id = '".$user_id."'";

$result = mysqli_query($conn, $query);
if (mysqli_fetch_array($result) > 0) {
    while ($row = mysqli_fetch_array($result)) {
       echo $row["course_name"]; 
       echo $row["course_id"];

The course_name and course_id neither echo nor give any error messages.


UPDATE: I actually need to increase the query complexity by JOINing more tables and changing the selected columns. I need to JOIN these tables:

tutors which has columns: tutor_id, t_fname, t_othernames, email, phone number
faculty which has columns: faculty_id, faculty_name, faculty_code
courses which has columns: course_id, course_code, course_name, tutor_id, faculty_id

I want to JOIN these tables to the reg_students table in my original query so that I can filter by $user_id and I want to display: course_name, t_fname, t_othernames, email, faculty_name

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Solomon Mbak
  • 75
  • 1
  • 2
  • 14
  • To offer the very best support to you, please create an sqlfiddle demo or at the very least export your tables and enough sample rows for us to test with. In other words, we want to see 3 `CREATE` table queries and 3 sets of `INSERT` queries so that we can use your actual schema/data. – mickmackusa Oct 28 '18 at 04:30
  • 1
    Furthermore, I can eyeball something that is not quite right... `mysqli_fetch_array($result)` is not used to count rows -- in fact, you are going to ignore the first row of data because you use it in the `if` condition. If you are only interested in the `course_name` and `course_id` columns, ask for the specifically in the `SELECT`. If you know which table that they are coming from, be sure to nominate the table, then a `.`, then the column name. Use `mysqli_fetch_assoc()` to generate an assoc result set; `fetch_array()` includes both indexed and associative elements. – mickmackusa Oct 28 '18 at 04:33
  • Are you sure that you need to JOIN `user_info`? You aren't SELECTing anything from it, but it may be a critical check for your query logic -- I can't be sure. – mickmackusa Oct 28 '18 at 04:37

1 Answers1

1

I can't imagine that the user_info table is of any benefit to JOIN in, so I'm removing it as a reasonable guess. I am also assuming that your desired columns are all coming from the courses table, so I am nominating the table name with the column names in the SELECT.

For reader clarity, I like to use INNER JOIN instead of JOIN. (they are the same beast)

Casting $user_id as an integer is just a best practices that I am throwing in, just in case that variable is being fed by user-supplied/untrusted input.

You count the number of rows in the result set with mysqli_num_rows().

If you only want to access the result set data using the associative keys, generate a result set with mysqli_fetch_assoc().

When writing a query with JOINs it is often helpful to declare aliases for each table. This largely reduces code bloat and reader-strain.

Untested Code:

$query = "SELECT c.course_name, t.t_fname, t.t_othernames, t.email, f.faculty_name
          FROM reg_students r
          INNER JOIN courses c ON r.course_id = c.course_id
          INNER JOIN faculty f ON c.faculty_id = f.faculty_id
          INNER JOIN tutors t ON c.tutor_id = t.tutor_id
          WHERE r.user_id = " . (int)$user_id;
if (!$result = mysqli_query($conn, $query)) {
    echo "Syntax Error";
} elseif (!mysqli_num_rows($result)) {
    echo "No Qualifying Rows";
} else {
    while ($row = mysqli_fetch_assoc($result)) {
        echo "{$row["course_name"]}<br>";
        echo "{$row["t_fname"]}<br>";
        echo "{$row["t_othernames"]}<br>";
        echo "{$row["email"]}<br>";
        echo "{$row["faculty_name"]}<br><br>";
    }
}
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • This is actually an assumption. Assuming user_info is relevant, how exactly would I echo contents of both tables? – Solomon Mbak Oct 28 '18 at 05:30
  • The table has the following tables `tutors`, `courses`, `faculty`, and some unique fields on them (tutor_id). I want to echo fields from all these tables on one form. – Solomon Mbak Oct 28 '18 at 13:41
  • Ok, these are the tables. Tutors table has [tutor_id, t_fname, t_othernames, email, phone number] Faculty table has [faculty_id, faculty_name, faculty_code] Courses table has [course_id, course_code, course_name, tutor_id, faculty_id] I want to JOIN these tables and echo (course_name, t_fname, t_othernames, email, faculty_name) – Solomon Mbak Oct 29 '18 at 06:34
  • It's says: mysqli_num_roes() expects parameter 1 to be mysqli_result, Boolean given. The error points to the line with `elseif(!mysqli_num_rows($result))` – Solomon Mbak Oct 29 '18 at 09:03
  • Then you didn't use my snippet. My code catches error and it should be telling you "Syntax Error". Please replace my `echo "Syntax Error";` line with `echo mysqli_error($conn);` – mickmackusa Oct 29 '18 at 09:04
  • It did. I deleted the first line and left it as if(!mysqli_num_rows($result)). Just to simplify it. – Solomon Mbak Oct 29 '18 at 09:06
  • Instead of using the result in an if statement, I declared it instead as $result = mysqli_query($conn, $query); – Solomon Mbak Oct 29 '18 at 09:16
  • Please follow this link to see a screenshot of what I did: https://drive.google.com/file/d/1y5oX4S_E41br_PFStU4QoKGKu8ImaHPF/view?usp=drivesdk – Solomon Mbak Oct 30 '18 at 13:21
  • I have already seen your original coding attempt. How can I possibly offer you continued support when you don't use the EXACT snippet that I post for you? Use my snippet. Then tell me in detail how it doesn't work. – mickmackusa Oct 30 '18 at 21:52
  • I get "Syntax Error" returned to me. – Solomon Mbak Oct 31 '18 at 06:56
  • Please replace my `echo "Syntax Error";` line with `echo mysqli_error($conn);` – mickmackusa Oct 31 '18 at 08:08
  • My guess is that we have a typo in a table name or column name. – mickmackusa Oct 31 '18 at 12:20
  • Works perfectly. I modified the join statement. There was a little error on it. It's great now. – Solomon Mbak Nov 01 '18 at 07:01
  • Phew!! Then it was all worth it. Was there a typo in the column name or table name? We now have the responsibility to clean up this page. Please edit your question so that it reflects the exact issue that I have solved (mention the tables and columns to be JOINed; I can't edit your question because I don't know what the correct spelling is for each table/column) , then I can update my answer too. Then we should remove all of the comments to clean up the page. I am happy to upvote your question after it is updated. Thank you for your efforts. – mickmackusa Nov 01 '18 at 07:05
  • Yes, there was a typo on the masters_course. It was an i instead of an o. It was really worth it. You also need to add a . in front of the `.(int)$user_id.` On your end, that's just what you need to do. Tye typo was from the DB itself, not the code. – Solomon Mbak Nov 01 '18 at 16:01
  • What good would it do to add a second dot in front of `(int)`? There is no benefit to telling php "I'm concatenating, I'm concatenating, here's the number variable". – mickmackusa Nov 01 '18 at 20:11
  • I mean, just the way I typed it up there. A second . is missing at the end of yours. – Solomon Mbak Nov 02 '18 at 05:21
  • With `WHERE r.user_id = " . (int)$user_id;` the query is finished after `$user_id`. There is absolutely no reason to add another dot. There is nothing more to concatenate. – mickmackusa Nov 02 '18 at 05:34