Select query executing twice - php

I'm writing a simple page to retrieve "PO Numbers" that belong to the logged-in user. That portion is working fine with the exception of the query returning 2 complete sets of records. I have checked for page refresh issues, as mentioned in other posts I've read, but none have been found.
poTable.php
<table class="table" style="width: 100%">
<thead class="thead-dark">
<tr>
<th scope="col">PO#</th>
<th scope="col">Job#</th>
<th scope="col">Job Name</th>
<th scope="col">Salesperson</th>
<th scope="col">Vendor</th>
<th scope="col">Date</th>
</tr>
</thead>
<tbody>
<?php include 'usersPOs.php'?>
</tbody>
</table>
usersPOs.php
$db = mysqli_connect('localhost', 'root', '', 'acs-jobs-pos');
$userID = $_SESSION['userID'];
$userPrivs = $_SESSION['admin'];
if ($userPrivs == 0) { // User IS NOT an admin
// Get ALL main table records that belong to the logged-in user
$sqlmain = "SELECT * FROM main INNER JOIN users ON main.userID = '" . $userID . "'";
//debug_print_backtrace();
$resultmain = mysqli_query($db,$sqlmain);
while($rowmain = mysqli_fetch_assoc($resultmain))
{
?>
<tr>
<?php
$PONumb = $rowmain["PONumb"];
$jobNumber = $rowmain["jobNumber"];
$jobName = $rowmain["jobName"];
$salespersonID = $rowmain["salespersonID"];
$vendorID = $rowmain["vendorID"];
$timestamp = $rowmain["timestamp"];
?>
<td><?php echo $PONumb ?></td>
<td><?php echo $jobNumber ?></td>
<td><?php echo $jobName ?></td>
<?php
$sqlsp = "SELECT * FROM users WHERE userID = '" . $salespersonID . "'";
$resultsp = mysqli_query($db,$sqlsp);
$rowsp = mysqli_fetch_assoc($resultsp);
if ($rowsp["lastname"] == '' && $rowsp["firstname"] == '') {
?>
<td></td>
<?php
} else {
?>
<td><?php echo $rowsp["lastname"] . ', ' . $rowsp["firstname"] ?></td>
<?php
}
$sqlvendor = "SELECT * FROM vendor
WHERE vendorID = '" . $vendorID . "'";
$resultvendor = mysqli_query($db,$sqlvendor);
$rowvendor = mysqli_fetch_assoc($resultvendor);
?>
<td><?php echo $rowvendor["vendorname"] ?></td>
<td><?php echo $timestamp ?></td>
</tr>
<?php
}
mysqli_close($db);
}

This code could be hugely simplified by use of joins. I'd also recommend using PDO for your database access; it's less verbose and makes prepared statements easier (and those are not optional in any environment.) Only relevant columns are selected from the database. A heredoc block is also used to simplify output.
<?php
$db = new PDO('mysql:host=localhost;dbname=acs-jobs-pos', 'root', '');
$userID = $_SESSION['userID'];
$userPrivs = $_SESSION['admin'];
if ($userPrivs == 0) {
$sql = "SELECT m.PONumb, m.jobNumber, m.jobName, m.salespersonID, m.vendorID, m.timestamp,
u.lastname, u.firstname, v.vendorname
FROM main m
LEFT JOIN users u ON (m.salespersonID = u.userID)
LEFT JOIN vendors v ON (m.vendorID = v.vendorID)
WHERE m.userID = ?";
$stmt = $db->prepare($sql);
$stmt->execute([$userID]);
$results = $stmt->fetchAll(\PDO::FETCH_ASSOC);
foreach ($results as $row) {
echo <<< HTML
<tr>
<td>$row[PONumb]</td>
<td>$row[jobNumber]</td>
<td>$row[jobName]</td>
<td>$row[lastname], $row[firstname]</td>
<td>$row[vendorname]</td>
<td>$row[timestamp]</td>
</tr>
HTML;
}
}

follow sql error
"SELECT * FROM main INNER JOIN users ON main.userID = '" . $userID . "'";
you can not use join as this, something like
"SELECT * FROM main INNER JOIN users ON main.userID = users.ID where users.ID='" . $userID . "'";

Related

Join two table with pdo

