Complex sql, How do I do it?

I am developing an application which records students’ school fees in a table named ‘dailyincome’. I have two categories of student, those in the junior secondary school ‘jss’ and senior secondary school ‘sss’. I have two other tables ‘jss’ and ‘sss’ housing the information about the two categories of students. I want a situation that whenever incomeList.php is loaded in the browser, it access the database and list out the payee (student’s) full name, amount paid, date of payment. The link between ‘dailyincome’ table and ‘jss & sss’ is that they both has a column ‘payersID’ which should reference and uniquely identify the full details of the payer and display it on the page. My whole page is now below as I’m trying to get information from dailyincome and jss tables presently though I want to get information from both jss and sss tables and identify them within the dailyincome table.



<?php



//connect to the database
    include_once ('DatabaseManager.php');
	$conn = DatabaseManager::getConnection();
    //get the function
    include_once ('function.php');

    	$page = (int) (!isset($_GET["page"]) ? 1 : $_GET["page"]);
    	$limit = 20;
    	$startpoint = ($page * $limit) - $limit;

        //to make pagination
        $statement = "SELECT dailyincome.id, paymentType, amountPaidInFigure, paymentDate, jss.firstName AS firstName, jss.lastName AS lastName, jss.id FROM dailyincome, jss WHERE jss.payersID = dailyincome.payersID";


require_once '../classes/Config.php';

$result = new ECConfig();
$result2 = new ECConfig();
$result3 = new ECConfig();
$result->getSiteName();
$result2->getSiteNickName();
$result3->getCurrency();
?>

<!DOCTYPE html>
<!--[if IE 8]> 				 <html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->

<head>
	<meta charset="utf-8" />
  <meta name="viewport" content="width=device-width" />
  <title><?php echo $result->getSiteName(); ?>  | Finance</title>
  <link href="../css/normalize.css" rel="stylesheet" />
  <link href="../css/foundation.css" rel="stylesheet" />
  <link href="../css/pagination.css" rel="stylesheet" type="text/css" />
  <link href="../css/B_blue.css" rel="stylesheet" type="text/css" />
  <link href="../main.css" rel="stylesheet" type="text/css" media="all">
  <script src="../js/vendor/custom.modernizr.js"></script>


</head>
<body>
<?php $query = $conn->query("{$statement} ORDER BY jss.id DESC LIMIT {$startpoint} , {$limit}"); ?>
<?php $dailyIncomeRegister = $conn->query("{$statement}");
       $dailyIncome = $dailyIncomeRegister->rowCount(); ?>
     <div class="contain-to-grid">
					<div class="top-bar text-center">

						<h3 class="me1"><?php echo $result->getSiteName(); ?></h3>
                        <h5 class="subheader"><?php echo $result->getSiteNickName(); ?></h5>
					
	</div>
      </div>

 <!-- The part above takes care of the banner region -->

      <div class="row">
      <div class="breadcrumbs">
      <div class="large-7 columns">
        <a href="../homepage.php">Main Home</a> || <a href="index.php">Finance</a>
        </div>
		<div class="large-5 columns">
        You are logged in as <?php if(isset($_SESSION['userName'])) echo $_SESSION['userName']; ?> || Log Out <a href="index.php?action=logout"><img src="../img/quit.png" alt="Log Out" /></a>
        </div>
      </div>
      </div>

      <br/>
      <div class="row">
        <div class="large-9 columns">
        <?php include 'incomeConsole.php'; ?>
        </div>

        <div class="large-3 columns">
        <?php include 'mainmenu.php'; ?>
        </div>

        </div><!--closing tag for the first row -->

        <div class="row">
        <div class="large-12 columns">
          <?php if(isset($query)): ?>
        <p class="searchResult">
        <?php
		  if(isset($dailyIncome)) {
		  if($dailyIncome == 0)
		  {
			   echo 'There is no record of any daily income in the database.';
		  }
		  if($dailyIncome == 1)
		  {
			  echo 'There is 1 record of daily income in the database.';
		  }
		  if($dailyIncome > 1)
		  {
			  echo "There are $dailyIncome records of daily income in the database.";
		  }
		  }
		  ?>
          </p>
         <div class="large-3 columns panel"><h5>Payee's Name</h5></div>
         <div class="large-3 columns panel"><h5>Amount Paid</h5></div>
         <div class="large-2 columns panel"><h5>Payment Date</h5></div>
         <div class="large-4 columns panel"><h5>Action</h5></div>

         <?php foreach($query as $i=>$dailyIncome): ?>

                <div class="large-3 columns"><?php echo ($dailyIncome['lastName']); ?> <?php echo ($dailyIncome['firstName']); ?> <?php echo ($dailyIncome['id']); ?></div>
                <div class="large-3 columns"><?php echo $result->getCurrency(); ?><?php echo htmlentities(number_format($dailyIncome['amountPaidInFigure']), 2); ?></div>
                <div class="large-2 columns"><?php echo (date($dailyIncome['paymentDate'])); ?></div>
                <div class="large-4 columns">
                 <form action="index.php" method="post">
                <div>
                  <input type="hidden" name="id" value="<?php  echo htmlentities($dailyIncome['id']); ?>"/>
                  <input type="submit" name="action" value="Edit Income" class="button myconsole2 radius" />
                  <input type="submit" name="action" value="Delete Income" onclick="return confirm('Delete This Income?')" class="button myconsole2 radius" />
                </div>

              </form>
                </div>
             <hr/>
             <?php endforeach; ?>


        <?php endif; ?>
        <div class="large-12 columns paginate"><?php echo pagination($statement, $limit, $page); ?></div>
		
        </div>

     </div>



