PHP Performing a persistent DB check - php

I'm actually trying to create a ( more or less ) instant chat.
There's just one thing left to go, until it's finished. And that's a DB check for new entries every second by PHP itself.
A while loop works great for it, because i can exit it perfectly.
The Problem is, that the "every second" thing isn't working.
I tried a sleep(1), but that causes a 1 minute server freeze, until the script has been completed.
Hope someone can help me, i'm actually frustrated about this problem.
elseif($latestID != 'undefined' && $_POST['returnafter'] == '60')
{
$timeout = '60';
$i = '0';
while ($i != $timeout)
{
$chat_content = "";
$i++;
$getLastID = mysql_query("SELECT id, userid, content, time_posted FROM (SELECT * FROM chat_system ORDER BY id DESC LIMIT 150) chat_system WHERE id > '" . $latestID . "' $extraQuery ORDER BY id ASC");
while ($lastID = mysql_fetch_object($getLastID))
{
$rowID = $lastID->id;
$user_posted_id = $lastID->userid;
$chat_content = $lastID->content;
$chat_posted = $lastID->time_posted;
$getUserData = mysql_query("SELECT username, avatar, loggedIn FROM account_data WHERE account_id=('" . $user_posted_id . "')");
while ($userData = mysql_fetch_object($getUserData))
{
$username = $userData->username;
$useravatar = $userData->avatar;
$loginStatus = $userData->loggedIn;
}
if ($loginStatus == '1')
{
$onlineStatus = '<img src="./images/3DArt/newOnline.png" class="chat_onlineStatus">';
}
else
{
$onlineStatus = '<img src="./images/3DArt/newOffline.png" class="chat_onlineStatus">';
}
if (date('Y-m-d', $chat_posted) == date('Y-m-d'))
{
$time_posted = strftime('Heute, %H:%M', $chat_posted);
}
elseif (date('Y-m-d', $chat_posted) == date('Y-m-d', strtotime("Yesterday")))
{
$time_posted = strftime('Gestern, %H:%M', $chat_posted);
}
elseif (date('Y-m-d', $chat_posted) < date('Y-m-d', strtotime("Yesterday")))
{
$time_posted = strftime("%A, %d %B %Y %H:%M", $chat_posted);
}
if (isset($_POST['parseEmoticons']) && $_POST['parseEmoticons'] == 'true')
{
$chat_content = emoticons($chat_content);
}
$newChatRow.= '<div class="chatRow" id="' . $rowID . '">
<div class="chatRow_container">
<div><img src="' . $useravatar . '" class="chatAvatar">' . $onlineStatus . '<b>' . $username . '</b>
</div>
</div>' . $modActions . '
<div class="chat_mainMsg">
' . $chat_content . '
</div>
<div class="chatTime">' . $time_posted . '</div>
</div>';
}
$content = str_replace(array(
'\r\n',
'\r',
'\n'
) , "<br />", $newChatRow);
if(!empty($chat_content)) { echo $newChatRow; $i = $timeout; return false; }
if(empty($chat_content)) { sleep(1); return true; }
}
}
I think, this informations should be enough. If not, just ask.
EDIT: The request is initialized by Ajax and on success the request repeats.
That's why PHP have to check for 60 seconds.

you should let the clientside decide what messages it "like" to receive.
eg you call your messages.php class - per ajax on the client side and pass a timestamp when the last time was the script requested new messages
example:
ajax interval with 1 second loop call the messages.php?last=123456 and receive all messages that were created after or equal this timestamp. now you update in javascript the last timestamp and so on.
or you use a perfect framework (if possible) that is designed perfectly for your task to solve this.
http://socket.io/ (or js keyword websockets)

Related

How do I create a prev/next function for a one page display site?

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;
}

After ajax request php function not receiving variables

