Group PHP ODBC results with common dataset? - php

I'm using PHP to connect to and display data from an ODBC MS Access database. I'm able to display the necessary data with a select statement, but I'm failing to learn how to group this data based on another dataset.
Here is my code:
<?
$handle = odbc_connect("Potter","","");
$results = odbc_exec($handle, "SELECT DISTINCT prodModelNo, prodSubType, prodCAD FROM product WHERE prodType NOT LIKE 'Plus' AND prodType = 'Fire' AND prodCAD LIKE '%CAD Drawing%' GROUP BY prodSubType");
// Results List
odbc_fetch_row($results, 0);
while(odbc_fetch_row($results)){
$cadString1 = odbc_result($results, "prodCAD");
$cadString2 = str_replace('<img src=images/i_drawing.gif> <a href=fire/', '', $cadString1);
$cadURL = str_replace(' target=_blank>CAD Drawing (zip format)</a>', '', $cadString2);
echo "<div id='file'><div id='filelink'><ul><li><a href='$cadURL'><img src='../images/download.png'/> Download</a> (zip format)</li></ul></div>";
echo odbc_result($results, "prodModelNo");
echo "<div class='clear'></div></div>";
}
?>
This outputs a list of accurate data. What I'd like to do is group results that share a common category and have that category name displayed between each group. The column for category names in the database is called prodSubType.
How would I get this to display properly?