<br/>
<br/>
<br/>
<!-- Footer -->
<div class="wrapper row2">
  <div class="row">&nbsp;
  <br/>
   </div>
   </div>
<div class="wrapper row4">
  <div class="row">
  <div class="large-12 columns text-center">
    <p> &copy; <?php echo date('Y'); ?>School Manager  Licensed to <?php echo $result->getSiteName(); ?>, All Rights Reserved.</p>

  </div>

  </div>
</div>

</body>
</html>

I keep getting this error message:

Fatal error: Uncaught exception ‘PDOException’ with message ‘SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘SELECT dailyincome.id, paymentType, amountPaidInFigure, paymentDate, jss.fir’ at line 1’ in C:\xampp\htdocs\finance\function.php:9 Stack trace: #0 C:\xampp\htdocs\finance\function.php(9): PDO->query(‘SELECT COUNT(*)…’) #1 C:\xampp\htdocs\finance\incomeList.php(137): pagination(‘SELECT dailyinc…’, 20, 1) #2 {main} thrown in C:\xampp\htdocs\finance\function.php on line 9.

Now, function.php is to help in paginating my result and its working fine for all other pages where results need to be paginated. Function.php is shown below:

&lt;?php


   function pagination($query, $per_page = 10,$page = 1, $url = '?'){
   include_once ('DatabaseManager.php');
   $conn = DatabaseManager::getConnection();
	
    	$query = "SELECT COUNT(*) as `num` FROM {$query}";
		foreach($conn-&gt;query($query) as $row);
		$total = $row['num'];
        $adjacents = "2";

    	$page = ($page == 0 ? 1 : $page);
    	$start = ($page - 1) * $per_page;								
		
    	$prev = $page - 1;							
    	$next = $page + 1;
        $lastpage = ceil($total/$per_page);
    	$lpm1 = $lastpage - 1;
    	
    	$pagination = "";
    	if($lastpage &gt; 1)
    	{	
    		$pagination .= "&lt;ul class='pagination'&gt;";
                    $pagination .= "&lt;li class='details'&gt;Page $page of $lastpage&lt;/li&gt;";
    		if ($lastpage &lt; 7 + ($adjacents * 2))
    		{	
    			for ($counter = 1; $counter &lt;= $lastpage; $counter++)
    			{
    				if ($counter == $page)
    					$pagination.= "&lt;li&gt;&lt;a class='current'&gt;$counter&lt;/a&gt;&lt;/li&gt;";
    				else
    					$pagination.= "&lt;li&gt;&lt;a href='{$url}page=$counter'&gt;$counter&lt;/a&gt;&lt;/li&gt;";					
    			}
    		}
    		elseif($lastpage &gt; 5 + ($adjacents * 2))
    		{
    			if($page &lt; 1 + ($adjacents * 2))		
    			{
    				for ($counter = 1; $counter &lt; 4 + ($adjacents * 2); $counter++)
    				{
    					if ($counter == $page)
    						$pagination.= "&lt;li&gt;&lt;a class='current'&gt;$counter&lt;/a&gt;&lt;/li&gt;";
    					else
    						$pagination.= "&lt;li&gt;&lt;a href='{$url}page=$counter'&gt;$counter&lt;/a&gt;&lt;/li&gt;";					
    				}
    				$pagination.= "&lt;li class='dot'&gt;...&lt;/li&gt;";
    				$pagination.= "&lt;li&gt;&lt;a href='{$url}page=$lpm1'&gt;$lpm1&lt;/a&gt;&lt;/li&gt;";
    				$pagination.= "&lt;li&gt;&lt;a href='{$url}page=$lastpage'&gt;$lastpage&lt;/a&gt;&lt;/li&gt;";		
    			}
    			elseif($lastpage - ($adjacents * 2) &gt; $page && $page &gt; ($adjacents * 2))
    			{
    				$pagination.= "&lt;li&gt;&lt;a href='{$url}page=1'&gt;1&lt;/a&gt;&lt;/li&gt;";
    				$pagination.= "&lt;li&gt;&lt;a href='{$url}page=2'&gt;2&lt;/a&gt;&lt;/li&gt;";
    				$pagination.= "&lt;li class='dot'&gt;...&lt;/li&gt;";
    				for ($counter = $page - $adjacents; $counter &lt;= $page + $adjacents; $counter++)
    				{
    					if ($counter == $page)
    						$pagination.= "&lt;li&gt;&lt;a class='current'&gt;$counter&lt;/a&gt;&lt;/li&gt;";
    					else
    						$pagination.= "&lt;li&gt;&lt;a href='{$url}page=$counter'&gt;$counter&lt;/a&gt;&lt;/li&gt;";					
    				}
    				$pagination.= "&lt;li class='dot'&gt;..&lt;/li&gt;";
    				$pagination.= "&lt;li&gt;&lt;a href='{$url}page=$lpm1'&gt;$lpm1&lt;/a&gt;&lt;/li&gt;";
    				$pagination.= "&lt;li&gt;&lt;a href='{$url}page=$lastpage'&gt;$lastpage&lt;/a&gt;&lt;/li&gt;";		
    			}
    			else
    			{
    				$pagination.= "&lt;li&gt;&lt;a href='{$url}page=1'&gt;1&lt;/a&gt;&lt;/li&gt;";
    				$pagination.= "&lt;li&gt;&lt;a href='{$url}page=2'&gt;2&lt;/a&gt;&lt;/li&gt;";
    				$pagination.= "&lt;li class='dot'&gt;..&lt;/li&gt;";
    				for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter &lt;= $lastpage; $counter++)
    				{
    					if ($counter == $page)
    						$pagination.= "&lt;li&gt;&lt;a class='current'&gt;$counter&lt;/a&gt;&lt;/li&gt;";
    					else
    						$pagination.= "&lt;li&gt;&lt;a href='{$url}page=$counter'&gt;$counter&lt;/a&gt;&lt;/li&gt;";					
    				}
    			}
    		}
    		
    		if ($page &lt; $counter - 1){
    			$pagination.= "&lt;li&gt;&lt;a href='{$url}page=$next'&gt;Next&lt;/a&gt;&lt;/li&gt;";
                $pagination.= "&lt;li&gt;&lt;a href='{$url}page=$lastpage'&gt;Last&lt;/a&gt;&lt;/li&gt;";
    		}else{
    			$pagination.= "&lt;li&gt;&lt;a class='current'&gt;Next&lt;/a&gt;&lt;/li&gt;";
                $pagination.= "&lt;li&gt;&lt;a class='current'&gt;Last&lt;/a&gt;&lt;/li&gt;";
            }
    		$pagination.= "&lt;/ul&gt;\
";		
    	}


        return $pagination;
    }
