Ive been trying to get this to work but I dont think my sql is setup correctly.
For instance I am trying to get a search word from the URL and then insert it using prepared statements so that its safe to use in the database.
First I call the userid of the products they own from the sessions.
Then I check if they have more than 1 item, if they do I setup an array and insert into database, if they do not have more than 1 item then I just simply insert into database to retrieve data.
The reason why I am setting it into variables is because its being sent to the pagination class so it will paginate the results.
Here is the header of the html:
<?php
$searchword = $urlmaker->geturlandsearch($_GET["search"]);
$findcomma = strpos($_SESSION["SESS_USERSPRODUCTIDS"], ",");
if($findcomma == true){
$userproductid = explode(',', $_SESSION["SESS_USERSPRODUCTIDS"]);
$prep = array(':like' => "%$searchword%", ':like2' => "%$searchword%");
$q = '';
$e = '';
$i = 1;
foreach($userproductid as $productid){
$q .= 'productid=:productid' . $i . ' || ';
$prep[":productid{$i}"] = $productid;
$i++;
}
$q = rtrim($q, " || ");
} else {
$q = 'productid=:productid';
$prep = array(':productid' => $_SESSION["SESS_USERSPRODUCTIDS"], ':like' => "%$searchword%", ':like2' => "%$searchword%");
}
$maxlimit = 15;
$geturi = "/Search-Forum/" . $_GET['search'] . "/";
$string = "SELECT id,title,date,username,viewcount,replycount,replyuser,replydate FROM forum_topics WHERE " . $q . " AND title LIKE :like OR content like :like2 ORDER BY replydate DESC";
$pagstring = "SELECT id FROM forum_topics WHERE " . $q . " AND title LIKE :like OR content like :like2";
$pagurl = $geturi;
Here is the frontend code:
<?php
$topicQuery = $pagination->paginatedQuery($pdo, $string, $maxlimit, $prep);
if($topicQuery != "no query"){
while($fetchquery = $topicQuery->fetch()) {
$topicid = stripslashes($fetchquery["id"]);
$topictitle = stripslashes($fetchquery["title"]);
$topicdate = stripslashes($fetchquery["date"]);
$topicusername = stripslashes($fetchquery["username"]);
$topicviewcount = stripslashes($fetchquery["viewcount"]);
$topicreplycount = stripslashes($fetchquery["replycount"]);
$topicreplyuser = stripslashes($fetchquery["replyuser"]);
$topicreplydate = stripslashes($fetchquery["replydate"]);
?>
<li>
<div class="topiclisttitle"><p><b><?php echo ucwords($topictitle); ?></b><br><?php echo $topicusername ; ?> on <?php echo $betterTime->dateAndtime($topicdate); ?></p></div>
<div class="topiclistview"><p><b><?php echo $topicviewcount ; ?></b><br>Views</p></div>
<div class="topiclistview"><p><b><?php echo $topicreplycount ; ?></b><br>Replies</p></div>
<div class="topiclistlastposted"><?php if(!empty($topicreplyuser)){ ?><p>By: <b><?php echo $topicreplyuser ; ?></b> On<br><?php echo $betterTime->dateAndtime($topicreplydate); ?></p><?php } else { ?><p>By: <b><?php echo $topicusername ; ?></b> On<br><?php echo $betterTime->dateAndtime($topicreplydate); ?></p><?php } ?></div>
</li>
<?php } } else { ?>
<li><p class="morepadding">No Topics Regarding Your Search Words :(</p></li>
<?php } ?>
Here is the database input on the pagination class:
$freebiesquery = $pdo->prepare($string . " LIMIT " . $maxlimit);
$freebiesquery->execute($prep);
$freebiesquery_num = $freebiesquery->rowCount();
All this works on other pages so it has to be the way Im doing the header section of the code, the way im formating the sql query in the first place.
The only errors I am getting are as follows:
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number
And
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number
But this cant be as I have counted thema and they are the same?
Putting strings containing => into an array doesn't make associations. => is part of the syntax of array literals, they have to be outside the strings.
Replace:
$prep[] = "':productid{$i}' => {$productid}";
with:
$prep[":productid{$i}"] = $productid};
Replace:
$e = "':productid' =>" . $_SESSION["SESS_USERSPRODUCTIDS"];
With:
$prep = array(':productid' => $_SESSION["SESS_USERSPRODUCTIDS"]);
Replace:
$prep = array($e, ':like' => "%$searchword%", ':like2' => "%$searchword%");
with:
$prep[':like'] = "%$searchword%";
$prep[':like2'] = "%$searchword%";
Related
i want to produce an array in this format [x,x,x] where each x is grouped by the addition of each retail id, however, for an empty array list, i want to have [x,x,0] assuming the third array is empty, instead of [x,x]
Below is my code
<?php
$q = "SELECT DISTINCT outletid FROM " . TBL_SALES_LOGS;
$result = $database->query($q);
$outlets = [];
?>
data: [<?php
while ($row = $result->fetch_assoc()) {
// $outletname = $row['title'];
$outlet_id = $row['outletid'];
$outlets[] = $row['outletid'];
$amount = $row['amount'];
?>
<?php echo $outlet_id; ?>,
<?php } ?> ]
data: [<?php
$outlet = implode("','", $outlets);
$qsum3 = "SELECT outletid, SUM(amount) AS totalsum FROM " . TBL_SALES_LOGS . " WHERE outletid IN ('{$outlet}') and fueltype='PMS' group by `outletid`";
$qresult3 = $database->query($qsum3);
while ($rowq3 = $qresult3->fetch_assoc()) {
$tot3 = $rowq3['totalsum'];
?>'<?php echo $tot3; ?>',<?php } ?>]
instead of having [3,4,2,3] and missing value not showing, i want to have [3,4,2,0,3] for the missing values, assuming 0 is the missing values
thanks
I have made a few changes. Mostly created a key value array depending on the id as the key, and setting all those values to sum => 0. Then, when you loop through all of the id and their sum's it changes the sum of the id's it finds.
It is untested, but should solve it. You may need to change the end. It was messy with all the opening and closing php tags.
<?php
$q = "SELECT DISTINCT outletid FROM " . TBL_SALES_LOGS;
$result = $database->query($q);
$outlets = [];
$outletsIdSum = [];
?>
data: [<?php
while ($row = $result->fetch_assoc()) {
// $outletname = $row['title'];
$outlet_id = $row['outletid'];
$outlets[] = $outlet_id;
$outletsIdSum[(int)$outlet_id] = 0;
$amount = $row['amount'];
?>
<?php echo $outlet_id; ?>,
<?php } ?> ]
data: [<?php
$outlet = implode("','", $outlets);
$qsum3 = "SELECT outletid, SUM(amount) AS totalsum FROM " . TBL_SALES_LOGS . " WHERE outletid IN ('{$outlet}') and fueltype='PMS' group by `outletid`";
$qresult3 = $database->query($qsum3);
while ($rowq3 = $qresult3->fetch_assoc()) {
$outletsIdSum[(int)$rowq3['outletid']] = $rowq3['totalsum'];
}
echo "'" . implode( "','", $outletsIdSum );
?>]
add if condition on array
<?php
foreach(some_array as a)
{
if(a=="" or a==NULL)
a=0;
}
?>
this will check array element which is empty and then ,if it is empty it will assign array element to '0'
use this algorithm
I have two columns in my database, year and content i want to group the content by year (i have a lot of content and many years not only 2015 and 2016 as the example )
so i'll have this output in html
<div class="all">
<div class="2016">
2016
<div class="content_2016">
All the content of the column that is in the same ligne as 2016 in the database
</div>
</div>
<div class="2015">
2015
<div class="content_2015">
All the content of the column that is in the same ligne as 2015 in the database
</div>
</div>
</div>
<?php
$query = "SELECT * FROM publi where pub_type=0 order by pub_year DESC, pub_publi ";
$result = mysqli_query($connection, $query);
$previous =0;
while ($val = mysqli_fetch_array($result))
{
if ($previous <> $val['pub_year'])
{
$previous = $val['pub_year'];
$year = $previous;
echo $year;
echo '<br>';
$Temp = highlight("person1",$val['pub_publi'],"0000FF");
$Temp = highlight("person2",$Temp,"0000FF");
$Temp = highlight("person3",$Temp,"0000FF");
$Temp = highlight("person4",$Temp,"0000FF");
$Temp = highlight("person5",$Temp,"0000FF");
$Temp = highlight("person6",$Temp,"0000FF");
$Temp = highlight("person7",$Temp,"0000FF");
$Temp = highlight("person8",$Temp,"0000FF");
$Temp = highlight("person9",$Temp,"0000FF");
$Temp = highlight("person10",$Temp,"0000FF");
echo '<a target=blank href="http://www.test.com/query.f?term=' . $val['pub_pubmed'] . '";)><img border="0" src="img/test.gif" align=MIDDLE alt="Search in for ' . $val['pub_publi'] . '"></a>';
echo $Temp;
echo '<br>';
}
}
?>
It is outputing the years right
2016
2015
2014
etc...
but it is only showing the first ligne of each year not all the content for each year.
Run the following query:
Select Content From table order by year
echo like following (or concat):
while rs.hasNext(){
if (currentYear != lastyear){
echo div #with year As Class;
}
echo row # a single entry the way you want it dispalyed;
lastYear = currentYear;
}
what u are asking is huge chunk to write. so here are steps:
create array with this SQL statement below and fetch assoc in PHP
select distinct on year * from table
now use foreach($years as $year) on array and fetch content
select content from table where year=$year
to sandwich your code output in SQL keep concatenating like
$html = "";
$html .= "<div class=\"all\">";
foreach($years as $year){
$html .= "<div class=\"content_$year\">";
//then content fetched from second sql query
$html .= "</div>";
}
$html .= "</div>";
how to fetch data in sql | PHP.NET MANUAL
how to join/concat in php | PHP.NET MANUAL
LATER ADDITIONS, SNIPPET FROM MY OWN CODE :
$letter = $_POST['letter'];
$query_out = "SELECT link_id,singer_url FROM letter_mapping WHERE letter = '$letter'";
if($result_out = $conn_out->query($query_out)){
if($result_out->num_rows > 0){
while($row = $result_out->fetch_assoc()) {
$link_id = $row['link_id'];
$singer_url = $row['singer_url'];
/*
foreach($row as $name=>$value){
}
*/
}
}
$result_out->free();
}
if($conn_out->close()){
// Message for disconnect
//echo "Status : DISCONNECTED<br/>";
}
I'm looking to create a function to display prev-next buttons on the header of a one page site.
$query = "SELECT * FROM `issue` ORDER BY `issue_no` DESC LIMIT 1";
The content for the entire site comes off a primary key in the database titled "issue_no" everything inside issue_no is the content to be displayed on the one page.
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<article id='date_published'><p>Date published: " . $row['date_published'] . "</p></article>";
echo "<article id='article_head'>" . $row['article_head'] . "</article>";
echo "<article id='article_body'>" . $row['article_body'] . "</article>";
echo "<article id='vidpicks_embed'>" . $row['vidpick'] . "</article>";
echo "<article id='quote_body'>" . $row['quote_body'] . "—</article>";
echo "<article id='quote_auth'>" . $row['quote_auth'] . "</article>";
echo "<article id='wotd_body'>" . $row['wotd_body'] . "</article>";
echo "<article id='wotd_desc'>" . $row['wotd_desc'] . "</article>";
}
}
This is displayed on index.php
Currently, it displays the latest issue pending on the publish date, but I would like to add the function to go back to previous and next editions.
On top of this, I'd like to rollout all issues inside a dropdown select menu that allows you to select say "Issue 23" and it would link you through to the appropriate content contained in that issue.
Also - how would I go about making sure these each have clean URLs?
e.g. http://www.example.com/issue/023
Any help much appreciated.
I've tried reading up on pagination, but I'm finding it a little complicated to wrap my head around this one.
Thanks.
You say:
On top of this, I'd like to rollout all issues inside a dropdown select menu that allows you to select say "Issue 23" and it would link you through to the appropriate content contained in that issue.
Assuming (for example) an URL like “http://www.example.com/issue.php?issue=23” (for now postponed the ‘clean’ URL question) you can resolve all questions in this way:
$issueId = $_GET['issue'];
/* 01: Retrieve ALL id */
$result = $con->query( "SELECT GROUP_CONCAT( `issue_no` ORDER BY `issue_no` DESC ) FROM `issue`" );
$allId = explode( ',', $result->fetch( PDO::FETCH_NUM )[0] );
/* 02: Check if $issueId exists and set previous/next id */
$prev = $next = False;
$found = array_search( $key, $allId );
if( $found === False ) $found = count( $allId )-1;
if( $found > 0 ) $prev = $allId[$found-1];
if( $found < count($allId)-1 ) $next = $allId[$found+1];
/* 03: Retrieve current issue: */
$result = $con->query( "SELECT * FROM `issue` WHERE `issue_no` = '{$allId[$found]}'" );
$row = $result->fetch_assoc();
/* 04: Output previous/next page link: */
if( $prev !== False ) echo "Prev Page";
else echo "<span class=\"inactive\">Prev Page</span>";
if( $next !== False ) echo "Next Page";
else echo "<span class=\"inactive\">Next Page</span>";
// Your code from here
Code above is only as example. By this way, all issue_no are stored in $allId variable, so you can easy implement also the dropdown menu. The issue_no fields are retrieved in descending order, if you prefer ascending you can change first query (#01) in ORDER BY issue_no ASC.
Note that if the user don't ask for any specific issue (i.e. calling http://www.example.com/issue.php), the current issue is set to first array value of $allId (#02): if you prefer to produce an alert like “This issue doesn't exists” you have to modify the script in this way:
$found = array_search( $key, $allId );
if( $found === False )
{
// Your error routine here
}
else
{
if( $found > 0 ) $prev = $allId[$found-1];
(...)
}
In the output of previous/next page URLs (#04), I use a basic <a href> tag, but you can use buttons.
Clean URLs
I strongly recommend to produce first a full working code ignoring the ‘clean’ URL question. Then, all you will need to change will be only one row.
By the way, to activate clean urls, you have to modify the .htaccess file of your site in a way like this:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^issue/.*$ /issue.php [NC,L]
</IfModule>
then, in your issue.php script, you have to change $issueId = $_GET['issue']; with:
$issueId = array_pop( explode( '/', $_SERVER['REQUEST_URI'] ) );
This RewriteRule is only an example, actually I think you are interested in clean URLs for all your site, so the best solution can be to redirect all incoming URLs to a redirect.php that process the REQUEST_URI and include appropriate page or echoes ‘Not Found’ message.
Here you can find more about basics on RewriteRule
These code I haven't tested, not stable at all. You have to optimize it.
Function to get data
In PHP:
<?php
$issueno = $_GET["issueno"];
if($issueno == null){
$issueno = 0;
}
$servername = "localhost";
$username = "username";
$password = "password";
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM `issue` ORDER BY `issue_no` DESC LIMIT " + $issueno + ",1";
if($row = mysqli->query($query, MYSQLI_USE_RESULT))
{
/* row is the row selected */
echo "<article id='date_published'><p>Date published: " . $row['date_published'] . "</p></article>";
echo "<article id='article_head'>" . $row['article_head'] . "</article>";
echo "<article id='article_body'>" . $row['article_body'] . "</article>";
echo "<article id='vidpicks_embed'>" . $row['vidpick'] . "</article>";
echo "<article id='quote_body'>" . $row['quote_body'] . "—</article>";
echo "<article id='quote_auth'>" . $row['quote_auth'] . "</article>";
echo "<article id='wotd_body'>" . $row['wotd_body'] . "</article>";
echo "<article id='wotd_desc'>" . $row['wotd_desc'] . "</article>";
}else{
echo "It does not exist";
}
$mysqli->close();
?>
NEXT
In Javascript, by redirecting with a issueno parameter
function next(){
var currentissueno = getQueryVariable("issueno");
if (currentissueno == null){
//Added 1 here as NEXT
currentissueno = 0;
}
//Maximum issues No. OutOfBounds not handled... I have to sleep now
currentissueno++;
//Redirect (should use window.location.href instead of static url)
//window.location = window.location.href + "?issueno=" + currentissueno;
window.location = "http://www.example.com/index.php?issueno=" + currentissueno;
}
PREVIOUS
In Javascript, by redirecting with a issueno parameter
function prev(){
var currentissueno = getQueryVariable("issueno");
if (currentissueno == null){
alert("The last previous page");
return;
}
currentissueno--;
//Redirect (should use window.location.href instead of static url)
//window.location = window.location.href + "?issueno=" + currentissueno;
window.location = "http://www.example.com/index.php?issueno=" + currentissueno;
}
Function to GET url parameter
Required. From Using the GET parameter of a URL in JavaScript
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return null;
}
I have a bootstrap based website with 2 columns(col-lg-6 and col-lg-6).
I have the ability to add text from an admin panel (articles).
How can I make it so it splits in the second div (col-lg-6) after a specific number of characters or after I insert a character or something that will represent the breakage?
I prefer a PHP solution, but Javascript/Jquery would do too
edit *
if(isset($_GET['chapter']) && !empty($_GET['chapter'])){
$chapterid = (int)$_GET['chapter'];
$chaptertitle = mysql_query("SELECT bookname FROM books WHERE id=$chapterid");
$chaptertitle = mysql_fetch_array($chaptertitle);
$chaptertitle = $chaptertitle[0];
$chapter = mysql_query("SELECT bookContent FROM books WHERE id=$chapterid");
$chapter = mysql_fetch_array($chapter);
$chapter = $chapter[0];
$bookcontent = mysql_query("SELECT * FROM books WHERE bookid=$id");
$bookcontainer = '';
while($row = mysql_fetch_array($bookcontent)){
$bookcontainer .= '<h2>'.$row['bookname'].'</h2>' . $row['bookContent'];
}
and this is the place where the code is printed
<div class="row">
<div class="col-lg-6" id="paragraphs">
<div style="width:100%;">
<?php
//if($errors == false){
echo $chapter;
//}
//else{
//echo 'erorr madarfaker';
//}
?>
</div>
</div>
<div class="col-lg-6"></div>
</div>
If anyone is interested in this: I made 2 fields in the admin panel and the variable that was being sent to the database was "field 1 + ' | ' + field 2" and then I used explode to display the content on 2 sides, separator being " | "
Choose an arbitrary character for your split, like "|". Based on your posted code, use this as your echo statement:
echo str_replace($chapter, "|", "</div></div><div class='col-lg-6' id='paragraphs'><div style='width:100%;'>");
I am not sure if this solves your problem, but you can try :
<?php
// An array with your database data :
$arr = array('val1', 'val2', 'val3', 'val4');
$col1 = "";
$col2 = "";
$flag=false;
for($i=0; $i<sizeof($arr); $i++){
//Break condition :
$flag = ($arr[$i] == "val3" || $flag != true ) ? true : false;
if(!$flag){
$col1 .= $arr[$i];
}
else{
$col2 .= $arr[$i];
}
}
$html = "";
if($col1 != ""){
$html .= "<div class='col-lg-6'>".$col1."</div>";
}
if($col2 != ""){
$html .= "<div class='col-lg-6'>".$col2."</div>";
}
// The two div with your content (if the break rule is found) :
echo $html;
?>
If anyone is interested in this: I made 2 fields in the admin panel and the variable that was being sent to the database was "field 1 + ' | ' + field 2" and then I used explode to display the content on 2 sides, separator being " | "
I am having trouble with modifying a php application to have pagination. My error seems to be with my logic, and I am not clear exactly what I am doing incorrectly. I have had before, but am not currently getting errors that mysql_num_rows() not valid result resource
and that invalid arguments were supplied to foreach. I think there is a problem in my logic which is stopping the results from mysql from being returned.
All my "test" echos are output except testing while loop. A page is generated with the name of the query and the word auctions, and first and previous links, but not the next and last links. I would be grateful if a more efficient way of generating links for the rows in my table could be pointed out, instead of making a link per cell. Is it possible to have a continuous link for several items?
<?php
if (isset($_GET["cmd"]))
$cmd = $_GET["cmd"]; else
die("You should have a 'cmd' parameter in your URL");
$query ='';
if (isset($_GET["query"])) {
$query = $_GET["query"];
}
if (isset($_GET["pg"]))
{
$pg = $_GET["pg"];
}
else $pg = 1;
$con = mysql_connect("localhost","user","password");
echo "test connection<p>";
if(!$con) {
die('Connection failed because of' .mysql_error());
}
mysql_query('SET NAMES utf8');
mysql_select_db("database",$con);
if($cmd=="GetRecordSet"){
echo "test in loop<p>";
$table = 'SaleS';
$page_rows = 10;
$max = 'limit ' .($pg - 1) * $page_rows .',' .$page_rows;
$rows = getRowsByProductSearch($query, $table, $max);
echo "test after query<p>";
$numRows = mysql_num_rows($rows);
$last = ceil($rows/$page_rows);
if ($pg < 1) {
$pg = 1;
} elseif ($pg > $last) {
$pg = $last;
}
echo 'html stuff <p>';
foreach ($rows as $row) {
echo "test foreach <p>";
$pk = $row['Product_NO'];
echo '<tr>' . "\n";
echo '<td>'.$row['USERNAME'].'</td>' . "\n";
echo '<td>'.$row['shortDate'].'</td>' . "\n";
echo '<td>'.$row['Product_NAME'].'</td>' . "\n";
echo '</tr>' . "\n";
}
if ($pg == 1) {
} else {
echo " <a href='{$_SERVER['PHP_SELF']}?pg=1'> <<-First</a> ";
echo " ";
$previous = $pg-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pg=$previous'> <-Previous</a> ";
}
echo "---------------------------";
if ($pg == $last) {
} else {
$next = $pg+1;
echo " <a href='{$_SERVER['PHP_SELF']}?pg=$next'>Next -></a> ";
echo " ";
echo " <a href='{$_SERVER['PHP_SELF']}?pg=$last'>Last ->></a> ";
}
echo "</table>\n";
}
echo "</div>";
function getRowsByProductSearch($searchString, $table, $max) {
$searchString = mysql_real_escape_string($searchString);
$result = mysql_query("SELECT Product_NO, USERNAME, ACCESSSTARTS, Product_NAME, date_format(mycolumn, '%d %m %Y') as shortDate FROM {$table} WHERE upper(Product_NAME) LIKE '%" . $searchString . "%'" . $max);
if($result === false) {
echo mysql_error();
}
$rows = array();
while($row = mysql_fetch_assoc($result)) {
echo "test while <p>";
$rows[] = $row;
}
return $rows;
mysql_free_result($result);
}
edit: I have printed out the mysql error of which there was none. However 8 "test whiles" are printed out, from a database with over 100 records. The foreach loop is never entereded, and I am unsure why.
The problem (or at least one of them) is in the code that reads:
$rows = getRowsByProductSearch($query, $table, $max);
$numRows = mysql_num_rows($rows);
The $numRows variable is not a MySQL resultset, it is just a normal array returned by getRowsByProductSearch.
Change the code to read:
$rows = getRowsByProductSearch($query, $table, $max);
$numRows = count($rows);
Then it should at least find some results for you.
Good luck, James
Hi there,
The next problem is with the line that reads:
$last = ceil($rows/$page_rows);
It should be changed to read:
$last = ceil($numRows / $page_rows);
Would recommend adding the following lines to the start of you script at least while debugging:
ini_set('error_reporting', E_ALL | E_STRICT);
ini_set('display_errors', 'On');
As that would have thrown up a fatal error and saved you a whole lot of time.
if (!(isset($pg))) {
$pg = 1;
}
How is $pg going to get set? You don't appear to be reading it from $_GET. If you're relying on register_globals: don't do that! Try to read it from $_GET and parse it to a positive integer, falling back to '1' if that fails.
<a href='{$_SERVER['PHP_SELF']}?pg=$next'>Next -></a>
You appear to be losing the other parameters your page needs, 'query' and 'cmd'.
In general I'm finding it very difficult to read your code, especially the indentation-free use of echo(). Also you have untold HTML/script-injection vulnerabilities every time you "...$template..." or .concatenate a string into HTML without htmlspecialchars()ing it.
PHP is a templating language: use it, don't fight it! For example:
<?php
// Define this to allow us to output HTML-escaped strings painlessly
//
function h($s) {
echo(htmlspecialchars($s), ENT_QUOTES);
}
// Get path to self with parameters other than page number
//
$myurl= $_SERVER['PHP_SELF'].'?cmd='.urlencode($cmd).'&query='.urlencode($query);
?>
<div id="tableheader" class="tableheader">
<h1><?php h($query) ?> Sales</h1>
</div>
<div id="tablecontent" class="tablecontent">
<table border="0" width="100%"> <!-- width, border, cell width maybe better done in CSS -->
<tr>
<td width="15%">Seller ID</td>
<td width="10%">Start Date</td>
<td width="75%">Description</td>
</tr>
<?php foreach ($rows as $row) { ?>
<tr id="row-<?php h($row['Product_NO']) ?>" onclick="updateByPk('Layer2', this.id.split('-')[1]);">
<td><?php h($row['USERNAME']); ?></td>
<td><?php h($row['shortDate']); ?></td>
<td><?php h($row['Product_NAME']); ?></td>
</tr>
<?php } ?>
</table>
</div>
<div class="pagercontrols">
<?php if ($pg>1) ?>
<<- First
<?php } ?>
<?php if ($pg>2) ?>
<-- Previous
<?php } ?>
<?php if ($pg<$last-1) ?>
Next -->
<?php } ?>
<?php if ($pg<$last) ?>
Last ->>
<?php } ?>
</div>
Is it possible to have a continuous link for several items?
Across cells, no. But you're not really using a link anyway - those '#' anchors don't go anywhere. The example above puts the onclick on the table row instead. What exactly is more appropriate for accessibility depends on what exactly your application is trying to do.
(Above also assumes that the PK is actually numeric, as other characters may not be valid to put in an 'id'. You might also want to consider remove the inline "onclick" and moving the code to a script below - see "unobtrusive scripting".)
This is wrong:
if($cmd=="GetRecordSet")
echo "test in loop\n"; {
It should be:
if($cmd=="GetRecordSet") {
echo "test in loop\n";
In your getRowsByProductSearch function, you return the result of mysql_error if it occurs. In order to debug the code, maybe you can print it instead, so you can easily see what the problem is.