"Double" evaluation in PHP - php

Morning all!
My MySQL query returns a PHP variable name which I'd like to "double" evaluate when I output it. It may be best for me to do this by example.
On the static resources page I have:
$page1 = "test1.php";
$page2 = "test2.php";
And my MySQL table called tbl_pages contains 2 entries under fld_pagename: $page1 and $page2. That way, I figure that I only define $page1 and $page2 once.
Now, on the page I'm working on, I have a query which returns the name of the page:
$query = mysql_query("SELECT fld_pagename FROM tbl_pages WHERE fld_show = 1 ORDER BY fld_ref");
while($row = mysql_fetch_array($query)){
$nameofpage = $row['fld_pagename'];
echo "$nameofpage",'<br />';
}
However, the double quotes around the variable only evaluate the variable to one level. Its output is:
$page1<br />$page2<br />
But I want these variables to be evaluated before output:
test1.php<br />test2.php<br />
Any thoughts much appreciated!

If I get you correctly, you can use this PHP feature (example):
$test1=1234;
$test2='test1';
echo $$test2; // echoes 1234
Or, to make it compatible with your system...
$nameofpage=substr($nameofpage,1); // remove dollar
echo $$nameofpage.'<br/>';

If you're after evaluating the pages you've referenced, then this would work:
$query = mysql_query("SELECT fld_pagename FROM tbl_pages WHERE fld_show = 1 ORDER BY fld_ref");
while($row = mysql_fetch_array($query)){
$nameofpage = $row['fld_pagename'];
include($nameofpage);
echo '<br />';
}

If you only store variable name without $ you can use variable of variable feature of PHP
echo $$nameofpage,'<br />';
can remove $ from input stored
$nameofpage=substr( $nameofpage, 1 );
echo $$nameofpage,'<br />';

it seems your database design is wrong.
There is not a single reason to store PHP variable names in the database.
Store pagenames itself and you'll be okay

Related

Php variable increment

So i have the following code that works and outputs the information let's say 2 11. I would like to have $keyidcall increment in variable name so $keyidcall2, $keyidcall3....... with the additional variables I would like the variable to hold the correct value so I can call it later. so expected output would be $Apiammount ="2";
echo $keyidcall; would echo 2
echo $keyidcall: would echo 11
while($Apiammount > 1){
$Keyidquery = mysqli_query($connection, "SELECT ID FROM `Characterapi` WHERE UserId = '$Idcall'");
while($keyid = mysqli_fetch_assoc($Keyidquery)){
$keyidcall = $keyid['ID'];
echo $keyidcall;
}
$Apiammount--;
}
The better way to do this would be to store the values in an array.
$keyidcall[] = $keyid['ID'];
Then you can refer to them later as
echo $keyidcall[0];
echo $keyidcall[1];
in the order that they were entered in.
Or if you wanted something more specific to refer to it by, you could use
$keyidcall[$Apiammount] = $keyid['ID'];
then you would refer to them as:
echo $keyidcall[<apiamount>];
Assuming you know what that would be.
You can do:
$i = 0;
while($foo){
$name = 'keyidcall';
$i++;
$newvar = $name . $i;
echo $$newvar;
}
And $$newvar will echo the value of "keyidcallX" where X is an incrementing value. Not sure if that's what you meant.

Pass PHP Variable into WHERE/AND MySQL Query

