Pulling mySQL data and placing inside a variable in PHP - php

I'm trying out something like below. I get to successfully display the $Message without the PHP script that you see in the middle.
$Message = "<table><tr><td>" <?php code A ?>"</td></tr></table>";
The "Code A" PHP script meant to pull some date from an SQL database and present inside a table as you would see.
I see with this code not working, the issue is the way I place the PHP script inside $Message.
Would like to know, first is this really possible to have a script running attempting to pull data from an mySQL database and assign the output to a variable and if so how should the script look like otherwise?
Here's the full code which represent Code A, if that helps in understanding the issue better.
<?php
if(!isset($_POST['savedata']))
{
echo 'some text message';
}
else
{
include ('dbconnect/index.php');
$SQLuserpw="SELECT * FROM USER WHERE EMAIL = '".htmlspecialchars($email)."'";
$user=mysqli_query($conn, $SQLuserpw) or die ('SQL Error');
$pendingRow=mysqli_num_rows($user);
if($pendingRow == '')
{ echo 'some text here';} else
{
while ($reK = mysqli_fetch_array($user))
{
$wec = $reK['FNAME']; $wec2 = $reK['LNAME']; $wec3 = $reK['EMAIL'];
echo '<table>';
echo '<tr><td>First Name</td><td> : </td><td>'.$reK['FNAME'].'</td></tr>';
echo '<tr><td>Last Name</td><td> : </td><td>'.$reK['LNAME'].'</td></tr>';
echo '<tr><td>Email</td><td> : </td><td>'.$reK['EMAIL'].'</td></tr>';
}
echo '</table>';
}
}
?>
UPDATE
Suggestion made by #ADyson works.

if the code piece you've shared is working, do it like that,
$message = '<table>';
$message .= '<tr><td>First Name</td><td> : </td><td>'.$reK['FNAME'].'</td></tr>';
$message .= '<tr><td>Last Name</td><td> : </td><td>'.$reK['LNAME'].'</td></tr>';
$message .= '<tr><td>Email</td><td> : </td><td>'.$reK['EMAIL'].'</td></tr>';
}
$message.= '</table>';
the use $message wherever you want.

Related

SQL Query PHP, populate content quickly

Not sure I worded the title correctly, I'm unsure of what this is called.
I have a while loop which is populated by an SQL query
while($row = $result->fetch_assoc()){
$Tchannel = $row['chan'];
echo '<img src="https://static-cdn.jtvnw.net/previews-ttv/live_user_'.$Tchannel.'-320x180.jpg" alt="Thumbnail"><br />';
echo '<p>';
}
My problem is that when the page loads it does it in sections. I've seen other websites populate these straight away on page load. How would I replicate something like this?
See Example: http://puu.sh/oTh6v/73446c0c15.jpg
Could this be what you meant to achieve...? And by the way, the opening Paragraph Tag:< p > could contribute to some unexpected &/or sluggish behaviour since it was just opened without being closed anywhere in your code... I commented it out... You may try to see if it helps....
<?php
// CREATE A STRING VARIABLE TO HOLD THE ENTIRE OUTPUT TILL YOU ARE READY TO RENDER IT TO THE STREAM...
$strOutput = "";
while($row = $result->fetch_assoc()){
$Tchannel = $row['chan'];
$strOutput .= '<img src="https://static-cdn.jtvnw.net/previews-ttv/live_user_' . $Tchannel . '-320x180.jpg" alt="Thumbnail"><br />';
// WHY DO YOU NEED THIS OPENING PARAGRAPH TAG? WHERE IS IT CLOSED IN YOUR CODE?
//echo '<p>';
}
// RENDER THE OUTPUT
echo $strOutput;
?
If you need the images wrapped in paragraph tags, you can do it differently:
<?php
// CREATE A STRING VARIABLE TO HOLD THE ENTIRE OUTPUT TILL YOU ARE READY TO RENDER IT TO THE STREAM...
$strOutput = "";
while($row = $result->fetch_assoc()){
$Tchannel = $row['chan'];
$strOutput .= '<p>'; // <== OPEN A PARAGRAPH
$strOutput .= '<img src="https://static-cdn.jtvnw.net/previews-ttv/live_user_' . $Tchannel . '-320x180.jpg" alt="Thumbnail"><br />';
$strOutput .= '</p>'; // <== CLOSE THE PARAGRAPH
// OR ALL IN ONE LINE:
// $strOutput .= '<p><img src="https://static-cdn.jtvnw.net/previews-ttv/live_user_' . $Tchannel . '-320x180.jpg" alt="Thumbnail"><br /></p>';
}
// RENDER THE OUTPUT
echo $strOutput;
?>

get id in url form ajax call php