I'd like to join two tables in my database. It works fine the 'classic' way but there are a bunch of select query in my script, so I'd like to shorten it...
Here is the joint sql:
SELECT
matches.id, matches.start_time, matches.category_id,
matches.highl, first_team.tid, first_team.t_name,
second_team.tid, second_team.t_name AS ft_name
FROM matches
INNER JOIN teams AS first_team ON matches.first_team_id = first_team.tid
INNER JOIN teams AS second_team ON matches.second_team_id = second_team.tid
ORDER BY matches.id DESC
LIMIT 10
What I want to achive is something like this, but I don't exactly know how to add all the values I copied above.
public function getMatches($table,$conditions = array()){
$sql = 'SELECT ';
$sql .= array_key_exists("select",$conditions)?$conditions['select']:'';
$sql .= ' FROM '.$table;
if(array_key_exists("where",$conditions)){
$sql .= ' WHERE ';
$i = 0;
foreach($conditions['where'] as $key => $value){
$pre = ($i > 0)?' AND ':'';
$sql .= $pre.$key." = '".$value."'";
$i++;
}
}
if(array_key_exists("inner_join",$conditions)){
$sql .= ' INNER JOIN '.$conditions['inner_join'];
}
if(array_key_exists("on",$conditions)){
$sql .= ' ON '.$conditions['on'];
}
if(array_key_exists("as",$conditions)){
$sql .= ' AS '.$conditions['as'];
}
if(array_key_exists("order_by",$conditions)){
$sql .= ' ORDER BY '.$conditions['order_by'];
}
if(array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
$sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit'];
}elseif(!array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
$sql .= ' LIMIT '.$conditions['limit'];
}
$query = $this->db->prepare($sql);
$query->execute();
if(array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all'){
switch($conditions['return_type']){
case 'count':
$data = $query->rowCount();
break;
case 'single':
$data = $query->fetch(PDO::FETCH_ASSOC);
break;
default:
$data = '';
}
}else{
if($query->rowCount() > 0){
$data = $query->fetchAll();
}
}
return !empty($data)?$data:false;
}
}
Here is the output:
<div class="panel-heading">Matches</div>
<table class="table">
<tr>
<th>#</th>
<th>First Team</th>
<th>Second Team</th>
<th>Start Time</th>
</tr>
<?php
include 'inc/functions.php';
$db = new DB();
$matches = $db->getMatches('matches', array('inner_join'=>'teams'), array('as'=>'first_team'), array('on'=>'matches.first_team_id = first_team.tid'), array('inner_join'=>'teams'), array('as'=>'second_team'), array('on'=>'matches.second_team_id = second_team.tid'), array('order_by'=>'matches.id'));
if(!empty($matches)){ $count = 0; foreach($matches as $result){ $count++;?>
<tr>
<td><?php echo $count; ?></td>
<td><?php echo $result['ft_name']; ?></td>
<td><?php echo $result['t_name']; ?></td>
<td><?php echo $result['start_time']; ?></td>
</tr>
<?php } }else{ ?>
<tr><td colspan="4">No entry found!</td>
<?php } ?>
</table>
</div>
With all the honesty, for the life of me I will never ever ever understand, how such wall of PHP arrays
array('inner_join'=>'teams'), array('as'=>'first_team'),
array('on'=>'matches.first_team_id = first_team.tid'),
array('inner_join'=>'teams'),
array('as'=>'second_team'),
array('on'=>'matches.second_team_id = second_team.tid'),
array('order_by'=>'matches.id'));
can be even remotely considered "shorter" than elegant and compact SQL
SELECT
matches.id, matches.start_time, matches.category_id,
matches.highl, first_team.tid, first_team.t_name,
second_team.tid, second_team.t_name AS ft_name
FROM matches
INNER JOIN teams AS first_team ON matches.first_team_id = first_team.tid
INNER JOIN teams AS second_team ON matches.second_team_id = second_team.tid
ORDER BY matches.id DESC
LIMIT 10
Let alone the meaningfulness and readability.
Are you talking of saving yourself typing a few SQL keywords like SELECT or FROM? Seriously? Does it really worth making such a mess out of a meaningful and comprehensible SQL?

MySQL - Select row values from url ID