?&gt;

I want this page to work and more importantly, I want to get list of students who have paid from both jss and sss tables and cross reference it with dailyincome table and have the result displayed and paginated if necessary, how do I get it to work? I understand the issue is with my sql syntax. please I need help. Thanks.

Place a var_dump($query); after your $query = “SELECT COUNT(*) as num FROM {$query}”; line in pagination.

Take that output and paste it in phpMyAdmin and see if it works. Chances are it doesn’t and you need to modify how that pagination query gets built.

Not real sure about your table structure but you would list the TABLE and FIELD for each requested field and do some sort of JOIN to get multiple tables. I’m thinking the jss in this case would be the primary table to call for student names then LEFT JOIN dailyincome to get any matching income data. If dailyincome should be primary then you’d want to switch those around. You use ON to link the tables by id fields. Something like this.

 $statement = "SELECT 
 dailyincome.id, 
 dailyincome.paymentType, 
 dailyincome.amountPaidInFigure, 
 dailyincome.paymentDate, 
 jss.firstName AS firstName, 
 jss.lastName AS lastName, 
 jss.id 
 FROM jss
 LEFT JOIN dailyincome 
 ON dailyincome.payersID = jss.payersID";

I would test the query as a stand-along version FIRST to check than result is as expected before dealing with pagination.