I need the id in url to make a mysql_query. The problem is that I need to make this from an Ajax call and $_GET['id'] apparently is not working.
Is there an easy way to free myself from this?
Thank you :)
Here is my ajax call:
echo "<div id='loading_utilizadores' class='loading'><img src='".$CONF['HOME']."/images/structure/ajax-loader.gif'/></div>";
echo "<div id='utilizadores'></div>";
echo "<script type='text/javascript'>";
echo "CarregaAjax(\"#utilizadores\",\"#loading_utilizadores\",\"".$CONF['HOME']."/superadmin/box_utilizadores_ajax.php\", \"GET\")";
echo "</script>";
The ajax function:
function CarregaAjax(id,loading,page,method){
if(method=="GET"){
$(document).ready(function(){
//$(loading).ajaxStart(function(){
$(loading).show();
$(id).hide();
//});
$(id).load(page);
$(loading).ajaxStop(function(){
$(loading).hide();
$(id).show();
});
});
}
else{
$(document).ready(function(){
//$(method).submit(function() {
$(loading).show();
$(id).load(page,$(method).serializeArray());
$(loading).hide();
return false;
//});
});
}
And the peace of html ajax call. In this page I try to make the $_GET['id'], but with no success.
if (isset($_GET['id']))
{
$officeID = intval($_GET['id']);
}
else
{
$officeID = 0;
}
if(!isset($crm_users))$crm_users = new crm_utilizadores;
//$officeID = 12;
$resultGetUsers = $crm_users->getUsersByOfficeId($officeID);
$html = "<table class='table1' width='100%' cellpadding='5' cellspacing='1' border='0'>";
if(!empty($resultGetUsers)){
$html .= "<tr>";
$html .= "<td class='table_title1'>Utilizador</td>";
$html .= "<td class='table_title1'>Telefone</td>";
$html .= "<td class='table_title1'>Telemóvel</td>";
$html .= "<td class='table_title1'>E-mail</td>";
$html .= "<td class='table_title1'>Situação</td>";
$html .= "</tr>";
}else{
$html .= "<tr><td class='empty1'>não foram encontrados utilizadores registados neste cliente</td></tr>";
}
//finalizar a tabela
$html .= "</table>";
I guess I'm mising the point, right? :p
This code attempts to read the id value from the URL:
$_GET['id']
But this is the URL you're requesting:
/superadmin/box_utilizadores_ajax.php
As you can see, there is no id value (or any other value). That would look something like this instead:
/superadmin/box_utilizadores_ajax.php?id=123
The value has to be on the URL in order for $_GET to read it.
Now, the page you're currently viewing may have that value in the URL you previously requested. But the server-side code isn't looking at your screen or interacting with your web browser. All it knows is the request that you send it. And that request doesn't contain that value.
You can, when loading the page, put that value on the request. In index.php read the $_GET['id'] value and output it to the JavaScript code which is making that AJAX request. Technically it could be something as simple as this, just to demonstrate:
"/superadmin/box_utilizadores_ajax.php?id=" . $_GET['id'] . "\", \"GET\")"
However, be aware of the dangers of outputting raw user input to the page. This results in things like XSS vulnerabilities. Be mindful of what you're outputting to the page, but ultimately you need to output that value somewhere in order for that JavaScript code to send it to the next (AJAX) request. (Or, alternatively, you could store the file server-side in session state or something similar. Thereby removing the URL from the equation entirely. There are pros and cons either way.)
In short, you need to include the value on the URL being requested if the page at that URL is going to read the value. The code can only read values which are there.

Using PHP to determine what HTML to write out

This block of PHP code prints out some information from a file in the directory, but I want the information printed out by echo to be used inside the HTML below it. Any help how to do this? Am I even asking this question right? Thanks.
if(array_pop($words) == "fulltrajectory.xyz") {
$DIR = explode("/",htmlspecialchars($_GET["name"]));
$truncatedDIR = array_pop($DIR);
$truncatedDIR2 = ''.implode("/",$DIR);
$conffile = fopen("/var/www/scmods/fileviewer/".$truncatedDIR2."/conf.txt",'r');
$line = trim(fgets($conffile));
while(!feof($conffile)) {
$words = preg_split('/\s+/',$line);
if(strcmp($words[0],"FROZENATOMS") == 0) {
print_r($words);
$frozen = implode(",", array_slice(preg_split('/\s+/',$line), 1));
}
$line = trim(fgets($conffile));
}
echo $frozen . "<br>";
}
?>
The above code prints out some information using an echo. The information printed out in that echo I want in the HTML code below where it has $PRINTHERE. How do I get it to do that? Thanks.
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno=[$PRINTHERE]; halos on;", "frozen on")
You just need to make sure that your file is a php file..
Then you can use html tags with php scripts, no need to add it using JS.
It's as simple as this:
<div>
<?php echo $PRINTHERE; ?>
</div>
Do remember that PHP is server-side and JS is client-side. But if you really want to do that, you can pass a php variable like this:
<script>
var print = <?php echo $PRINTHERE; ?>;
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno="+print+"; halos on;", "frozen on"));
</script>

Inserting shortcode into php line

I want to insert this sortcode:
echo do_shortcode('[AUTHORIMAGE-CIRCLE]');
and replace it with the ua1 class on this php line:
$STRING .= $b_f.''.$CORE->_e(array('head','4')).''.$b_a;
This is the real code. the full one is:
if( $canShowBar ){
if(!$isTop){
$STRING .= "<div class='breadcrumb'>";
}
if(isset($userdata) && $userdata->ID){
if(isset($GLOBALS['CORE_THEME']['links'])){
// my account
$STRING .= $b_f.''.$CORE->_e(array('head','4')).''.$b_a;
}
}
}
when working on local host and try to modify the code, after refreshing the whole page is turning blank

PHP : Second Function not being called

I am using PHP and want to run 2 functions, one after the other.
These functions are getallmydata() and createCSV()
The code below runs the first function fine but the second function createCSV() is not working. It seems like it is not being called properly.
Is there anything wrong with the structure of my code as both functions work correctly independently? I cannot work this out!
<?php
//run this function//
getallmydata();
//then run this function//
createCSV();
function getallmydata(){
require_once dirname(__FILE__).'/cm/csrest_general.php';
require_once dirname(__FILE__).'/cm/csrest_clients.php';
require_once dirname(__FILE__).'/cm/csrest_campaigns.php';
$api_key = 'MY API KEY';
$wrap = new CS_REST_General($api_key);
$result = $wrap->get_clients();
$Content = "";
if ($result->was_successful()) {
foreach ($result->response as $client) {
$client_wrapper = new CS_REST_Clients($client->ClientID, $api_key);
$client_details_result = $client_wrapper->get();
$campaigns_result = $client_wrapper->get_campaigns();
if ($client_details_result->was_successful()) {
/* This is where the client details will be */
$client_details = $client_details_result->response;
echo ('<pre>');
/*print out the company name*/
echo "Company Name = " . $client_details->BasicDetails->CompanyName . "<br/>";
/*print out the company markup*/
echo "Markup On Delivery = " . $client_details->BillingDetails->MarkupOnDelivery . "<br/>";
$count = 0;
if ($campaigns_result->was_successful()) {
/*print out the latest campaign name of the current campaign*/
foreach ($campaigns_result->response as $campaign_ob) {
echo 'Latest Campaign Name = ' . $campaign_ob->Name . '<br/>';
//echo 'Latest Subject = ' . $campaign_ob->Subject . '<br/>';
//echo 'Total Recipients = ' . $campaign_ob->TotalRecipients . '<br/>';
//echo 'Sent Date = ' . $campaign_ob->SentDate . '<br/>';
/*Set content for CSV File*/
//$Content .= "This is within the loop \n";
$count++;
if($count > 0) break;
}/*end loop*/
}/*end campaigns if statement*/
echo ('</pre>');
} else {
echo 'Failed with code '.$client_details_result->http_status_code."\n<br /><pre>";
var_dump($client_details_result->response);
}
}
} else {
echo 'Failed with code '.$result->http_status_code."\n<br /><pre>";
var_dump($result->response);
echo ('</pre>');
}
} //end main function
/*create the downloadable csv file*/
function createCSV(){
$FileName = date("d-m-y") . '.csv';
# Titlte of the CSV
//$Content = "Company_Name Markup Campaign_Name Subject Recipients Date \n";
# fill data in the CSV
//$Content .= "\"John Doe\",\"New York, USA\",15,65465464 \n";
$Content .= "Testing The Function Works OK \n";
//$Content .= "This should be another line";
header('Content-Type: application/csv');
header("Content-length: " . filesize($NewFile));
header('Content-Disposition: attachment; filename="' . $FileName . '"');
echo $Content;
exit();
}//end csv download function
/*end create downloadable .csv file */
?>
I think you should get the error: headers already sent. (you checked that the second function is called right? You can find it out by placing a echo on the first line of the function.)
You are trying to create a CSV page but you are parsing HTML in the first function, so the header is already sent to the client saying that it is a normal HTML page. Remove these echo's in the first function and it should work.
Quote of the PHP manual:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
More info about headers: PHP header
First think I would tell you is
1 you should first write function definition and then you should call a function
i.e
function getallmydata(){
// function code
}
function createCSV(){
// function code
}
getallmydata();
createCSV();
2 . The second thing is that check that is there any white space left in the code out side php code or any o/p that is sent as resonse as because when ever you user header() at that if any kind of content other than header() is sent as response then header() function fails. Try this things and check again.

Categories