I created a table which is updated through a form and each row gets assigned a specific number.
When viewing this table, I want to click on that assigned number and get a page where all the details of that row are displayed.
If I do $sql = "SELECT * FROM clients WHERE nif_id='114522';"; - where the nif_id is the assigned number - I get the values for that number, but I need it to change with every number in the table.
Any ideas?
UPDATE
This is the table code:
<div class="card card-body">
<table class="table">
<thead>
<tr>
<th>NIF</th>
<th>Nome</th>
<th>Apelido</th>
<th>Telemóvel</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
<?php
include_once '../includes/db.inc.php';
$sql = "SELECT * FROM clients ORDER BY nif_id ASC;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$first = $row["prm_nome"];
$last = $row["apelido"];
$phone = $row['nmr_tlm'];
$email = $row['mail'];
$nif = $row['nif_id'];
echo '<tr>';
echo '<td>'.$nif.'</td>';
echo '<td>'.$first.'</td>';
echo '<td>'.$last.'</td>';
echo '<td>'.$phone.'</td>';
echo '<td>'.$email.'</td>';
echo '</tr>';
}
}
?>
</tbody>
</table>
</div>
You can use the get request parameters.
ex: www.myapp.com/table?id=3920393
add functionality in your PHP file as follows
if(isset($_GET["id"])){
$id = $_GET["id"];
$sql = "SELECT * FROM clients WHERE nif_id='".$id."';";
//make db call & display HTML
}
This is a very simple implementation and does not implement any security or SQL injection security. This was more of a conceptual answer as to how you can tackle your problem.
This is quite a common scenario for web-based systems.
<div class="card card-body">
<table class="table">
<thead>
<tr>
<th>NIF</th>
<th>Nome</th>
<th>Apelido</th>
<th>Telemóvel</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
<?php
include_once '../includes/db.inc.php';
$sql = "SELECT * FROM clients ORDER BY nif_id ASC;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$first = $row["prm_nome"];
$last = $row["apelido"];
$phone = $row['nmr_tlm'];
$email = $row['mail'];
$nif = $row['nif_id'];
echo '<tr>';
echo '<td>'.$nif.'</td>';
echo '<td>'.$first.'</td>';
echo '<td>'.$last.'</td>';
echo '<td>'.$phone.'</td>';
echo '<td>'.$email.'</td>';
echo '</tr>';
}
}
?>
</tbody>
</table>
</div>
where the detail.php is another page to query specific details regarding the query nifid.
As a reminder, if the data type of the column is INT, there is no need to use single quotes to surround the value in the SQL statement.
Sample detail.php:
<?php
if(!isset($_GET['nifid']) || (int)$_GET['nifid'] <= 0) {
// Invalid or missing NIFID
header('Location: table.php');
}
include_once '../includes/db.inc.php';
$id = (int)$_GET['nifid'];
$sql = "SELECT * FROM clients WHERE nif_id=$id";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
// TODO: display the result in whatever way you like
?>

Location of DIV that display MySQL within PHP file

