How to assign a PHP expression to a PHP variable - php

I need to do something like
$var = "Hello World ..the value is <?php echo 'XYZ' ?>";
Any help will be highly useful. I am stuck in this from the very long time but not able to acheive this. please help
Below is my PHP code that I need to assigned again to php variable (this variable will be passed to return of my ajax call)
<div class="photo-post">
<h4 class="h4-1">Some data...</h4>
<?php
$i=0;
$unique_seq="888094499";
$pic_counter=1;
foreach (glob("target/*".$unique_seq."*") as $filename)
{
$i++;
}
$total_pics=$i;
echo "<div id='post-photo-slider'>";
if($i>1)
{
echo "<a href='#' class='control_next_photo'>></a>";
echo "<a href='#' class='control_prev_photo'><</a>";
}
echo "<ul>";
foreach (glob("target/*".$unique_seq."*") as $filename)
{
echo "<li>";
echo "<div class='photos-slide-container'>";
echo "<img src='".$filename."' width='540px' height='225px'>";
echo "<span class='count-span-photos'>".$pic_counter." of ".$total_pics."</span>";
echo "</div>";
echo "</li>";
$pic_counter++;
}
if ($i==1)
{
echo "<li></li>";
}
echo "</ul>";
echo "</div><!-- post-photo-slider END -->";
echo "<hr class='hr4'>";
?>
</div><!-- photo end -->

you cannot do it in this way
$var = "Hello World ..the value is <?php echo 'XYZ' ?>";
when you return this string to your javascript php code cannot be execute on client side!!!!
why do not return do this simple way?
$var = "Hello World ..the value is " . "XYZ";

Related

Call a php function to echo in place

I have this code
$css=0;
<?php
echo "<div>";
function style(){
global $css;
echo $css;
}
echo "</div>";
$css =5 ; style();
?>
what i want to happen is this
<div>5</div>
and what really happens is
<div></div>5
I need to declare the value of the variable then go back and echo it in the same place it intended to be in, and I can't change the order due to many reasons in the code structure .
UPDATE :: after reading all the answers it seems i wasn't clear enough .
<html>
<?php $css=0; ?>
<div id="<?php echo $css ?>"></div>
<div id ="K"></div>
<?php
$css=5;
?>
</html>
this is the situation
1- i can not declare $css before the echo.
2- i can not reposition anything from this structure .
3- i can not put #K after the declaring of the $css .
what i really need a way to put the value inside the variable and let echo where it's .
any ideas ?
you can try this as well using js
<?php
$css=0;
echo "<div id='tt'>";
/*function style(){global $css; echo $css;}*/
echo "</div>";
$css =5 ;
echo "<script>";
echo "document.getElementById('tt').innerHTML = $css";
echo "</script>";
?>
Your function is run when you call it, and as it is called below the you get the expected 5.
To fix this:
echo "<div>";
style();
echo "</div>";
<?php
echo "<div>";
function style() {
global $css;
echo $css;
}
$css =5 ;
style();
echo "</div>";
?>
or simply:
<?php
function style() {
global $css;
echo $css;
}
$css = 5;
echo "<div>" . style() . "</div>";
?>
Previously, you well calling the function to echo out the variable after closing the div.

PHP Session SID URL - url does not have SID

