Jump to content

Get rows from mysql table.


ram4nd

Recommended Posts

I need to get some rows from mysql table.

 

I have 2 tables: categories and subcategories.

I need to get categorie and subcategories what are linked with that catagorie.

 

I have table where are: subcategorie name and categorie_id. I wonder how can I get all those subcategories. When i tryed i got only the first subcategorie name.

 

This code takes categore names and prints them all.

$mysql = new mysql();
$num_rows1 = $mysql->doQueryC('SELECT * FROM category');

for($i = 0; $i <= $num_rows1; $i++)
{
$cat = $mysql->doQueryA('SELECT name FROM category WHERE id = ' . $i);
echo $cat['name'] . '<br>';
}

Link to comment
https://forums.phpfreaks.com/topic/141067-get-rows-from-mysql-table/
Share on other sites

I have table where are: subcategorie name and categorie_id. I wonder how can I get all those subcategories. When i tryed i got only the first subcategorie name.

 

This code takes categore names and prints them all.

$mysql = new mysql();
$num_rows1 = $mysql->doQueryC('SELECT * FROM category');

for($i = 0; $i <= $num_rows1; $i++)
{
$cat = $mysql->doQueryA('SELECT name FROM category WHERE id = ' . $i);
echo $cat['name'] . '<br>';
}

Instead of doing a num_rows and a for loop with a second MySQL statement, just do this:

 

$mysql = new mysql();
$result = $mysql->doQueryA('SELECT id,name FROM category');

foreach ($result as $r) {
   echo $r['name'];

   // Then, do a second query to pull your subcategories... something like this:
   $result2 = $mysql->doQueryA('SELECT name FROM subcategorie WHERE categorie_id='.$r['id']);

   foreach ($result2 as $r2) {
       echo 'Subcategory:  '.$r2['name'];
   }
}

 

Just kinda guessed at the subcategory table, since you didn't really describe the layout of the tables.

Shows couple of errors, I think if I copye my sql code to here than that's enought.

function doQueryA($query)
{
$this->doConnect();
$result = mysql_fetch_assoc(mysql_query($query, $this->connect));
$this->doDisconnect();
return $result;
}

You're not checking to see that the result actually contains a result row.  Use a conditional statement to test that the $result has num_rows() > 0 before you fetch_assoc() it.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.