Ok so I have this below page, it pulls back some details from a DB. The final line shows me how many rows I have with a certain state.
My issue I want to show this at the top of the page not the bottom, if I copy my last line to the top it doesnt count correctly and just shows 1 rather than 2 currently as it does at the bottom. Any ideas how I can include this final div at the top but have it dispaly the correct output?
Any help would be really useful.
<h2>All P1 Issues</h2>
<table class="table table-striped table-bordered table-head-bordered-bottom table-condensed">
<thead>
<tr>
<th class=span1>Ticket ID</th>
<th class=span2>Title</th>
<th class=span2>Submitter</th>
<th class=span2>Owner</th>
<th class=span2>Status</th>
<th class=span1>Created</th>
<th class=span1>Modified</th>
</tr>
</thead>
<tbody>
<?php
$query1 = "
SELECT HD_TICKET.ID as ID,
HD_TICKET.TITLE as Title,
HD_STATUS.NAME AS Status,
HD_PRIORITY.NAME AS Priority,
HD_TICKET.CREATED as Created,
HD_TICKET.MODIFIED as Modified,
S.FULL_NAME as Submitter,
O.FULL_NAME as Owner,
HD_TICKET.CUSTOM_FIELD_VALUE0 as Type
FROM HD_TICKET
JOIN HD_STATUS ON (HD_STATUS.ID = HD_TICKET.HD_STATUS_ID)
JOIN HD_PRIORITY ON (HD_PRIORITY.ID = HD_TICKET.HD_PRIORITY_ID)
LEFT JOIN USER S ON (S.ID = HD_TICKET.SUBMITTER_ID)
LEFT JOIN USER O ON (O.ID = HD_TICKET.OWNER_ID)
WHERE HD_TICKET.HD_QUEUE_ID IN( 1,3) AND
(HD_PRIORITY.NAME like '%High%') OR
(HD_STATUS.NAME like '%Critical%')
ORDER BY Owner, Created DESC
";
$result1 = mysql_query($query1);
$num = mysql_numrows($result1);
$i = 0;
while ($i < $num)
{
$ID = mysql_result($result1,$i,"ID");
$Title = mysql_result($result1,$i,"Title");
$Status = mysql_result($result1,$i,"Status");
$Type = mysql_result($result1,$i,"Type");
$Created = mysql_result($result1,$i,"Created");
$Modified = mysql_result($result1,$i,"Modified");
$Priority = mysql_result($result1,$i,"Priority");
$Owner = mysql_result($result1,$i,"Owner");
$Submitter = mysql_result($result1,$i,"Submitter");
$ID = stripslashes($ID);
$Title = stripslashes($Title);
$Status = stripslashes($Status);
$Type = stripslashes($Type);
$Created = stripslashes($Created);
$Modified = stripslashes($Modified);
$Priority = stripslashes($Priority);
$Owner = stripslashes($Owner);
$Submitter = stripslashes($Submitter);
$StatusSpan="";
if ($Status=="Stalled")
{
$StatusSpan="<span class='label label-warning'>$Status</span>";
}
$PriortySpan="";
if ($Priority=="High")
{
$PriortySpan="<span class='label label-important'><i class='icon-exclamation-sign icon-white'></i>High</span>";
}
if ($Priority=="Low")
{
$PriortySpan="<span class='label'>Low</span>";
}
if ($Priority=="Medium")
{
$PriortySpan="<span class='label'>Medium</span>";
}
if ($Priority=="Critical")
{
$PriortySpan="<span class='label'><i class='icon-exclamation-sign icon-white'></i>Critical</span>";
}
echo "<tr><td><a href='http://$KaceBoxDNS/adminui/ticket.php?ID=$ID' target='_blank'>$ID</a> $StatusSpan $PriortySpan</td> \n";
echo "<td>$Title</td> \n";
echo "<td>$Submitter</td> \n";
echo "<td>$Owner</td> \n";
echo "<td>$Status</td> \n";
echo "<td>$Created</td> \n";
echo "<td>$Modified</td> \n";
echo "</tr> \n";
$i++;
}
echo "<p><span class='label label-important'>$num P1 Issues</span></p>";
echo "</tbody></table> \n";
?>
<center><div class="alert alert-success" role="alert"><strong>No Current</strong><?php echo "<p><span class='label label-important'>$num P1 Issues</span></p>"; ?> Critical / High Priority Incidents</div></center>
You can hop in & out of PHP in an HTML code.
Below is an example of this.
Also in HTML you can use <br> or <br /> as /n is used in texts to break line. A last point: mysql* is deprecated, I'd advise using PDO instead, as it's great fun.
<?php
$query1 = "
SELECT HD_TICKET.ID as ID,
HD_TICKET.TITLE as Title,
HD_STATUS.NAME AS Status,
HD_PRIORITY.NAME AS Priority,
HD_TICKET.CREATED as Created,
HD_TICKET.MODIFIED as Modified,
S.FULL_NAME as Submitter,
O.FULL_NAME as Owner,
HD_TICKET.CUSTOM_FIELD_VALUE0 as Type
FROM HD_TICKET
JOIN HD_STATUS ON (HD_STATUS.ID = HD_TICKET.HD_STATUS_ID)
JOIN HD_PRIORITY ON (HD_PRIORITY.ID = HD_TICKET.HD_PRIORITY_ID)
LEFT JOIN USER S ON (S.ID = HD_TICKET.SUBMITTER_ID)
LEFT JOIN USER O ON (O.ID = HD_TICKET.OWNER_ID)
WHERE HD_TICKET.HD_QUEUE_ID IN( 1,3) AND
(HD_PRIORITY.NAME like '%High%') OR
(HD_STATUS.NAME like '%Critical%')
ORDER BY Owner, Created DESC
";
$result1 = mysql_query($query1);
$num = mysql_numrows($result1);
$i = 0;
while ($i < $num)
{
$ID = mysql_result($result1,$i,"ID");
$Title = mysql_result($result1,$i,"Title");
$Status = mysql_result($result1,$i,"Status");
$Type = mysql_result($result1,$i,"Type");
$Created = mysql_result($result1,$i,"Created");
$Modified = mysql_result($result1,$i,"Modified");
$Priority = mysql_result($result1,$i,"Priority");
$Owner = mysql_result($result1,$i,"Owner");
$Submitter = mysql_result($result1,$i,"Submitter");
$ID = stripslashes($ID);
$Title = stripslashes($Title);
$Status = stripslashes($Status);
$Type = stripslashes($Type);
$Created = stripslashes($Created);
$Modified = stripslashes($Modified);
$Priority = stripslashes($Priority);
$Owner = stripslashes($Owner);
$Submitter = stripslashes($Submitter);
$StatusSpan="";
if ($Status=="Stalled")
{
$StatusSpan="<span class='label label-warning'>$Status</span>";
}
$PriortySpan="";
if ($Priority=="High")
{
$PriortySpan="<span class='label label-important'><i class='icon-exclamation-sign icon-white'></i>High</span>";
}
if ($Priority=="Low")
{
$PriortySpan="<span class='label'>Low</span>";
}
if ($Priority=="Medium")
{
$PriortySpan="<span class='label'>Medium</span>";
}
if ($Priority=="Critical")
{
$PriortySpan="<span class='label'><i class='icon-exclamation-sign icon-white'> </i>Critical</span>";
}
?>
<h2>All P1 Issues</h2>
<table class="table table-striped table-bordered table-head-bordered-bottom table-condensed">
<thead>
<tr>
<th class=span1>Ticket ID</th>
<th class=span2>Title</th>
<th class=span2>Submitter</th>
<th class=span2>Owner</th>
<th class=span2>Status</th>
<th class=span1>Created</th>
<th class=span1>Modified</th>
</tr>
</thead>
<?php
/* THIS IS THE IMPORTANT PART FOR YOUR STUFF */
echo "<tr><td><a href='http://$KaceBoxDNS/adminui/ticket.php?ID=$ID' target='_blank'>$ID</a> $StatusSpan $PriortySpan</td> \n";
echo "<td>$Title</td><br>";
echo "<td>$Submitter</td><br>";
echo "<td>$Owner</td><br>";
echo "<td>$Status</td><br>";
echo "<td>$Created</td><br>";
echo "<td>$Modified</td><br>";
echo "</tr> \n";
$i++;
}
?>
<tbody>
<?php
echo "<p><span class='label label-important'>$num P1 Issues</span></p>";
echo "</tbody></table><br>";
?>
<center><div class="alert alert-success" role="alert"><strong>No Current</strong><?php echo "<p><span class='label label-important'>$num P1 Issues</span></p>"; ?> Critical / High Priority Incidents</div></center>