I'm trying to learn how to use Sessions to maintain state between pages.
I think my problem is that I dont know how to escape properly. When I load the page im not getting the SID at the end of the url, instead I'm getting this:
mytestsite.com/login.php?<?php echo SID;?>
I have session_start() at the top of every page. And the session initialy works as I see the login name appear on the page and the Register and Login links, but then when I click to another page the session is not maintained.
The main site nav is dynamically createdusing an array($nav) and foreach loop. Here too I'm not sure how to echo the url and php SID constant. I don't think my syntax is correct.
//LOGIN BAR
echo "<nav id='statusBar'>";
echo "<ul>";
if(isset($_SESSION['userIn']) && $_SESSION['userIn'] != ''){
echo "<li id='userLo'>Log Out</li>";
echo "<li id='userLi'>User Logged In: " . $_SESSION['userIn'] . "</li>";
} else{
echo '<li>Register</li>';
echo '<li>Login</li>';
}
echo "</ul>";
echo "</nav>";
//START MAIN MENU
echo "<nav id='nav'> ";
$nav = array();
$nav['index.php?<?php echo SID;?>'] = 'Home';
$nav['public1.php?<?php echo SID;?>'] = 'Public 1';
$nav['public2.php?<?php echo SID;?>'] = 'Public 2';
$nav['members.php?<?php echo SID;?>'] = 'Members';
//CREATE UNORDERED LIST
echo '<ul>';
foreach ($nav as $key => $navValues) {
echo "<li>";
echo "<a href='$key'>$navValues</a>";
echo "</li>";
}
echo '</ul>';
echo "</nav>";
Below everything within echo '..'; is interpreted as html.
echo '<li>Login</li>';
If you want to use variables inside the string you have to concatenate them like so:
echo 'Login' ;
For concatenating php code take a look at:
http://php.net/manual/en/language.operators.string.php
and more about sessions:
http://php.net/manual/en/session.constants.php

I want to add .html at the end or a full url fetch from Database and php query between echo

I am going to write following code for my blog. But problem, I am facing with:
"echo 'a href=".$query2['url']."</a>';" I want to add .$query2['url']. in echo and also want to add .html at the end of url like
"a href=".$query2['url'].html.".
If you have any idea please tell me as soon as possible thanks. Basically I am fetching this data from database .
<?php
$start=0;
$limit=5;
if(isset($_GET['id']))
{
$id=$_GET['id'];
$start=($id-1)*$limit;
}
$query=mysql_query("select * from tbl_services LIMIT $start, $limit");
echo "<div class='entry'>";
while($query2=mysql_fetch_array($query))
{
echo '<h2>' .$query2['name'].'</h2>';
echo "<p>".$query2['Contents']."</p>";
echo "<div class='meta'><i class='fa fa-clock-o'></i>".$query2['date']. "<b><i class='fa fa-user'></i></b> Written by <strong>Arslan Ali</strong> <b><i class='fa fa-comment-o'></i></b>" ;
echo "</div>";
}
echo "</div>";
$rows=mysql_num_rows(mysql_query("select * from tbl_services"));
$total=ceil($rows/$limit);
echo "<ul class='pagination'>";
if($id>1)
{
echo "<li><a href='?id=".($id-1)."' class='disabled'><<</a></li>";
}
for($i=1;$i<=$total;$i++)
{
if($i==$id) { echo "<li class='current'>".$i."</li>"; }
else { echo "<li><a href='?id=".$i."'>".$i."</a></li>"; }
}
if($id!=$total)
{
echo "<li><a href='?id=".($id+1)."' class='disabled'>>></a></li>";
}
echo "</ul>";
?>
(Updated)
Replace this line
echo '<h2>' .$query2['name'].'</h2>';
with
echo "<a href='".$query2['url'].".html'>".$query2['name']."</a>";
There is still one problem with the solution made by Syntax Error. The href is in single quotes. This is not the proper Syntax. It is easily remedied by reversing the use of the single and double quotes as I have shown here.
echo '' . $query2['name']. '';

Add class to variable inside echo

How can i add to variable $title inside echo ? In the foreach:
<?php
foreach($this->searchfields as $fsearch) {
$title = $this->field->showFieldTitle($this->catid,$fsearch);
echo "<div id=".$fsearch->name.">".htmlspecialchars($title)."";
$this->field->showFieldSearch($fsearch,$this->catid,null);
echo "</div>";
}?>
I tried echo "<div id=".$fsearch->name.">".htmlspecialchars(<div class="header">$title</div>).""; but it doesnt work :)
How about:
echo "<div id='".$fsearch->name."'><div class='header'>".htmlspecialchars($title)."</div>";
?

How to speedup by code?