I'm trying to pass a value for a query that takes in a variable from an earlier Sql query and then compares the result against a field from another table. But I can't seem to figure out my syntax.
$topName = $row_rsAdminDetails['fullName'] ;
$TESTqueryTwo =
"SELECT * FROM participants, admin WHERE admin.over_id = participants.fk_over_id AND participants.dr_over_names LIKE '%$topName%'";
$TESTresult2 = mysql_query($TESTqueryTwo) or die(mysql_error());
the php output I'm looking to do:
<?php
// Print out the contents of each row
while($row_TESTresultTwo = mysql_fetch_array($TESTresultTwo)){
echo $row_TESTresultTwo['userName']. " - ". $row_TESTresultTwo['Participant_Name'];
echo "<br />";
}
?>
Problem could be on this line:
while($row_TESTresultTwo = mysql_fetch_array($TESTresultTwo)){
should be
while($row_TESTresultTwo = mysql_fetch_array($TESTresult2)){
// as you have no $TESTresultTwo variable...
}
And also try with the query ... with LIKE '%".$topName."%'"

How to identify list of variables_x from url in PHP, using one parameter?

I have a members site where users are given up to 7 web page templates to display their products on. Each template has the same field names, differentiated by _1, _2... _7 at the end of each.
For example:
// Template 1 would have the following list of variables
product_name_1
product_descript_1
product_color_1
product_price_1
// Template 2 would have the following list of variables
product_name_2
product_descript_2
product_color_2
product_price_2
// through Template 7
I am able to display any variables for a specific user within a web page, by use of a query string identifying their user_id in the url, ie
http://domain.com/folder/page.php?id=78
I then $_Get any variable by simply identifying it in the PHP file, ie
$product_name_1
$product_descript_1
$product_color_1
$product_price_1
My problem is that the url must identify WHICH template, since each template identifies a specific product, ie _1, _2, ..._7. How do I use a parameter in the url, such as
http://domain.com/folder/page.php?id=78&parameter=_7
...to identify all variables ending with _7, which would appear in the web page? The parameter used in the url would identify the variables to be used in the web page, whether _1, _2, etc.
UPDATE
I have tried the various answers with only partial success, ie "Array_x" is displayed when using any particular variable along with the suggested code. There may be a conflict with the rest of the code I'm using in page.php, as follows:
$db_connection = new mysqli("", "", "");
if ($db_connection->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$id = $_GET['id'];
$query = mysql_query("SELECT * FROM table_name WHERE id = '$id' LIMIT 1") or die(mysql_error());
$row = mysql_fetch_object($query);
$prop_address=array(
"_1"=>"prop_address_1",
"_2"=>"prop_address_2",
"_3"=>"prop_address_3"
//Through to Temp 7
);
$prop_address{$_GET['parameter']}=$row->prop_address;
echo " $prop_address{$_GET['parameter']} ";
"Array_x" displays (where x=1, 2, 3, etc is used as the parameter in url, ie http://domain.com/page.php?id=72&parameter=1), instead of the actual value held in the database table for $product_name{$_GET['parameter']}. For some reason, the code is not picking up the value of the variable from the database table.
Would it be possible to use arrays so...
$product_name=array(
"1"=>"Product name for template 1",
"2"=>"Product name for template 2"
//Through to Temp 7
);
echo $product_name[$_GET["parameter"]];
You could then do the same for the other variables.
You could fill each array by doing something like:
$row = mysql_fetch_object($query);
$product_name[$_GET['parameter']]=$row->product_name;
echo $product_name[$_GET['parameter']];
I may be missing something...
$_GET['parameter'] = '_2';
$product_name{$_GET['parameter']} = 'string';
echo $product_name_2; // string
or
$_GET['parameter'] = '_2';
$var = 'product_name'.$_GET['parameter'];
$$var = 'string';
echo $product_name_2; // string
Personally, I would use array's for this type of behavior.
Update:
Although the above works and tested ok, it is a lot more work than anyone would probably desired.
In lieu of simplicity, I would suggest the approach via array's.
$templates = array(2 => array(
'product_name' => "value",
'product_descript' => "value",
'product_color' => "value",
'product_price' => "value",
);
foreach($templates[substr($_GET['parameter'],1)] as $var => $val){
$variable = $var.$_GET['parameter'];
$$variable = $val;
}
The above is backwards compatible, it uses substr to remove the leading _ from your parameter.
I couldn't get any of the answers given to work. I found an example given by a user for php variable variables in the PHP manual here and found it to work. I incorporated it into my code as follows:
$id = $_GET['id'];
$query = mysql_query("SELECT * FROM table_name WHERE id = '$id' LIMIT 1") or die(mysql_error());
$row = mysql_fetch_object($query);
for( $i = 1; $i < 8; $i++ )
{
$product_name[$_GET['parameter']] = "product_name_" . $i;
$product_descript[$_GET['parameter']] = "product_descript_" . $i;
$product_color[$_GET['parameter']] = "product_color_" . $i;
$product_price[$_GET['parameter']] = "product_price_" . $i;
}
${$product_name[1]} = "$row->product_name_1";
${$product_name[2]} = "$row->product_name_2";
${$product_name[3]} = "$row->product_name_3";
${$product_name[4]} = "$row->product_name_4";
${$product_name[5]} = "$row->product_name_5";
${$product_name[6]} = "$row->product_name_6";
${$product_name[7]} = "$row->product_name_7";
// List 7 variables and values for each field name
echo "${$prop_name[$_GET['par']]}";
The only problem is that mysql injection is possible with this code. If anyone could suggest a solution, I would greatly appreciate it.

External looping of the variable

How could I best loop the data through a variable that's nested inside a 'while' loop but it's called outside of it ? Like in this example:
PHP:
$fr_q2 = mysqli_query($connect,"SELECT * FROM friends WHERE username ='".$_SESSION['user']."'
ORDER BY id DESC");
while ($rowsPicFr2 = mysqli_fetch_array($fr_q2)) {
$friends_q2[] = $rowsPicFr2['added_friend'];
$frn[] = $rowsPicFr2['added_friend'];
$frn2 = $rowsPicFr2['added_friend'];
}
$rowscheck = mysqli_num_rows($fr_q2);
for ($i=0; $i<$rowscheck; $i++)
HTML:
YES
So I need to pass $frn[$i] into a remdata() function - but the $frn[$i] needs to loop....All I get is a string of all ids from 'friend_added' in $frn[$i]....Thanks.
Once this HTML is sent to the browser, it won't loop anymore. It will just be HTML. So what you need to do, is either have it loop in JavaScript or simply echo each remdata():
YES
This solution is only really an option if you have very few elements in $frn.
Your question is confusing; I think you need the loop for the HTML output
<?php foreach ($frn as $i => $friend_id){ ?>
YES
<?php } ?>
Based on your comment in toon81's answer, it seems like you're having a problem dealing with several loops in your output that deal with the same result set in your database query. I'm not sure. I'd suggest in the future that you try to make your question easier to follow. For instance, do we need to know it's a social networking app? Your variable names aren't inherently easy to understand; what's the difference between $frn and $frn2? Presumably that's 'friend', but I keep reading it as 'fern'. You also only provided one line of your output, but your problem seems related to it's interaction with other output. Your code is cut off -- the rowscheck loop doesn't have a definition.
That said, this is a high level suggestion of how I'd handle your work differently. Data preparation:
$connection = ...;
$user = $_SESSION['user'];
$sql = "
SELECT added_friend
FROM friends
WHERE username = '$user'
ORDER BY id DESC
";
$response = mysql_query($sql, $connection);
$added_friends = array();
while ($row = mysql_fetch_object($response)){
$added_friends[] = $row->added_friend;
}
Ouput handling:
// With one loop if the markup can be ouput all at once.
foreach ($added_friends as $friend){
// Your 'friends_q2', whatever that is.
echo "Friends_q2: $friend";
// Your 'frn2' output, whatever that is.
echo "Frn2: $friend";
// Your 'frn' output.
echo "YES";
}
// ...or multiple loops if it can't.
foreach ($added_friends as $friend){
// Your 'friends_q2', whatever that is.
echo "Friends_q2: $friend";
}
foreach ($added_friends as $friend){
// Your 'frn2' output, whatever that is.
echo "Frn2: $friend";
}
foreach ($added_friends as $friend){
// Your 'frn' output.
echo "YES";
}
In any case, you're handling the same ID three times in different lists and in different ways. I'm not at all sure why. Is this what you're asking for help with?

When listing information from a database using php and mysql how would you make the first row look different to the rest?

Basically I have articles in my database and I want to alter the way the first record displays. I want the lastest (Posted) article to be the focus and the older article just to list, (see F1.com). I need to know how to get the first of my values in the array and get it to display differently but I am not sure how to do this, I can do it so all rows display the same just not how to alter the first row. I also need to know how to tell the rest of the rows to display the same afterwards im guessing you use an if statement there and before that some kind of count for the rows.
Current code:
$result = mysql_query("SELECT * FROM dbArticle WHERE userID='".$_SESSION["**"]."' ORDER BY timestamp DESC");
while($row = mysql_fetch_array($result))
{
echo "<h2 class=\"heading1\">". $row['title'] ."</h2>";
echo "By: ".$row['username']." Type: ".$row['type']." Posted: ".$row['timestamp']."
$body = $row['body'];
echo "<br/><p>";
echo substr("$body",0,260);
echo "...<span class=\"tool\"><a class=\"blue\" href=\"index.php?pageContent=readArticle&id=".$row['id']."\">Read More</a></span></p><hr/>";
}
mysql_close($con);
Ok I have taken Luke Dennis's code and tried to test it, but I am getting this error: Warning: Invalid argument supplied for foreach() this is the line of the foreach statment. Something that has just come to mind is that I will only want 5 or so of the older articles to display. This is what I have thats creating the error:
<? $con = mysql_connect("localhost","****","***");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("******", $con);
$result = mysql_query("SELECT * FROM dbArticle ORDER BY timestamp DESC");
$first = true;
foreach($result as $row){
if($first)
{
echo"".$row['title']."";
echo"this is the headline";
$first = false;
}
else
{
echo"".$row['title']."";
}
}
?>
Do I need to add mysql_fetch_array somewhere to set the array up?
I would just iterate through the results and apply a css class to the first entry:
$first = true;
while ($row = mysql_fetch_assoc($result)) {
$cssClass = '';
if ($first) {
$cssClass = 'highlight';
}
echo '<p class="' . $cssClass . '">' . $row['text'] . '</p>';
$first = false;
}
It's a bit crude, but I often hard-code a variable to designate the first run through a loop. So something like:
$first = true;
foreach($list_of_items as $item)
{
if($first)
{
// Do some stuff
$first = false;
}
else
{
// Do some other stuff
}
}
A simple if statement when looping through your results will usually do the trick. You can use a boolean to indicate if you've output the first row of results or now. If you haven't then give it a particular style and then set the boolean to true. Then all subsequent rows get a different style.
All of the above are correct. Luke Dennis' post is of course fleshed-out a bit more.
As Brian Fisher said, add some CSS styling to the first link when you encounter it per Luke's post.
I took a look at the article list on the F1 website. Pretty well constructed site - "One would expect that." :-)
Anyway, the article listings are contained within a two row table (summary="Latest Headlines") in descending order (newest first).
Just place a class in the second column (<td class="first-news-article">). Then add the class name and appropriate styling values in the css file - probably your' modules.css. There's already quite a few class values associated with articles in that file, so you may be able to just use an existing value.
That should be about it - other than actually doing it!
By the way, judging by the quality of the underlying html, I'm assuming there's already an "article list emitter." Just find that emitter and place the appropriate conditional to test for the first record.
Darrell
I just noted your code addition. I assume that you were showing the F1 site as an example. Anyway, I think you're on your way.
I presume you have some code that loops through your resultset and prints them into the page? Could you paste this code in, and that might give us a starting point to help you.
I don't know PHP, so I'll pseudocode it in Perl. I wouldn't do it like this:
my $row_num = 0;
for my $row ($query->next) {
$row_num++;
if( $row_num == 1 ) {
...format the first row...
}
else {
...format everything else...
}
}
The if statement inside the loop unnecessarily clutters the loop logic. It's not a performance issue, it's a code readability and maintainability issue. That sort of thing just BEGS for a bug. Take advantage of the fact that it's the first thing in the array. It's two different things, do them in two different pieces of code.
my $first = $query->next;
...format $first...
for my $row ($query->next) {
...format the row...
}
Of course, you must make the first row stand out by using tags.
I'd use array_shift():
$result = mysql_fetch_assoc($resultFromSql); // <- edit
$first = array_shift($result);
echo '<h1>'.$first['title'].'</h1>';
foreach ($result as $row) {
echo '<h2>'.$row['title'].'</h2>';
}
The best way to do this is to put a fetch statement prior to the while loop.
Putting a test inside the while loop that is only true for one iteration can be a waste of time for a result of millions of rows.

Categories