1

I can't get the following code to display items from the database where the parent_id is equal to the id.

Here is the code below.

// Query member data from the database and ready it for display
$mysqli = new mysqli("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT * FROM categories WHERE id=parent_id");

if (!$dbc) {
// There was an error...do something about it here...
print mysqli_error();
}

while ($row = mysqli_fetch_assoc($dbc)) {
echo '<li><a href="' , $row['url'] , '" title="' , $row['description'] , '">' , $row['category_name'] , '</a>';
   }

I think I know what I'm doing wrong how can I have this query check a previous query?

4
  • Could you provide us with some more info? Like what exaclty doesn't work. Also you can ommit the if statement in the while loop, because you're selecting only rows where parent_id equals id. Commented Oct 26, 2009 at 17:55
  • Does categories have a column called "parent_id"? or is parent_id meant to be a parameter supplied to the query? Commented Oct 26, 2009 at 17:56
  • categories has a parent_id field Commented Oct 26, 2009 at 17:58
  • The code seems fine, try running the query directly from mysql so you can make sure there are records matching your where clause. Which I agree seems strange. Commented Oct 26, 2009 at 18:21

3 Answers 3

1

I'd put the SQL query in a var so you can output it, then try this direct in the database to see if there are any matching rows:

$mysqli = new mysqli("localhost", "root", "", "sitename");
$query = "SELECT * FROM categories WHERE id=parent_id";
echo $query;
Sign up to request clarification or add additional context in comments.

Comments

0

i think this line should be rethought:

if ($row['parent_id'] == $row['id']) {

cause are u sure its the correct logic?

1 Comment

@adam .. this one has me scratching my head really .. i mean i dont really understand the double check there and the logic of the query in the first place.
0

Try do do something like:

if ($row['parent_id'] == $row['id']) {
    echo '<li><a href="' , $row['url'] , '" title="' , $row['description'] , '">' , $row['category_name'] , '</a>';
}
else {
    echo "there is no match!";
}

And see if the problem is, in fact, not in the SQL query but in you app logic (which I think is more likelly).

That said try to debug SQL queries with phpMyAdmin. Just post the query you want there and check for the output. If the output is ok, look into your logic, if not look into your query.

Do try to split your problem into smaller chunks, makes your debugging much easier.

Hope it helps.

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.