I can't figure out how to format my table so that there is a header for each section of attributes. I only see one header when there are actually more that I need to see.
For example I'm able to get DROID 4 by MOTOROLA and all of it's attributes go from Full Retail Price to Voice Dialing. After Voice Dialing there should be a second header for another phone. Clearly my logic is messed up and I have been struggling for about 4 hours on it. I also need the two tables to be side by side, not in a long list like this.
This is what I'm trying to achieve:
My code looks like this:
<?
session_start();
if(!session_is_registered(myusername)){
header("location:main_login.php");
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="theme.css" />
</head>
<body>
<?php
include_once 'config.php';
$conf = new config();
mysql_connect($conf->getdbServ(), $conf->getdbUser(), $conf->getdbPwd()) or die(mysql_error());
mysql_select_db($conf->getDB()) or die(mysql_error());
$selectedPhones = $_POST['phones'];
$totalSelected = count($selectedPhones);
//echo $totalSelected;
$idList = "";
for($i=0;$i < $totalSelected; $i++){
$idList .= $selectedPhones[$i] . ",";
}
$idList = substr($idList,0,-1);
$query = "Select name from ".$conf->getproductTbl()." WHERE id='$idList'";
$res=mysql_query($query);
//echo $idList;
$data = mysql_query("SELECT ".$conf->getproductTbl().".id, ".$conf->getproductAttr().".* from ".$conf->getproductTbl()."
LEFT JOIN ".$conf->getproductAttr()." ON ".$conf->getproductTbl().".id=".$conf->getproductAttr().".prodFK
Where ".$conf->getproductTbl().".id IN(" . $idList . ");");
echo "<table width = 100% border = '1' cellspacing = '2' cellpadding = '0'>";
while ($result = mysql_fetch_assoc($res))
{
echo "<th colspan='2'>".$result["name"]."</th>";
}
while ($row = mysql_fetch_assoc($data)) {
echo "<tr><td>";
echo $row["Name"];
echo "</td><td>";
echo $row["value"];
echo "</td></tr>";
}
echo "</table>";
?>
</body>
</html>
1 - You might want to look into MYSQL JOIN to combine your two queries. (http://www.tizag.com/mysqlTutorial/mysqljoins.php)
2 - Use CSS to style your result set.
You can try something like this.. I hope that will help you.
<table>
<tr>
<?php
for($i=0;$i < $totalSelected; $i++){
//$idList .= $selectedPhones[$i] . ",";
?>
<td><?php
$data = mysql_query("SELECT ".$conf->getproductTbl().".id, ".$conf->getproductAttr().".* from ".$conf->getproductTbl()."
LEFT JOIN ".$conf->getproductAttr()." ON ".$conf->getproductTbl().".id=".$conf->getproductAttr().".prodFK
Where ".$conf->getproductTbl().".id = ".$selectedPhones[$i]);
echo "<table width = 100% border = '1' cellspacing = '2' cellpadding = '0'>";
while ($result = mysql_fetch_assoc($res))
{
echo "<th colspan='2'>".$result["name"]."</th>";
}
while ($row = mysql_fetch_assoc($data)) {
echo "<tr><td>";
echo $row["Name"];
echo "</td><td>";
echo $row["value"];
echo "</td></tr>";
}
echo "</table>";
?>
</td>
<?php }?>
</tr>
</table>
Related
Ok so I'm trying to make a localhost site that has the same base functions as Phpmyadmin, and everything is working other than displaying a table's data.
here's an example of what I'm trying to accomplish:
though I'm not sure how to accomplish this. Here is some code to show you what I have now
<div class="content">
<?php $query2 = "SELECT * FROM " . $table; ?>
<div class="query-class">
<?php echo $query2; ?>
</div>
<h1>
Tables In <?php echo $db; ?>
</h1>
<table>
<?php
$columquery = "SHOW COLUMNS FROM " . $table;
$columresult = mysql_query($columquery);
while ($row3 = mysql_fetch_array($columresult)) {
echo "<th>" . $row3['Field'] . "</th>";
}
?>
<?php
$result2 = mysql_query($query2);
while ($row2 = mysql_fetch_array($result2)) {
foreach($row2 as $var) {
echo "<tr><td>" . $var . "</td></tr>";
}
}
?>
</table>
</div>
Yes yes, I know it's horrible.
The other answers use the mysqli API while you're using the older, no longer supported mysql API. I really recommend upgrading to either mysqli or PDO, but if you want to stay with mysql you can use the following solution:
<div class="content">
<?php $query2 = "SELECT * FROM " . $table; ?>
<div class="query-class">
<?php echo $query2; ?>
</div>
<h1>
Tables In <?php echo $db; ?>
</h1>
<table>
<?php
$shouldOutputHeaders = true;
$result2 = mysql_query($query2);
while ($row2 = mysql_fetch_assoc($result2)) {
if ($shouldOutputHeaders) {
echo "<tr>";
foreach (array_keys($row2) as $header) {
echo "<th>" . $header . "</th>";
}
echo "</tr>";
$shouldOutputHeaders = false;
}
echo "<tr>";
foreach ($row2 as $var) {
echo "<td>" . $var . "</td>";
}
echo "</tr>";
}
?>
</table>
</div>
If i understood you well, You need mysqli_fetch_row.
$q= "SELECT * FROM table";
$result = $mysqli->query($q)
while ($row = $result->fetch_row()) {
print ("$row[0], $row[1]);
}
I think you are looking for something very ugly like the following. I found it in the garbage. I am not responsable for any use of it:
<?php
$db=Db::getConnection(); // singleton
$this->var['result']=$db->query($_POST['query']);
if (isset($this->var['result'])) {
echo '<table cellpadding="5" cellspacing="2" border="1"><tbody>';
$titles=array_keys(#$this->var['result'][0]);
echo '<tr>';
foreach($titles as $title)
echo '<th>'.$title.'</th>';
echo '</tr>';
foreach($this->var['result'] as $row) {
echo '<tr>';
foreach($row as $cell) {
echo '<td>'.$cell.'</td>';
}
echo '</tr>';
}
echo '</tbody></table>';
}
?>
Db is an standard singleton that contains a mysqli private object.
query() contains something like
$sql = $this->mysqli->query($query);
$this->lastInsertId = $this->mysqli->insert_id;
$errno = $this->mysqli->connect_errno;
if ($errno === 0) {
if ($this->mysqli->field_count > 0) {
while ($row = $sql->fetch_assoc()) $response[] = $row;
return $response;
}else{
return true;
}
}
to create the "array of arrays" response. Suitable for the output you are looking for.
I've added some escaping and only queried the database when needed:
// Print table tags
echo "<table>";
// Print out records
$q = mysql_query("SELECT * FROM {$table};");
if($res = $result->fetch_all(MYSQLI_ASSOC)){
// Print out columns
$columns = array_keys($res[0]);
echo'<tr><th>'.implode('</th><th>', array_map('htmlspecialchars',$columns).'</th></tr>';
// Print out table data
echo'<tr><td>'.implode('</td><td>', array_map('htmlspecialchars',$res).'</td></tr>';
} else {
// IFF there is no data, print out columns
$q = mysql_query("SHOW COLUMNS FROM {$table};");
if($res = $result->fetch_all(MYSQLI_ASSOC)){
// Print columns
echo'<tr><th>'.implode('</th><th>', array_map('htmlspecialchars',$res).'</th></tr>';
}
}
echo '</table>';
Hope this helps,
i'm coding a project and have some troubles when the system inform error:
Invalid argument supplied for foreach() in:
foreach($dbh->query($q1) as $row)
and can't get data from the database. How can i fix it, im a newbie, so if i don't understand, please teach me! thanks!
thank for your helps but i still can't fix it
<?php include("top.html"); ?>
<body>
<div id="main">
<h1>Results for <?php echo $_GET['firstname'] . " " . $_GET['lastname'] ?></h1> <br/><br/>
<div id="text">All Films</div><br/>
<table border="1">
<tr>
<td class="index">#</td>
<td class="title">Title</td>
<td class="year">Year</td>
</tr>
<?php
$dbh = new PDO('mysql:host=localhost;dbname=imdb_small', 'root', '');
$q1 = "SELECT id
FROM actors
WHERE first_name = '".$_GET['firstname']."' AND last_name = '".$_GET['lastname']."'
AND film_count >= all(SELECT film_count
FROM actors
WHERE (first_name LIKE'".$_GET['firstname']." %' OR first_name = '".$_GET['firstname']."')
AND last_name = '".$_GET['lastname']."')";
$id = null;
foreach($dbh->query($q1) as $row){
$id = $row['id'] ;
}
if($id == null){
echo "Actor ".$_GET['firstname']." ".$_GET['lastname']."not found.";
}
`
$sql2 = "SELECT m.name, m.year
FROM movies m
JOIN roles r ON r.movie_id = m.id
JOIN actors a ON r.actor_id = a.id
WHERE (r.actor_id='".$id."')
ORDER BY m.year DESC, m.name ASC";
$i = 0;
foreach($dbh->query($sql2) as $row){
echo "<tr><td class=\"index\">";
echo $i+1;
echo "</td><td class=\"title\">";
echo $row['name'];
echo "</td><td class=\"year\">";
echo $row['year'];
echo "</td></tr>";
$i++;
}
$dbh = null;
?>
</table>
</div>
</div>
<?php include("bottom.html"); ?>
</body>
</html>
Check that your query succeeded before iterating on the result:
if (false !== ($result = $dbh->query($d1))) {
foreach($result as $row){
$id = $row['id'] ;
}
}
By the way, I don't understand what you are trying to do with this pointless loop.
You could do this
$st = $dbh->query($q1);
if ( $st ) {
while ( $row = $st->fetch() ) {}
}
Try to make your code more readable
$result = $dbh->query($q1);
foreach($result as $row){$id = $row['id'];}
I am writing an application in which user can enter a database name and I should write all of its contents in table with using PHP.I can do it when I know the name of database with the following code.
$result = mysqli_query($con,"SELECT * FROM course");
echo "<table border='1'>
<tr>
<th>blablabla</th>
<th>blabla</th>
<th>blablabla</th>
<th>bla</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['blabla'] . "</td>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['bla'] . "</td>";
echo "</tr>";
}
echo "</table>";
In this example I can show it since I know the name of table is course and it has 4 attributes.But I want to be able to show the result regardless of the name the user entered.So if user wants to view the contents of instructors there should be two columns instead of 4.How can I accomplish this.I get the table name with html.
Table:<input type="text" name="table">
Edit:Denis's answer and GrumpyCroutons' answer are both correct.You can also ask me if you didnt understand something in their solution.
Quickly wrote this up, commented it (This way you can easily learn what's going on, you see), and tested it for you.
<form method="GET">
<input type="text" name="table">
</form>
<?php
//can be done elsewhere, I used this for testing. vv
$config = array(
'SQL-Host' => '',
'SQL-User' => '',
'SQL-Pass' => '',
'SQL-Database' => ''
);
$con = mysqli_connect($config['SQL-Host'], $config['SQL-User'], $config['SQL-Pass'], $config['SQL-Database']) or die("Error " . mysqli_error($con));
//can be done elsewhere, I used this for testing. ^^
if(!isSet($_GET['table'])) { //check if table choser form was submitted.
//In my case, do nothing, but you could display a message saying something like no db chosen etc.
} else {
$table = mysqli_real_escape_string($con, $_GET['table']); //escape it because it's an input, helps prevent sqlinjection.
$sql = "SELECT * FROM " . $table; // SELECT * returns a list of ALL column data
$sql2 = "SHOW COLUMNS FROM " . $table; // SHOW COLUMNS FROM returns a list of columns
$result = mysqli_query($con, $sql);
$Headers = mysqli_query($con, $sql2);
//you could do more checks here to see if anything was returned, and display an error if not or whatever.
echo "<table border='1'>";
echo "<tr>"; //all in one row
$headersList = array(); //create an empty array
while($row = mysqli_fetch_array($Headers)) { //loop through table columns
echo "<td>" . $row['Field'] . "</td>"; // list columns in TD's or TH's.
array_push($headersList, $row['Field']); //Fill array with fields
} //$row = mysqli_fetch_array($Headers)
echo "</tr>";
$amt = count($headersList); // How many headers are there?
while($row = mysqli_fetch_array($result)) {
echo "<tr>"; //each row gets its own tr
for($x = 1; $x <= $amt; $x++) { //nested for loop, based on the $amt variable above, so you don't leave any columns out - should have been <= and not <, my bad
echo "<td>" . $row[$headersList[$x]] . "</td>"; //Fill td's or th's with column data
} //$x = 1; $x < $amt; $x++
echo "</tr>";
} //$row = mysqli_fetch_array($result)
echo "</table>";
}
?>
$tablename = $_POST['table'];
$result = mysqli_query($con,"SELECT * FROM $tablename");
$first = true;
while($row = mysqli_fetch_assoc($result))
{
if ($first)
{
$columns = array_keys($row);
echo "<table border='1'>
<tr>";
foreach ($columns as $c)
{
echo "<th>$c</th>";
}
echo "</tr>";
$first = false;
}
echo "<tr>";
foreach ($row as $v)
{
echo "<td>$v</td>";
}
echo "</tr>";
}
echo "</table>";
<?php
$table_name = do_not_inject($_REQUEST['table_name']);
$result = mysqli_query($con,'SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME='. $table_name);
?>
<table>
<?php
$columns = array();
while ($row = mysql_fetch_assoc($result)){
$columns[]=$row['COLUMN_NAME'];
?>
<tr><th><?php echo $row['COLUMN_NAME']; ?></th></tr>
<?php
}
$result = mysqli_query($con,'SELECT * FROM course'. $table_name);
while($row = mysqli_fetch_assoc($result)){
echo '<tr>';
foreach ($columns as $column){
?>
<td><?php echo $row[$column]; ?></td>
<?php
}
echo '</tr>';
}
?>
</table>
I am trying to display multiple rows from Oracle table with php.
Below is my code:
<?php
include("dbconnect.php");
$personcon=$conn;
$surname = $_POST['Surname'];
$suburb = $_POST['Suburb'];
$state = $_POST['State'];
$discipline = $_POST['Discipline'];
$companyname = $_POST['CompanyName'];
$rank = $_POST['Rank'];
$role = $_POST['Role'];
$yearsexperience = $_POST['YearsExperience'];
$recentproject = $_POST['RecentProject'];
$sellrate = $_POST['SellRate'];
$projectnumber = $_POST['ProjectNumber'];
$tendernumber = $_POST['TenderNumber'];
$query = "SELECT CP.ROLE AS CURRENT_ROLE , CP.SURNAME, CP.FIRSTNAME, CP.COMPANY,CC.COMPANYNAME AS CONSULTANT_COMPANY, CP.YEARSEXPERIENCE AS EXPERIENCE_IN_YEAR, CP.QUALIFICATION, D.PRINCIPLEDISCIPLINE, D.SUBDISCIPLINE1, D.SUBDISCIPLINE2, D.SUBDISCIPLINE3, D.SUBDISCIPLINE4, D.SUBDISCIPLINE5, D.SUBDISCIPLINE6, D.SUBDISCIPLINE7, D.SUBDISCIPLINE8, L.SUBURB, L.STATE, L.COUNTRY FROM CONSULTANTPERSONNEL CP, LOCATION L, ONSULTANTPERSONNEL_DISCIPLINE N, DISCIPLINE D, CONSULTANTCOMPANY CC, CONTRACTS C, PROJECTS P, TENDERS T, FEEBASIS F WHERE CP.LOCATIONID = L.LOCATIONID AND CP.CONSULTANTPERSONALID = N.CONSULTANTPERSONALID AND N.DISCIPLINID = D.DISCIPLINID AND CP.CONSULTANTCOMPANYID = CC.CONSULTANTCOMPANYID AND CP.CONTRACTID = C.CONTRACTID AND C.FEECODE = F.FEECODES AND C.PROJECTNUMBER = P.PROJECTNUMBER AND C.TENDERNUMBER = T.TENDERNUMBER AND LOWER(CP.SURNAME) LIKE LOWER('%".$surname."%') AND LOWER(L.SUBURB) LIKE LOWER('%".$suburb."%') AND LOWER(L.STATE) LIKE LOWER('%".$state."%') AND LOWER(D.PRINCIPLEDISCIPLINE) LIKE LOWER('%".$discipline."%') AND LOWER(CC.COMPANYNAME) LIKE LOWER('%".$companyname."%') AND LOWER(CP.RANK) LIKE LOWER('%".$rank."%') AND LOWER(CP.ROLE) LIKE LOWER('%".$role."%') AND LOWER(P.PROJECTNAME) LIKE LOWER('%".$recentproject."%') AND LOWER(P.PROJECTNUMBER) LIKE LOWER('%".$projectnumber."%') AND LOWER(T.TENDERNUMBER) LIKE LOWER('%".$tendernumber."%')";
$SQL = oci_parse($personcon, $query);
oci_execute($SQL);
$results = array();
$numRows = oci_fetch_all($SQL, $results, null, null, OCI_FETCHSTATEMENT_BY_ROW);
if($numRows > 0){
echo "<p> <table border=1>\n";
//Print the headings
echo "<tr>\n";
foreach($results[0] as $index=>$value)
echo "<th>$index</th>\n";
echo "</tr>\n";
echo "<tr>\n";
foreach($results as $row)
foreach($row as $index=>$value)
echo "<td>$value</td>\n";
echo "</tr>\n";
echo "</table>\n </p>";
oci_close($personcon);
} else {
echo "<tr> The search you enter is not in the database.";
}
?>
I can retrieve the data I wish but instead of displaying row by row, it displays all the data in one row.
Any Idea how to fix that ? Thanks
You got simple and common (for me at least) mistake in Your loops, that creates only one row and puts every column inside. Try changing:
echo "<tr>\n";
foreach($results as $row)
foreach($row as $index=>$value)
echo "<td>$value</td>\n";
echo "</tr>\n";
to something like this:
foreach($results as $row)
{
echo "<tr>\n";
foreach($row as $index=>$value)
{
echo "<td>$value</td>\n";
}
echo "</tr>\n";
}
The brackets will help You see the scopes. Its not python, You know. ;)
having trouble getting a script of mine to run correctly, I have 2 undefined index errors and an invalid argument supplied error that for the life of me I can't figure out why I'm getting. the 2 undefined index errors come from these lines.
if(!is_null($_GET['order']) && $_GET['order'] != 'courseTitle')
and
if (!is_null($_GET['page']))
and my invalid argument error is this
Warning: Invalid argument supplied for foreach() in
generated from this
<?php foreach ($books as $book) : ?>
my full code between the two classes is this.. any ideas of what I've done wrong? tearing my hair out over this.
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Catalog</title>
</head>
<body bgcolor="white">
<?php
/////////////////////////////////////////////////
//connect to db
/////////////////////////////////////////////////
$dsn = 'mysql:host=localhost;dbname=book_catalog';
$username = "php";
$password = "php";
$db = new PDO($dsn, $username, $password);
//get data
if(!is_null($_GET['order']) && $_GET['order'] != 'courseTitle')
{
$thesort = $_GET['order'];
$query = "Select * FROM book
INNER JOIN course
ON book.course = course.courseID
ORDER BY ".$_GET['order'];
}
else
{
$thesort = "courseTitle";
$query = "Select * FROM book
INNER JOIN course
ON book.course = course.courseID
ORDER BY $thesort";
}
//if page is null go to first page otherwise query for correct page
if (!is_null($_GET['page']))
{
$query = $query." LIMIT ".($_GET['page']*8-8).", 8";
}
else
{
$query = $query." LIMIT 0, 8";
}
//query result
$books = $db->query($query);
//get number of overall rows
$query2 = $db->query("SELECT * FROM book");
$count = $db->query("SELECT Count(*) As 'totalRecords' FROM book");
$count = $count->fetch();
$count = $count['totalRecords'];
?>
<table border =" 1">
<tr>
<th bgcolor="#6495ed"><a href="?order=course">Course #</th>
<th bgcolor="#6495ed"><a href="?order=courseTitle">Course Title</th>
<th bgcolor="#6495ed"><a href="?order=bookTitle">Book Title</th>
<th bgcolor="#6495ed"></th>
<th bgcolor="#6495ed"><a href="?order=price">Price</th>
</tr>
<?php foreach ($books as $book) : ?>
<tr>
<td><?php echo $book['course']; ?></td>
<td><?php echo $book['courseTitle']; ?></td>
<td><?php echo $book['bookTitle']; ?></td>
<td><?php
$bookcourse = $book['course'];
$isbn = $book['isbn13'];
$booklink = "<a href=\"course.php?course=$bookcourse&isbn=$isbn\">";
echo $booklink ;?><img src='images/<?php echo $book['isbn13'].'.jpg'; ?>'></a></td>
<td><?php echo $book['price']; ?></td>
</tr>
<?php endforeach; ?>
</tr>
</table>
<?php
//paging function... not sure if it works correctly?
for ($j=1; $j <= ceil($count/8); $j++)
{ ?>
<a href=<?php echo "?page=".$j."&order=".$thesort; ?>><?php echo $j; ?></a>
<?php
}?>
</body>
</html>
**course.php**
<?php
//get data from index.php
$course = $_GET['course'];
$isbn = $_GET['isbn'];
//connect to db
$dsn = 'mysql:host=localhost;dbname=book_catalog';
$username = "php";
$password = "php";
$db = new PDO($dsn, $username, $password);
//get data
$query = "Select * FROM book, course, author, publisher
WHERE book.isbn13 = $isbn AND book.course = '$course' AND book.course = course.courseID AND book.bookID = author.bookID AND book.publisher = publisher.publisherID
ORDER BY book.bookID";
//query results
$books = $db->query($query);
//error troubleshooting
if (!$books) {
echo "Could not successfully run query ($query) from DB: " . mysql_error();
exit;
}
//count the number of rows in the result
$results = $books->fetchAll();
$rowCount = count($book);
//get data from results
foreach($results as $book){
$bookID = $book['bookID'];
$bookTitle = $book['bookTitle'];
$isbn = $book['isbn13'];
$price = $book['price'];
$desc = $book['description'];
$publisher = $book['publisher'];
$courseTitle = $book['courseTitle'];
$courseID = $book['courseID'];
$credits = $book['credit'];
$edition = $book['edition'];
$publishDate = $book['publishDate'];
$length = $book['length'];
$firstName = $book['firstName'];
$lastName = $book['lastName'];
}
if($numrows > 1)
{
foreach ($books as $book)
{
$authorArray[] = $book['firstName'] + ' ' + $book['lastName'];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>CIS Department Book Catalog</title>
</head>
<body bgcolor=white">
<table border="0">
<tr>
<td>
<img src='images/<?php echo $isbn.'.jpg'; ?>'>
</td>
<td>
<?php
echo "For Course: $courseID $courseTitle ($credits)";
echo "</br>";
echo "Book Title: $bookTitle";
echo "</br>";
echo "Price: $price";
echo "</br>";
echo "Author";
if ($numResults > 1)
{
echo "s:";
for ($i = 0; $i < $numResults; $i++)
{
if ($i!=0)
echo ", $authorArray[i]";
else
echo $authorArrat[i];
}
}
else
echo ": $firstName, $lastName";
echo "</br>";
echo "Publisher: $publisher";
echo "</br>";
echo "Edition: $edition ($publishDate)";
echo "</br>";
echo "Length: $length pages";
echo "</br>";
echo "ISBN-13: $isbn";
?>
</td>
</tr>
<tr>
<td colspan="2">
<?php echo "Description: $desc"; ?>
</td>
</tr>
</table>
</body>
</html>
You should be using isset not is_null to keep it from warning about undefined variables.
$books is never defined It was defined, just incorrectly ... foreach needs it to be an array. You really don't need it anyway, fetch each row into the array with a while loop. (see my example below). You're also redefining $count several times in your query.
And like #Brad said. Use prepared statements and placeholders. Your database will end up hacked with your current code.
EDIT
Answer to your question. query() returns a statement handle. (I've defined it as $sth). fetch() returns a result which you need to pass one of the fetch mode constants (or define it by default earlier with $db->setFetchMode())
To get the books you need to have
$books = array();
$sth = $db->query($query);
while( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
$books[] = $row; // appends each row to the array
}
Here's how your code should look to get a count.
// you're not using the $query2 you defined ... just remove it
$sth = $db->query("SELECT Count(*) As 'totalRecords' FROM book");
$result = $sth->fetch(PDO::FETCH_ASSOC);
$count = $result['totalRecords'];
Take a look at:
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers Looks like a good guide to give you an in-depth understanding of how to use PDO. Pay special attention to error handling and to prepared statements!