PHP MySQL undefined Index and other errors

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!

two sql queries in one place

<?php
$results = mysql_query("SELECT * FROM ".TBL_SUB_RESULTS."
WHERE user_submitted != '$_SESSION[username]' AND home_user = '$_SESSION[username]' OR away_user =
'$_SESSION[username]' ") ;
$num_rows = mysql_num_rows($results);
if ($num_rows > 0)
{
while( $row = mysql_fetch_assoc($results))
{
extract($row);
$q = mysql_query("SELECT name FROM ".TBL_FRIENDLY." WHERE id = '$ccompid'");
while( $row = mysql_fetch_assoc($q))
{
extract($row);
?>
<table cellspacing="10" style='border: 1px dotted' width="300" bgcolor="#eeeeee">
<tr>
<td><b><? echo $name; ?></b></td>
</tr><tr>
<td width="100"><? echo $home_user; ?></td>
<td width="50"><? echo $home_score; ?></td>
<td>-</td>
<td width="50"><? echo $away_score; ?></td>
<td width="100"><? echo $away_user; ?></td>
</tr><tr>
<td colspan="2">Accept / Decline</td>
</tr></table><br>
<?
}
}
}
else
{
echo "<b>You currently have no results awaiting confirmation</b>";
}
?>
I am trying to run two queries as you can see.
But they aren't both working.
Is there a better way to structure this, I am having a brain freeze!
Thanks
OOOH by the way, my SQL wont stay in this form!
I will protect it afterwards
SELECT *
FROM TBL_SUB_RESULTS ts
LEFT JOIN
TBL_FRIENDLY tf
ON tf.id = ts.ccompid
WHERE ts.user_submitted != '$_SESSION[username]'
AND ts.home_user = '$_SESSION[username]' OR ts.away_user = '$_SESSION[username]'
For debuging purposes, try to print your queries to the sceen. Check if you find any errors in your final query. You might just have misspelled a variable name.
<?php
$query = "SELECT * FROM ".TBL_SUB_RESULTS." WHERE user_submitted != '$_SESSION[username]' AND home_user = '$_SESSION[username]' OR away_user = '$_SESSION[username]'";
echo "query: ".$query;
$results = mysql_query($query);
// rest of code...
I think you need brackets in your WHERE clause:
WHERE user_submitted != '$_SESSION[username]'
AND (home_user = '$_SESSION[username]'
OR away_user = '$_SESSION[username]')

Categories