Instead of GROUP BY prodSubType use ORDER BY prodSubType - so you can grab all items.
Then, in your code, have a BEFORE and AFTER variable to output the header differences (I'm not good at explaining this). See example (untested):
<?php
$handle = odbc_connect("Potter","","");
$results = odbc_exec($handle, "SELECT DISTINCT prodModelNo, prodSubType, prodCAD FROM product WHERE prodType NOT LIKE 'Plus' AND prodType = 'Fire' AND prodCAD LIKE '%CAD Drawing%' ORDER BY prodSubType ASC");
// Results List
odbc_fetch_row($results, 0);
$oldHeader = "";
while(odbc_fetch_row($results)){
$header = odbc_result($results, "prodSubType");
if($header != $oldHeader) {
$oldHeader = $header;
echo "<h1>$header</h1>";
}
$cadString1 = odbc_result($results, "prodCAD");
$cadString2 = str_replace('<img src=images/i_drawing.gif> <a href=fire/', '', $cadString1);
$cadURL = str_replace(' target=_blank>CAD Drawing (zip format)</a>', '', $cadString2);
echo "<div id='file'><div id='filelink'><ul><li><a href='$cadURL'><img src='../images/download.png'/> Download</a> (zip format)</li></ul></div>";
echo odbc_result($results, "prodModelNo");
echo "<div class='clear'></div></div>";
}
?>

Related

How to display count results with multiple keywords anywhere in a database field

We have a page tcount.php where we fetch counts for BOTH keyword1 and keyword2 occuring anywhere in a text field in mysql database using php script. The counts are displayed as hyperlinks. Now after that, we want that if someone clicks on the hyperlinks, they will see the detailed results in showt.php page showing those rows of the database corresponding to only those text field containing BOTH keywords.
The url of the second page showt.php is like
http://www.example.com/page.php?keyword=keyword1+keyword2
But problem is that it shows only those results which have keyword1 and keyword2 next to each other.
For example, keyword1 is car and keyword2 is cap and our text fields are as follows -
car cap
car best cap
car new
Then, we want it to show 1. and 2. as results but it is showing only no. 1 in the results page.
Please help.
Edit -
This is the code in page 1 tcount.php -
$kewyWordQ = $db->query("SELECT keywords FROM Table1 ");
<?php
while($row = $kewyWordQ->fetch(PDO::FETCH_ASSOC))
{$keyWord = $row['keywords'];
$keyWordsArr = explode(" ", $row['keywords']);
$countData = array();
$keyIndex = 0;
$tIndices = array();
$tArr = array();
$tIndices[] = "-1";
foreach($keyWordsArr as $keyword)
{
$t = $db->query("SELECT user_name FROM Table2 WHERE
t_text LIKE '%$keyWordsArr[$keyIndex]%'");
$tArr[] = $t;
while($row2 = $tweet->fetch(PDO::FETCH_ASSOC))
{
$found = TRUE;
foreach($keyWordsArr as $keyword1)
{
$ret = strpos(strtolower($row2['t_text']),
strtolower($keyword1));
if(($ret == 0) &&
strcmp(strtolower($row2['t_text'][0], strtolower($keyword1)[0])))
{
$found = FALSE;
break;
}
}
if($found == TRUE)
{
$ret = strpos($tIndices, $row2['t_id']);
if(($ret == 0) && strcmp($tIndices[0],
$row2['t_id']))
{
$tIndices[] = $row2['t_id'];
$countData[] = $row2['user_name'];
}
}
}
$keyIndex++;
}
?>
<tr><td><?php echo $row['keywords'];?></td>
<td><a href="showt.php?keyword=<?php echo
urlencode($keyWord); ?>" target="_blank"><?php echo count($countData); ?
></a></td>
<td><a href="showt.php?keyword=<?php echo
urlencode($keyWord); ?>" target="_blank"><?php echo
count(array_unique($countData)); ?></a></td>
</tr>
<?php } ?>
And this is the code in page 2 showt.php -
$keywords = $_GET['keyword'];
$sql="SELECT col1, col2, col3 from t AS s INNER JOIN users AS p ON
s.user_name=p.user_name where s.t_text LIKE '%$keywords%'
The WHERE statement of your query should look like:
WHERE my_text_field LIKE ?
and the binded parameter should be %$keyword1%$keyword2%
In order to define the $keyword1 and $keyword2 variables you can do something like:
list($keyword1, $keyword2) = explode(' ', $_GET['keyword']);
or you can simply use "%" . implode('%', explode(' ', $_GET['keyword'])) . "%" in case you have multiple possible keywords
There is a two way
one is hard way doing by php and mysql
$keyword = $_GET('keyword');
$keywordArray = explode(" ",$keyword);
$queryString = "";
foreach($keywordArray as $key=>$value) {
$queryString .= " column_name LIKE '%$value%' OR";
}
"SElECT * FROM table WHERE ".$queryString
second is mysql itself, that is Full text search

Include files in PHP

Thank you for reading this and for your help in advance.
I got a simple Book-Catalogue /procedure code/, every visitor can see the book catalogue and click through out the books and check their authors BUT I've got an idea to add a feature that allows the users to write a comment to each book ONLY if they're logged. So I added a session variable $_SESSION['isLogged']. But there is a lot of code blocks that duplicates. What I need is an advice, what to do with this duplicated blocks of code. What the good practice says? And my code below is from one of the 6 files that I got. In everyfile I got this repeating of code.
So here's my code:
if (!isset($_SESSION['isLogged'])) {
echo '<div class="user-navigation">
<a href="register.php" class="user-nav" >Register now</a>
Log in
</div>
<div class="navigation1">
Add book
Add author
</div>';
$booksAndAuthors = mysqli_query($connection, 'SELECT DISTINCT * FROM books LEFT JOIN books_authors ON books.book_id=books_authors.book_id LEFT JOIN authors ON authors.author_id=books_authors.author_id');
$result = array();
while ($resultArr = mysqli_fetch_assoc($booksAndAuthors)) {
$result[$resultArr['book_id']] ['book_name'] = $resultArr['book_title']; // Reodering array
$result[$resultArr['book_id']] ['author'][$resultArr['author_id']] = $resultArr['author_name']; // Reordering array
}
echo '<table class="table"><tr><th>Book name</th><th>Author</th></tr>'; // Open table html table tags
foreach ($result as $k=>$b) { // Foreach the result array to get the book_name
echo '<tr><td>' . $b['book_name'] . '</td><td>';
$data = array(); // Create an empty array in order to fill the data inside
foreach ($b['author'] as $k => $a) { // Foreach the nested array with the authors to get the author_name displayed
$_GET['author_name'] = $a;
$data[] = '' . $a . ''; // Link is chosen by the author_id
}
echo implode(', ', $data); // Add a comma after every record
echo '</td></tr>'; // Close table cell and row
}
exit;
echo '</table>'; // Close html table tag
}
else {
echo '<div class="user-navigation">
My Profile
Log out
</div>
<div class="navigation2">
Add book
Add author
</div>';
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$booksAndAuthors = mysqli_query($connection, 'SELECT DISTINCT * FROM books LEFT JOIN books_authors ON books.book_id=books_authors.book_id LEFT JOIN authors ON authors.author_id=books_authors.author_id');
$result = array();
while ($resultArr = mysqli_fetch_assoc($booksAndAuthors)) {
$result[$resultArr['book_id']] ['book_name'] = $resultArr['book_title']; // Reodering array
$result[$resultArr['book_id']] ['author'][$resultArr['author_id']] = $resultArr['author_name']; // Reordering array
}
echo '<table class="table"><tr><th>Book name</th><th>Author</th></tr>'; // Open table html table tags
foreach ($result as $k=>$b) { // Foreach the result array to get the book_name
echo '<tr><td>' . $b['book_name'] . '</td><td>';
$data = array(); // Create an empty array in order to fill the data inside
foreach ($b['author'] as $k => $a) { // Foreach the nested array with the authors to get the author_name displayed
$_GET['author_name'] = $a;
$data[] = '' . $a . ''; // Link is chosen by the author_id
}
echo implode(', ', $data); // Add a comma after every record
echo '</td></tr>'; // Close table cell and row
}
echo '</table>'; // Close html table tag
}
*If my question is not properly asked or you have some notices.Please let me know!
* (=
Put this code in a file then include that file at the bottom of all of the pages.
For example put the code in isLogged.php
Then on each page where the code is duplicated replace it with:
include "isLogged.php";
include is what you're looking for.
You should create a file that contains your repeated code. functions.php for example.
Then call it with one of these methods.
include "functions.php"
http://php.net/manual/en/function.include.php
include_once("functions.php")
http://php.net/manual/en/function.include-once.php
require_once("functions.php")
http://php.net/manual/en/function.require-once.php
create a function of repeated block and call when it required or create a file with the set of repeated code and use any of include,include_once,require_once to add the file.for more detail see php manual for these functions.

Displaying Correct IDs for Items (for example images)[',1,2,3,']

I need to display Correct IDs for Items images.
I have two tables. One containing the id, title, text and image.
The first section references are correct:
<?php
$st = $dbh->query("SELECT * FROM `info` ");
$st->execute(array($_GET['media']));
foreach ($st as $post):
$title = $post['title'];
$image = $post['image'];
$id = $post['id']; ... ->
Where the result of the image is: example ,1, (LIKE as ',?,' etc)
Distal part of the code retrieves the image data in the second table, but not correctly according to the first reference.
$pi = $post['image'];
$statementUser = $dbh->prepare("SELECT source FROM media WHERE id LIKE ? ");
$statementUser->execute(array($pi));
$name=$statementUser->fetchColumn(0);
$path = $settings['cms']['media_path'];
# Presentation part:
echo "<img src='$name' />";
endforeach;
?>
According to these, database displays the picture, but as incorrect.
Can anyone help me to fix this issue?
Solution: We need, get a readable string.
Example Function:
function clean_item_str($string){
return preg_replace('/[^a-zA-Z0-9_]/', '', $string);
}

PHP - Loop and not loop at the same time from a join

I'm trying to display a company name from a company table, and then loop out news from another table. The two tables are joined. This means that: I want to just pick out one row from one table in the join, and loop out data from the other table in the join. Is this possible? My code below only display two out of three posts in the news table in my loop.
Thanks!
$sql = "SELECT
newID, newTitle, newSummary, newDate,
comID, comName, comImageThumb
FROM
tblNews a RIGHT JOIN tblCompanies b
ON a.newCompanyID = b.comID
ORDER BY newDate DESC";
// Get company name and display
$companyData = mysql_fetch_assoc($result);
$comName = $companyData['comName'];
echo "<a href='#' class='name'>$comName</a>";
// Looping news
while($news = mysql_fetch_assoc($result)) {
// Display news posts
$newTitle = $news['newTitle'];
echo $newTitle;
}
Put everything inside while loop and try :
while($news = mysql_fetch_assoc($result)) {
// Get company name and display
$comName = $news ['comName'];
echo "<a href='#' class='name'>$comName</a>";
// Looping news
// Display news posts
$newTitle[] = $news['newTitle'];
echo $newTitle;
}
You should look at mysql GROUP_CONCAT for more detail.
Easiest solution probably would be to keep track of whether you are in the first iteration:
// query company name and news entries here
$firstRow = true;
while($news = mysql_fetch_assoc($result)) {
if ($firstRow) { echo $news['comName']; }
$firstRow = false;
echo $news['newTitle'];
}
You could also keep your current code and use mysql_data_seek(0) to reset the cursor after extracting the company name first.
And on a side note: Don't use mysql_* functions anymore! Use PDO instead.
Move the fetch operation to the end of the loop:
$companyData = mysql_fetch_assoc($result);
$comName = $companyData['comName'];
echo "<a href='#' class='name'>$comName</a>";
// you've already fetched a news item....
$news=$companyData;
do {
$newTitle = $news['newTitle'];
echo $newTitle;
} while ($news=mysql_fetch_assoc($result));

Mystified about making a PHP double-query dynamic list work. Using PHP 5.3.5

I'm trying to create a dynamic list (5 row results) in php by first getting data from one table then using a resulting var to get the latest uploaded "image_links" (just 1 from each of the 5 artists) from another table -- then echo out.
The code here gives me the only one row with the latest image. When I comment out the "// get the latest image link uploaded ///" section of the code I get the 5 rows of different artists I really want but, of course, w/o images. I tried (among a bunch of things) mysql_result() w/o the while statement but that didn't work.
So what am I missing?
Thanks
Allen
//// first get the artists followed ////////////////
$QUERY= "SELECT * FROM followArtist WHERE user_id = $user_id ";
$res = mysql_query($QUERY);
$num = mysql_num_rows($res);
if($num>0){
while($row = mysql_fetch_array($res)){
$artist_name = $row['artist_name'];
$artist_id = $row['artist_id'];
$date_lastSent = $row['date_lastSent'];
$date_artPosted = $row['date_artPosted'];
$date_notePosted = $row['date_notePosted'];
//// get new notice data /////
if ($date_artPosted >= $date_lastSent) {
$artp = "new artwork posted";
}else{
$artp = "";
}
if ($date_notePosted >= $date_lastSent) {
$notep = "news/announcement posted";
}else{
$notep = "";
}
if ($artp!="" && $notep!="") {
$and = " and<br />";
}else{
$and = "";
}
if ($artp=="" && $notep=="") {
$no = "No new images or news posted since your<br /> last visit, but we'll let you know when there is.";
}else{
$no = "";
}
//////// get the latest image link uploaded ////////////////////////////////////
$QUERY2="SELECT image_link FROM artWork WHERE artist_id ='$artist_id' AND make_avail = '1' ";
//ORDER BY date_submit DESC
$res = mysql_query($QUERY2);
$num = mysql_num_rows($res);
if($num>0 ){
while($row = mysql_fetch_assoc($res)){
mysql_fetch_assoc($res);
$image_link= $row['image_link'];
}
//////// end of get the latest images uploaded ////////////////////////////////
echo "<tr align=\"center\" height=\"115px\">
<td align=\"left\" width=\"15%\"> <a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\">
<img src=slir/w115-h115/$path$image_link /></a></td>
<td align=\"center\" width=\"80%\"
<span class=\"deviceMedLtGrayFont\">$artist_name</span>
<br /><br />
<a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\"/>
$artp</a>
<a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\"/>
$and$no</a>
<a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\"/>
$notep</a>
</td>
</tr>";
} //// end bracket for getting latest image link
} ///loop end for getting followed artist data
} ///end: if ($num>0) clause<code>
If I read your code correctly, I see you looping using data from query1 in the control structure, and a lookup on query2 within each loop. You are reusing the variables in your loop1 control structure for query2 ($num and the query handle ($res)) for the second loop. Probably not desirable within the loop.
You're sharing the variables $num and $res between the two queries ... your original properties will be overwritten when the second query is run. Use different property names for the inner query.
Example of problem:
$result = QueryA();
while( $row = $result->getRow() )
{
// -- You're overwriting the original result here ...
$result = QueryB();
// Next time the loop runs, it will run using the result from QueryB();
}
So change ...
$res = mysql_query($QUERY2);
$num = mysql_num_rows($res);
if($num>0 )
{
while($row = mysql_fetch_assoc($res))
{
mysql_fetch_assoc($res);
$image_link= $row['image_link'];
}
to
$res2 = mysql_query($QUERY2);
$num2 = mysql_num_rows($res2);
if($num2 > 0)
{
while($row2 = mysql_fetch_assoc($res2))
{
$image_link= $row2['image_link'];
}
this is a mess - as others have said you're using the same variables for different purposes.
That you're storing integers which seem to represent enumerations in a char field is bad.
You're iterating through the second result set to find the last record (from an unsorted result set!).
You only need one query - not 2.
SELECT f.artist_name, f.artist_id, f.dateLastSent....
SUBSTR(
MAX(
CONCAT(DATE_FORMAT(date_submit, '%Y%m%d%H%i%s'), a.image_link)
), 15) as img_link
FROM followArtist f
LEFT JOIN artWork a
ON (a.artist_id=f.artist_id AND a.make_avail = '1')
WHERE user_id = $user_id
GROUP BY f.artist_name, f.artist_id, f.dateLastSent....

Categories