I'm developing a searcher and I made a function that gets the data from a db, saves each ad in a variable and saves pagination (from another function) in another variable, so they can be returned in an array to be printed in the html later.
It works like this: you hit a buy or rent button and you go to the search page (/search?do?=buy/rent) then you have to select the property type, optionally a city/zone and hit search. Ajax sends the data via post (to search.php, the same file), hides the first container and shows the second container that has the list of properties with a pagination at the end of the page.
These are the main variables and a script to hide/show containers:
$mode = filter_input(INPUT_GET, 'do', FILTER_SANITIZE_STRING); // buy or rent
$prop_type = filter_input(INPUT_POST, 'prop_type', FILTER_SANITIZE_STRING); // res or com AJAX
$city = filter_input(INPUT_POST, 'city', FILTER_SANITIZE_NUMBER_INT); // AJAX
$zone = filter_input(INPUT_POST, 'zone', FILTER_SANITIZE_NUMBER_INT); // AJAX
$page_number = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_NUMBER_INT);
if (isset($page_number) && $page_number >= 1) {
$cont1 = 'display: none;';
$cont2 = NULL;
// need a way to get the prop_type (the checked checkbox before changing the page) without using $_GET.
} else {
$cont1 = NULL;
$cont2 = 'display: none;';
}
This is the function:
function get_prop_data($prop_type, $city, $zone, $page_number, $table, $targetpage) {
if ($prop_type == 'res') {
$table2 = 'res_prop';
} else if ($prop_type == 'com') {
$table2 = 'com_prop';
}
if ($city != 0) {
$optional_cond = ' WHERE t2.city = ' . $city;
$optional_cond2 = NULL;
if ($zone != 0) {
$optional_cond2 = ' AND t2.zone = ' . $zone;
}
} else $optional_cond = $optional_cond2 = NULL;
$mysqli = new mysqli('127.0.0.1', 'db', '123456', 'name');
// pagination
if ($stmt = $mysqli->prepare('SELECT COUNT(id) FROM ' . $table)) {
$stmt->execute();
$stmt->bind_result($totalitems);
$stmt->fetch();
if (!isset($page)) {
$page = (int)$page_number <= 0 ? 1 : (int)$page_number;
}
$limit = 4;
if ($page > ceil($totalitems / $limit)) {
$page = ceil($totalitems / $limit);
}
$start = ($page - 1) * $limit;
$stmt->close();
if ($stmt = $mysqli->prepare(' SELECT t1.id, t2.*
FROM ' . $table . ' t1
INNER JOIN ' . $table2 . ' t2 ON t2.id = t1.id
' . $optional_cond . $optional_cond2 . '
LIMIT ?, ?')) {
$stmt->bind_param('ii', $start, $limit);
$stmt->execute();
$stmt->bind_result($id, $id, $type, $status, $bhk, $baths, $area1, $area2, $age, $description, $price, $city, $zone, $img1, $img2, $img3, $img4);
$test = "";
while ($row = $stmt->fetch()) {
if ($status === 0) {
$possesion = 'En construcción';
} else if ($status === 1 || $status === 2) {
$possesion = 'Inmediata';
} else $possesion = 'Desconocida';
if ($prop_type == 'res') {
$is_res = '<p><span class="bath">Bed</span>: <span class="two">' . $bhk . ' BHK</span></p>
<p><span class="bath1">Baths</span>: <span class="two">' . $baths . '</span></p>';
} else $is_res = NULL;
$test .= '<div class="box-col">
<div class="col-sm-6 left-side ">
<img class="img-responsive" src="' . $img1 . '" alt="">
</div>
<div class="col-sm-6 middle-side">
<h4>Disponibilidad: ' . $possesion . '</h4>
' . $is_res . '
<p><span class="bath2">Built-up Area</span>: <span class="two">' . $area1 . ' m²</span></p>
<p><span class="bath3">Plot Area</span>: <span class="two">' . $area2 . ' m²</span></p>
<p><span class="bath4">Age of property</span>: <span class="two">' . $age . ' Year(s)</span></p>
<p><span class="bath5">Price</span>: <span class="two">' . $price . ' €</span></p>
<div class="right-side">
Contact Builder
</div>
</div>
<div class="clearfix"> </div>
</div>
';
$pagination = functions::getPaginationString($page, $totalitems, $limit, $adjacents = 1, $targetpage, $pagestring = "&page=");
}
} //else echo "Statement failed: " . $mysqli->error . "<br>";
} //else echo "Statement failed: " . $mysqli->error . "<br>";
return array($test, $pagination);
}
This is the main code:
if (empty($_GET)) {
echo 'under construction';
}
else if (isset($mode) && $mode == 'buy') {
$table = 'to_sell';
$targetpage = '/search?do=buy';;
if (isset($prop_type)) {
$data = get_prop_data($prop_type, $city, $zone, $page_number, $table, $targetpage);
$test = $data[0];
$pagination = $data[1];
}
}
else if (isset($mode) && $mode == 'rent') {
$table = 'to_rent';
$targetpage = '/search?do=rent';;
if (isset($prop_type)) {
$data = get_prop_data($prop_type, $city, $zone, $page_number, $table, $targetpage);
$test = $data[0];
$pagination = $data[1];
}
}
else {
echo 'invalid url';
}
This is the AJAX script that sends the checkbox value via post (it's not working correctly, I don't get an undefined error in $prop_type (I don't know why???) but I get it in $table2, that it's inside the if ($prop_type == '')):
$('.search, .pagination').click(function() { // search button and change page
if ($('#res_prop').is(':checked')) {
$prop_type = $('#res_prop').val();
}
else if ($('#com_prop').is(':checked')) {
$prop_type = $('#com_prop').val();
}
$.post('search.php', { // same file, maybe self
prop_type: $prop_type,
city: $('select[name=city]').val(), // optional
zone: $('select[name=zone]').val(), // option value="0" by default
success: function(){
$('.cont-1').hide();
$('.cont-2').show();
}
});
});
It works perfectly if I manually set $prop_type = 'res';. Any ideas?
Another problem is that the pagination buttons link does not work, it just triggers the ajax script (they need to send the data, otherwise the script will restart when changing pages).
I really would appreciate any optimization to the scripts. Thanks.
You're mixing your javascript and php here.
In PHP you declare a variable with $varname, in Javascript, $ represents the jQuery operator. As such your code that says $prop_type is totally invalid since this is javascript code. You're telling jQuery to execute some functionality called prop_type which doesn't exist, and as such you're getting an error that this is undefined.
if ($('#res_prop').is(':checked')) {
var prop_type = $('#res_prop').val();
}
else if ($('#com_prop').is(':checked')) {
var prop_type = $('#com_prop').val();
}
And change the line which reads prop_type: $prop_type, to prop_type: prop_type,
If you want to import the <div class="results"></div> container with ajax:
you should use this tested and working code:
$(document).ready(function(){
$('.search, .pagination').click(function() { // search button and change page
$prop_type = '';
if ($('#res_prop').is(':checked')) {
$prop_type = $('#res_prop').val();
}
else if ($('#com_prop').is(':checked')) {
$prop_type = $('#com_prop').val();
}
$.ajax({
method: "POST",
url: "go.php",
data: {
'prop_type': $prop_type,
'city': $('select[name="city"]').val(),
'zone': $('select[name="zone"]').val()
}
}).done(function(data) {
var _html = $.parseHTML(data);
$('.cont-1').hide();
$('.cont-2').show();
$(_html).each(function(i, el) {
if (el.className == 'results') {
$('.results').html($(el).html());
};
});
});
return false;
});
});

Trying to send star ratings from krajee bootstrap star rating to mysql database

I am using the following plugin
http://plugins.krajee.com/star-rating
I'm trying to send the rating submitted to the database but the values are not being recorded.
require_once $doc_root . '/includes/act_initiate_article_xref.php';
$rating_value = (#$user_article_xref_row['rating'] > 0) ? $user_article_xref_row['rating'] . ' stars' : 'unrated';
$article_rating = '<span class="line-sep">Rated:</span> ' . $rating_value;
if ($_SESSION['user_id'] == 1 || $_SESSION['user_id'] == 41) {
$rating_value_attr = (isset ($user_article_xref_row['rating'])) ? ' value="' . $user_article_xref_row['rating'] . '"' : '';
$article_rating .= '<span class="line-sep">Your rating: </span> <input id="input-21d" type="number" class="rating"' . $rating_value_attr . ' data-min=0 data-max=5 step=0.5 data-size="xs">';
}
and the code for act_initiate_article_xref.php
<?
/**
* reads user_article_xref
*/
$this_routine[] = "includes/act_initiate_article_xref.php";
/**
* no direct access allowed
*/
$doc_root = $_SERVER['DOCUMENT_ROOT'];
require_once $doc_root . '/includes/act_check_valid_access.php';
$table_title = 'user_article_xref';
$user_id = (isset ($_SESSION['user_id'])) ? $_SESSION['user_id'] : 0;
$fields = '`id`, `hits`, `rating`';
$match_where = '`user_id` = ' . $user_id . ' and `article_id` = ' . $article_id;
$article_result = $db->selectByStrings($fields, $table_title, $match_where, null, 1);
#if ($_SESSION['user_id'] == 1) { echo "<br>21. select $fields from $table_title where $match_where<pre>";print_r($_SESSION);echo "</pre>"; }
/**
* if there is already a record, update it
* if there isn't already a record, insert it
* either way, $user_article_xref_row holds details for any ajax rating update
*/
if ($db->getNumRows($article_result) > 0) {
$user_article_xref_row = $db->getNextRow($article_result);
$hits = $user_article_xref_row['hits'] + 1;
$pairs_array = array ('hits' => $hits);
$id_where = '`id` = ' . $user_article_xref_row['id'];
$update_result = $db->updateByArray($table_title, $pairs_array, $id_where);
$test = 'update';
} else {
$hits = 1;
$user_article_xref_row = array ('user_id' => $user_id, 'article_id' => $article_id, 'hits' => $hits);
$insert_result = $db->insertByArray($table_title, $user_article_xref_row);
$test = 'insert';
}
#if ($_SESSION['user_id'] == 1) { echo "<br>37. $test<pre>";print_r($user_article_xref_row);echo "</pre>"; }
?>
I know this post is a little old but just in case. In the star-rating.js I added an ajax post to my php file to the set.listenClick function. Hope this helps.
self.listenClick(self.$rating, function(e) {
if (self.inactive) {
return false;
}
pos = self.getPosition(e);
var div_id = self.$element.attr('id');
self.setStars(pos);
self.$element.trigger('change').trigger('rating.change', [self.$element.val(), self.$caption.html()]);
self.starClicked = true;
var rating = self.$element.val();
$.ajax({
type:"POST",
url:"rating.php",
data:"div="+div_id+"&rating="+rating,
success: function(res){
console.log("Rating was posted " + div_id + rating);
return res;
}
});
});

Using PHP to show "Next" an "Previous" in pagination

I am using the following code:
$result = mysql_query("SELECT * FROM table LEFT JOIN table2
ON table.field = table2.field WHERE ( table.field = '$pid' )
AND ( table.field5 LIKE '%$q%' OR table.field3 LIKE '%$q%'
OR table2.field2 LIKE '%$q%' )");
if (empty($what)) {
$countpls = "0";
} else {
$countpls = mysql_num_rows($result);
}
<?php
if ($countpls > 10) {
echo '<a id=pgnvg href="' . $_SERVER['PHP_SELF'] . '?pg=' . ($startrow + 20) . '&q=' . ($what) . '">Next</a>';
} else {
echo "";
}
$prev = $startrow - 20;
//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0) {
echo '<a id=pgnvg2 href="' . $_SERVER['PHP_SELF'] . '?pg=' . $prev . '&q=' . ($what) . '">Previous</a>';
} else {
echo "";
}
?>
I want the next to show only if there are more entries to show and previous only if there are more entries to circle back to. It works on the first page bt then on the last page Next shows despite teh fact that there are no more results to show.
I tried adding the 'else' but its still not working.
Any ideas?
if($countpls > 0){
$pg = $_POST['pg']?$_POST['pg']:1;
//if it's not the first page...
if($pg>1){
echo '<a id="pgnvg" href="'.$_SERVER['PHP_SELF'].'?pg='.($pg-1).'&q='.$what.'">Previous</a>';
}
//if you have more registers to show...
if(($countpls-(($pg-1)*10))>10){
echo '<a id="pgnvg" href="'.$_SERVER['PHP_SELF'].'?pg='.($pg+1).'&q='.$what.'">Next</a>';
}
}
In order to calculate your offset to use in queries, use this:
$offset = ($_POST['pg']-1)*10;
It would help if you would provide the code that's setting $countpls. That might be the part that's causing the problem. Also, the else's are unnecessary. However, try this:
if($countpls - $startrow > 20)
{
echo '<a id=pgnvg href="'.$_SERVER['PHP_SELF'].'?pg='.($startrow+20).'&q='.($what).'">Next</a>';
}
I think it would do you good if you followed a tutorial to grasp the basic concepts. It even comes with the example that could either 1.) replace your current pagination or 2.) fix it.
http://www.phpfreaks.com/tutorial/basic-pagination

PHP looped data will not echo outside the while function OR how can I pass looped data by echoing out of the while function?

I have a loop of data that will only echo the loop inside the while function, but if i call/echo the looped data outside the while function, it only runs the 1st loop.
SAMPLE:
$num = mysql_num_rows($queryFromDB);
$i=0;
while($i < $num)
{
$field1= mysql_result($queryFromDB,$i,"field1");
$field2= mysql_result($queryFromDB,$i,"field2");
$bothFields = $field1 . " " . $field2 "\n";
// This will show 2 rows of data
echo $bothFields;
$i++;
// This will only show 1 row of data. How can I pass the looped data to another variable?
echo $bothFields;
}
The output that I wanted to show is:
TITLE/HEADER GOES HERE in the 1st Line
-1st Row of Data from DB
-2nd Row of Data from DB
Here's the actual code:
$num = mysql_num_rows($qWoundAssessment);
$i=0;
while ($i < $num)
{
$wndType = mysql_result($qWoundAssessment,$i,"wndType");
$wndNum = mysql_result($qWoundAssessment,$i,"wndNum");
$wndLocation = mysql_result($qWoundAssessment,$i,"wndLocation");
$wndStage = mysql_result($qWoundAssessment,$i,"wndStage");
$wndL = mysql_result($qWoundAssessment,$i,"wndL");
$wndD = mysql_result($qWoundAssessment,$i,"wndD");
$wndW = mysql_result($qWoundAssessment,$i,"wndW");
$wndAseptic = mysql_result($qWoundAssessment,$i,"wndAseptic");
$wndIrrigate = mysql_result($qWoundAssessment,$i,"wndIrrigate");
$wndIrrigateBox = mysql_result($qWoundAssessment,$i,"wndIrrigateBox");
$wndPat = mysql_result($qWoundAssessment,$i,"wndPat");
$wndCover = mysql_result($qWoundAssessment,$i,"wndCover");
$wndCoverBox = mysql_result($qWoundAssessment,$i,"wndCoverBox");
$wndSecure = mysql_result($qWoundAssessment,$i,"wndSecure");
$wndSecureBox = mysql_result($qWoundAssessment,$i,"wndSecureBox");
$wndQvisit = mysql_result($qWoundAssessment,$i,"wndQvisit");
$wnd = "-" . $wndType . " " . "#" . $wndNum . ", " . "LOCATION " . $wndLocation . ", " . "STAGE " . $wndStage;
$wndSize = "SIZE " . $wndL . "CM" . " X " . $wndW . "CM" . " X " . $wndD;
if($wndAseptic=="1"){$wndAsepticTech = "USING ASEPTIC TECHNIQUE";}
if($wndIrrigate=="1"){$wndIrrigateWith = "IRRIGATE WITH " . $wndIrrigateBox;}
if($wndPat=="1"){$wndPatDry = "PAT DRY";}
if($wndCover=="1"){$wndCoverWith = "COVER WITH " . $wndCoverBox;}
if($wndSecure=="1"){$wndSecureWith = "COVER WITH " . $wndSecureBox;}
if($wndQvisit=="1"){$wndQv = "Q VISIT";}
if(isset($wnd, $wndSize, $wndAsepticTech, $wndIrrigateWith, $wndPatDry, $wndCoverWith, $wndSecureWith, $wndQv)){
$woundCare = implode(", ",array($wnd, $wndSize, $wndAsepticTech, $wndIrrigateWith, $wndPatDry, $wndCoverWith, $wndSecureWith, $wndQv)) . "\n\n ";}
$wndCare .= $woundCare;
$i++;
}
$snWoundCare = "SN TO PROVIDE SKILLED NURSING VISITS FOR WOUND CARE:" . "\n" . $wndCare;
if I echo $wndCare, it shows the "Undefined variable" error with the actual looped data. But if I pass this variable to PDF, it works.
SN TO PROVIDE SKILLED NURSING VISITS FOR WOUND CARE:
-PRESSURE ULCER #1, LOCATION COCCYX, 3, SIZE 2.0CM X 1.5CM X 0.07, USING ASEPTIC TECHNIQUE, IRRIGATE WITH NORMAL SALINE, PAT DRY, COVER WITH AQUACEL AG, COVER WITH MEPILEX BORDER, Q VISIT
-SURGICAL WOUND #2, LOCATION (R) KNEE, , SIZE 29CM X 0CM X 0, USING ASEPTIC TECHNIQUE, IRRIGATE WITH NORMAL SALINE, PAT DRY, COVER WITH AQUACEL AG, COVER WITH MEPILEX BORDER, Q VISIT
================ CODE NOW WORKS!!! HERE's MY FINAL SOLUTION ======================
$num = mysql_num_rows($qWoundAssessment);
$i=0;
$storeMyData = array();
while($i < $num)
{
$wnd= "-" . mysql_result($qWoundAssessment,$i,"wndType") . " #" . mysql_result($qWoundAssessment,$i,"wndNum"). ", LOCATION " . mysql_result($qWoundAssessment,$i,"wndLocation") . ", STAGE " . mysql_result($qWoundAssessment,$i,"wndStage");
$wndSize = "SIZE " . mysql_result($qWoundAssessment,$i,"wndL") . "CM" . " X " . mysql_result($qWoundAssessment,$i,"wndW") . "CM" . " X " . mysql_result($qWoundAssessment,$i,"wndD") . "CM";
if(isset($rowWoundAssessment['wndAseptic'])){$wndAsepticTech = "USING ASEPTIC TECHNIQUE";}
if(isset($rowWoundAssessment['wndIrrigate'])){$wndIrrigateWith = "IRRIGATE WITH " . mysql_result($qWoundAssessment,$i,"wndIrrigateBox");}
if(isset($rowWoundAssessment['wndPat'])){$wndPatDry = "PAT DRY";}
if(isset($rowWoundAssessment['wndCover'])){$wndCoverWith = "COVER WITH " . mysql_result($qWoundAssessment,$i,"wndCoverBox");}
if(isset($rowWoundAssessment['wndSecure'])){$wndSecureWith = "SECURE WITH " . mysql_result($qWoundAssessment,$i,"wndSecureBox");}
if(isset($rowWoundAssessment['wndQvisit'])){$wndQvisit = "Q VISIT";}
$wndCare = implode (", ", array($wnd, $wndSize, $wndAsepticTech, $wndIrrigateWith, $wndPatDry, $wndCoverWith, $wndSecureWith, $wndQvisit)). "\n\n";
// This will show 2 rows of data
$storeMyData[] = $wndCare ; // store current data in array
$i++;
}
/* this will echo your storedData of loop */
foreach($storeMyData as $prevData)
/* or join the data using string concatenation /
$allFinalData2 = "";
/ this will echo your storedData of loop */
foreach($storeMyData as $prevData)
{
$allFinalData2 = $allFinalData2.$prevData ; // keep on concatenating
}
echo "SN TO PROVIDE SKILLED NURSING VISITS FOR WOUND CARE:" . "\n" . $allFinalData2;
thanks to DhruvPathak and Antonio Laguna! You guys are the best! Just made my day! jumps around the room
This should work:
<?php
$wndCare = '';
while ($row = mysql_fetch_assoc($qWoundAssessment)){
$wnd = '-'.$row['wndType'].' #'..$row['wndNum'].', LOCATION '.$row['wndLocation'].', STAGE '.$row['wndStage'];
$wndSize = 'SIZE '.$row['wndL'].'CM X '.$row['wndW'].'CM X '.$row['wndD'];
$wndAsepticTech = ($row['wndAseptic'] == 1) ? 'USING ASEPTIC TECHNIQUE' : '';
$wndIrrigateWith = ($row['wndIrrigate'] == 1) ? 'IRRIGATE WITH '.$row['wndIrrigateBox'] : '';
$wndPatDry = ($row['wndPat'] == 1) ? 'PAT DRY' : '';
$wndCoverWith = ($row['wndCover'] == 1) ? 'COVER WITH'.$row['wndCoverBox'] : '';
$wndSecureWith = ($row['wndSecure'] == 1) ? 'COVER WITH'.$row['wndSecureBox'] : '';
$wndSecureWith = ($row['wndSecure'] == 1) ? 'COVER WITH'.$row['wndSecureBox'] : '';
$wndQvisit = ($row['wndQvisit'] == 1) ? 'Q VISIT' : '';
$wndCare .= implode (", ", array($wnd, $wndSize, $wndAsepticTech, $wndIrrigateWith, $wndPatDry, $wndCoverWith, $wndSecureWith, $wndQv)). '\n\n';
}
$snWoundCare = "SN TO PROVIDE SKILLED NURSING VISITS FOR WOUND CARE:" . "\n" . $wndCare;
?>
The issue I see is that you were testing if all variables where previously setted and this could make strange things as you were stablishing them sometimes and sometimes don't.
I am not sure what you want to do with your data. It seems you want to store
all the data to use it outside the loop, then this is the way to go :
<?php
$num = mysql_num_rows($queryFromDB);
$i=0;
$storeMyData = array();
while($i < $num)
{
$field1= mysql_result($queryFromDB,$i,"field1");
$field2= mysql_result($queryFromDB,$i,"field2");
$bothFields = $field1 . " " . $field2 "\n";
// This will show 2 rows of data
echo $bothFields;
$storeMyData[] = $bothFields ; // store current data in array
$i++;
}
/* this will echo your storedData of loop */
foreach($storeMyData as $prevData)
{
echo $prevData."\n";
}
?>
$allFinalData = implode("",$prevData); // implode will join all the data as string
echo $allFinalData."\n" ;
/* or join the data using string concatenation */
$allFinalData2 = "";
/* this will echo your storedData of loop */
foreach($storeMyData as $prevData)
{
$allFinalData2 = $allFinalData2.$prevData ; // keep on concatenating
}
echo $allFinalData2,"\n";
?>

Categories