Not sure how far you’re into things but you MIGHT consider having ONE table for students and a field to identify class, e.g. jss,sss.

Thanks Cpradio, I will test it out and get back to you.

Thanks Drummin, I will test out your solution and I think you’re right about the single table thing as it will reduce my headache. I will let you know when I’m through.

Cpradio, I tried out the line of code and it didn’t make any difference. I guess I didn’t use it right. Drummin, the solution you gave me worked but I’m having problem with function.php which is supposed to create the pagination. Thanks guys for your help so far, how do I get to the bottom of this?

If you look at the query within the pagination function, you’ll notice PART of the query is already written.

$query = "SELECT COUNT(*) as `num` FROM {$query}";

… so what you send as “the Query” through the function needs to just be the tables and conditions, which is…

		$statement2 = "jss
 LEFT JOIN dailyincome
 ON dailyincome.payersID = jss.payersID";

… so I would think that you’d want to have two versions listed on your main page.

        //to grab results from
        $statement = "SELECT
 dailyincome.id,
 dailyincome.paymentType,
 dailyincome.amountPaidInFigure,
 dailyincome.paymentDate,
 jss.firstName AS firstName,
 jss.lastName AS lastName,
 jss.id
 FROM jss
 LEFT JOIN dailyincome
 ON dailyincome.payersID = jss.payersID";
 					
        //to make pagination
		$statement2 = "jss
 LEFT JOIN dailyincome
 ON dailyincome.payersID = jss.payersID";

… and down the page where you call the function, use this second query.

&lt;div class="large-12 columns paginate"&gt;&lt;?php echo pagination($statement2, $limit, $page); ?&gt;&lt;/div&gt;

Of course I have no way to test this but it seems logical to me.

EDIT:

I also don’t like the fact that $query is defined in two places within this function, so I would suggest changing the variable sent through the function to $thequery.

function pagination($thequery, $per_page = 10,$page = 1, $url = '?'){
   include_once ('DatabaseManager.php');
   $conn = DatabaseManager::getConnection();

        $query = "SELECT COUNT(*) as `num` FROM {$thequery}";

See what I’m saying?

I thought that was a little strange too, but I think that it probably works because it’s querying the results of a subquery. Maybe what’s needed is some parenthesis to stop MySQL choking on more complicated queries?

$query = "SELECT COUNT(*) as `num` FROM ({$query})";

Drummin, you’re the guy! Thanks a lot. It worked just fine for me and I’ve learnt a lot from you. Thanks for educating me. Cpradio, I appreciate you and Fretburner as well. Thanks for your response and willingness to share knowledge.

There are so many such as Cpradio and Fretburner that know so much more than me, but I’m glad I could help. Thanks!

Cpradio is surely a Big Boss. He’s helped me out on many occasions. Fretburner is another great guy definitely! Seeing his number of posts within 4 months! Cpradio, Fretburner, Drummin, one more thing please. I want a situation whereby if there is nothing in the dailyincome table, the conditions I set in my main page:


<?php
          if(isset($dailyIncome)) {
          if($dailyIncome == 0)
          {
               echo 'There is no record of any daily income in the database.';
          }
          if($dailyIncome == 1)
          {
              echo 'There is 1 record of daily income in the database.';
          }
          if($dailyIncome > 1)
          {
              echo "There are $dailyIncome records of daily income in the database.";
          }
          }
          ?> 

displays the right information i.e, There is no record of any daily income in the database. You know presently the mysql code accesses both jss and dailyincome tables and even if there is nothing in dailyincome table and there is something in jss, it’ll display one of the messages above. I’ve tried using

style="display: <?php if(isset($dailyIncome['amountPaidInFigure'])) echo 'none'; ?>"

in the div containg the table that shows my result but I’m not getting the desired result. Presently, I have two rows in jss table and the conditional statement I stated up shows that I have two records in the database which display 0 where ($dailyIncome[‘amountPaidInFigure’]) should have displayed the right amount whenever I call the page. What do I do please?

I think what you want to do is follow Drummin’s earlier suggestion of reversing the join condition to make dailyincome the primary table. That way, if there are no daily income records, your query will return an empty resultset.

Thanks a lot Fretburner, Drummings suggestion worked well for my purpose.