Search code examples
phpsqljoinrating-system

How to do a join on this code AND how to retrieve data within the PHP form


I'm unable to figure out how to implement a join in this code. Also a second issue is that I want to use 'Charity No: '.$don['charity_id'].'<br/>'. in the mysql_query ("SELECT * FROM charity where id='?????????'")

What the code does now is it retrieves all this data which is fine, but I want charity_id[FK](which is in the donation table) as charityname(from the charity table) instead, and im sure this is done using a join but can't figure out how to do this in my code. The second issue is that I want to create a rating system that rates the charity (based on the charity number) the data is literraly a few lines above but I can't figure this out either.

My code is:

<?php
if (!isset($_POST['do']) || !isset($_POST['id']) || !$_POST['id'])
exit;

    require_once 'connection.php';

    $don=mysql_fetch_assoc(
        mysql_query('SELECT *
            FROM donation
            WHERE id="'.mysql_real_escape_string($_POST['id'],$con).'"',$con));
    if ($don===false || !$don['id'])
        print '<h3>Donation id #'.$_POST['id'].' does not exist!</h3>';
    else {
        print '<h3>Information about donation id #'.$_POST['id'].'</h3>'.
            'Donor ID: '.$don['donor_id'].'<br/>'.
            'Charity No: '.$don['charity_id'].'<br/>'.
            'Date & Time: '.$don['TransactionTime'].'<br/>'.
            'Donation Amount: £ '.number_format($don['D_Amount'],2).'<br/>'.
         }

$find_data = mysql_query("SELECT * FROM charity where id='?????????'");

while($row = mysql_fetch_assoc($find_data))
{
    $id = $row['id'];
    $C_Name = $row['CharityName']; 
    $C_Desc = $row['CharityDescription'];
    $Hits = $row['Hits'];
    $Ranking = $row['Ranking'];

    echo "

    <form action='rate.php' method='POST'>
    $C_Name: <select name='Ranking'>

    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>

    </select>
    <input type='hidden' value=$id name='ID'>
    <input type='submit' value='Rate'>; 
    </form>


    ";
}

The JOIN I tried now is:

$don=mysql_fetch_assoc(
        mysql_query('SELECT *
                   FROM donation As D JOIN charity as C ON d.charity_id=C.id 
            WHERE id="'.mysql_real_escape_string($_POST['id'],$con).'"',$con));

But now luck.

Any help given would be highly appreciated, Thanks.


Solution

  • Here's the JOIN:

    SELECT charity.*, donation.* 
    FROM charity 
    JOIN donation 
    ON charity.id = donation.charity_id; 
    

    This statement selects all donations. charities without donations are not shown.

    And here's a live-demo for you: http://sqlfiddle.com/#!2/be925/2

    Please rephrase and specify the second question, I didn't understand what you want.