user6403766
user6403766

Reputation:

How to Select and Fetch two tables Data in php mysql with one query?

I am getting this Error: operand should contain 1 column(s) from the following code

$select = mysql_query("SELECT (SELECT id_post,id_category,id_user,title,description,image,date_added FROM r_post) as id_post,id_category,id_user,title,description,image,date_added ,(SELECT name FROM r_category) as categoryname")or die(mysql_error());

while ($result = mysql_fetch_assoc($select)) {

    <div class="tc-ch">     
    <?php if(!empty($result['image'])){?>
        <div class="tch-img">
            <a href="/<?=$result['seo_url']?>"><img src="admin/images/<?= $result['image'] ?>" class="img-responsive" alt=""/></a>
        </div>
        <a class="blog blue"><?= $result['name'] ?></a>
        <?}?>
        <h3> <a href="/<?=$result['seo_url']?>"><?= $result['title'] ?></a></h3>
        <p><?= $result['description'] ?></p>
        <div class="blog-poast-info">
            <ul>
                <li><i class="glyphicon glyphicon-user"> </i><a class="admin" href="#"><?= $result['id_user'] ?> </a></li>
                <li><i class="glyphicon glyphicon-calendar"> </i><?= $result['date_added'] ?></li>
                <li><i class="glyphicon glyphicon-comment"> </i><a class="p-blog" href="#"><?= $result['categoryname'] ?></a></li>
            </ul>
        </div>
    </div>
<?php } ?>

Could someone help me to get over this ?

Upvotes: 0

Views: 357

Answers (1)

dcod
dcod

Reputation: 70

You cannot just select two tables in one query if the columns don't match (in which you could use a union) or you want to join.

Without seeing the structure of your database, I can't say for sure, but it seems to me that you want to join these on id_category like so:

SELECT id_post, id_category, name AS categoryname, id_user, title, description, image, date_added FROM r_post rp INNER JOIN r_category rc ON rc.id_category = rp.id_category

If my assumptions are wrong about your database please clarify what exactly you need. Also, for future reference, since this is purely a SQL question, just post your query and information about your database so we don't get lost in all of the other irrelevant code.

Edit for how to fetch results:

You are correct in doing

while ($result = mysql_fetch_assoc($select))

This will iterate over every row. All you then need to do is use

echo $result['col_name'];

in php code. So for example, for a paragraph tag you would use:

<p><?php echo $result['description']; ?></p>

That basically prints the result into the HTML code.

Upvotes: 1

Related Questions