is there a way to speed up my code? It takes about 15 seconds to load ... I don't really see a way to reduce my code... I just thought about inserting the values into database, so the user does not have to load new info every time.. but the thing is that my cron only allows 1 load per hour ... by loading new info on every load it gives me fresh information..
$q1=mysql_query("SELECT * FROM isara");
while($r1=mysql_fetch_array($q1)){
$named=$r1['name'];
$idd=$r1['id'];
$descd=$r1['desc'];
$online=check_online($named);
$char = new Character($r1['name'],$r1['id'],$r1['desc']);
if($online == "online"){
$char->rank = $i++;
}
else{
$char->rank = 0;
}
$arr[] = $char;
}
?>
<br />
<h2 style="color:green">Online enemies</h2>
<?php
foreach ($arr as $char) {
if($char->rank>=1){
echo "<a style=\"color:green\" href=\"http://www.tibia.com/community/?subtopic=characters&name=$char->name\">";
echo $char->name." ";
echo "</a>";
echo level($char->name)."<b> ";
echo vocation($char->name)."</b> (<i>";
echo $char->desc." </i>)<br />";
}
}
?>
<br />
<h2 style="color:red">Offline enemies</h2>
<?php
foreach ($arr as $char) {
if($char->rank==0){
echo "<a style=\"color:red\" href=\"http://www.tibia.com/community/?subtopic=characters&name=$char->name\">";
echo $char->name." ";
echo "</a>";
echo level($char->name)."<b> ";
echo vocation($char->name)."</b> (<i>";
echo $char->desc." </i>)<br />";
}
}
?>
As I wrote in the comment, fetch the page once instead of once for every name in the database.
Pseudo code for my comment:
users = <get users from database>
webpage = <get webpage contents>
for (user in users)
<check if user exists in webpage>
As mentioned in the comments you're calling a webpage for each entry in your database, assuming that's about 2 seconds per call it's going to slow you down a lot.
Why don't you call the page once and pass the contents of it into the check_online() function as a parameter so your code would look something like this which will speed it up by quite a few magnitudes:
$content=file_get_contents("http://www.tibia.com/community/?subtopic=worlds&worl‌​d=Isara",0);
$q1=mysql_query("SELECT * FROM isara");
while($r1=mysql_fetch_array($q1)){
$named=$r1['name'];
$idd=$r1['id'];
$descd=$r1['desc'];
$online=check_online($named,$content);
$char = new Character($r1['name'],$r1['id'],$r1['desc']);
if($online == "online"){
$char->rank = $i++;
}
else{
$char->rank = 0;
}
$arr[] = $char;
}
?>
<br />
<h2 style="color:green">Online enemies</h2>
<?php
foreach ($arr as $char) {
if($char->rank>=1){
echo "<a style=\"color:green\" href=\"http://www.tibia.com/community/?subtopic=characters&name=$char->name\">";
echo $char->name." ";
echo "</a>";
echo level($char->name)."<b> ";
echo vocation($char->name)."</b> (<i>";
echo $char->desc." </i>)<br />";
}
}
?>
<br />
<h2 style="color:red">Offline enemies</h2>
<?php
foreach ($arr as $char) {
if($char->rank==0){
echo "<a style=\"color:red\" href=\"http://www.tibia.com/community/?subtopic=characters&name=$char->name\">";
echo $char->name." ";
echo "</a>";
echo level($char->name)."<b> ";
echo vocation($char->name)."</b> (<i>";
echo $char->desc." </i>)<br />";
}
}
?>
and your check_online() function would look something like this:
function check_online($name,$content){
$count=substr_count($name, " ");
if($count > 0){ $ex=explode(" ",$name); $namez=$ex[1]; $nameused=$namez; }
else{ $nameused=$name; }
if(preg_match("/$nameused/",$content)){ $status="online"; }
else{ $status="offline"; }
return $status;
}
You can also do the following to make it faster
Stop using select * which is very bad on innodb
Put better indexes on your database to make the recordset return faster
Install PHP 5.4 as it's faster especially as you're creating a new object in each iteration
Use a byte code accelerator/cache such as xdebug
you should avoid using distinct (*) keyword in your SQL Query
for more information read this http://blog.sqlauthority.com/category/sql-coding-standards/page/2/

Categories