I have have some php code that I can't get to work ...
I can't seem to find my mistake :/, I realize it's going to be a syntax error but after looking for an hour with no success I turn to you guys for help =)
Here is the code:
<?php
$t= number_latest_added();
for ($n = 0; $n<$t; $n += 3) {
$latest = latest($n);
echo "<a class=\"example-image-link\" href=\"" .$latest. "\" data-lightbox=\"example-set\" data-title=\"De la galerie : " . $latest . "\"><div id=\"a\" style=\"background: url(" . $latest . ") 50% 50% / cover;background-size: contain;background-repeat: no-repeat;\"></div></a></br>";
}
?>
The problem is in getting the echo to concatenate with the variable but it isn't working ( the variable is echoed 3 times and then the text is echoed with blank instead of the variable) and I don't understand why not ...
If somebody could help me see my error; it would be great!
What is the function latest? From what you are saying I am guessing it is something like:
function latest($number) {
echo $number;
}
and you need something like:
function latest($number) {
return $number;
}
Make sure you turn on error reporting ini_set('display_errors', 'On');
In addition to that, php automatically parses variables to string, if your inside double quotes.
Example:
$var = "hello"
echo "$var world" //prints hello world
Your problem is that latest($n) doesn't return anything printable, you can find that out by simply echo'ing the value itself.
Related
I am simply trying to echo or print out specific data from a DB into a string (i hope thats the right name), which should be a very simple process as I've done it before. The point is everytime a user inserts information into the database this string echo's or prints out the inserted data.
But for some very odd reason this time around when i try to echo out the data, I literally get this.
Very frustrating. As you can see from the image above i have tried using 2 different ways to do this a variable and a session, but the echo literally just prints it out. I have done this before so i am aware that it is possible. I am just a little lost into how i am meant to achieve this or even better where i went wrong. I know how to do this using a different style of coding, but i am trying to keep everything uniformed (newbie).
$addon_name = $_SESSION['Add_On_OpName'];
mysqli_report(MYSQLI_REPORT_INDEX); //overrid a common php nonsense error
$prod_sel = $dbc->query("SELECT * FROM Add_On WHERE Add_On_OpName = '$addon_name'");
$prod_sel->data_seek(0);
while ($output = $prod_sel->fetch_assoc()) {
$prod_run .= $output['Add_On_OpName'] . $output['Prod_Name'] . $output['Add_On_Price'] . $output['Add_On_Select'] . '<br>';
$addon = $output['Add_On_OpName']; //echo out product name
$_SESSION['Prod_Name'] = $output['Prod_Name']; //echo out product desc
$_SESSION['Add_On_Price'] = $output['Add_On_Price']; //echo out price
echo '
<p>$addon . " " . $_SESSION["Add_On_Price"]; </p>
';
My session is started and the php file is connected to the DB.
I also have error handling which has not given out any error messages.
You must do:
echo "<p>$addon ".$_SESSION["Add_On_Price"]."; </p>";
A string encapsulated into ' is rendered just as it is.
Use " to render a string that contains variables. Example:
$a = 3;
$a++;
echo "the result is $a";
will result in the result is 4.
On the other hand,
echo 'the result is $a';
gives the result is $a.
As the documentation points out:
Single quoted ¶ The simplest way to specify a string is to enclose it
in single quotes (the character ').
Doued ¶
If the string is enclosed in double-quotes ("), PHP will interpret
more escape sequences for special characters
Try not mix it..
And if within double quotes you have an associative array you may concat.
echo "string $variable". $array["index"];
or
echo "string $variable {$array["index"]}";
Then your code should look like
$addon_name = $_SESSION['Add_On_OpName'];
mysqli_report(MYSQLI_REPORT_INDEX); //overrid a common php nonsense error
$prod_sel = $dbc->query("SELECT * FROM Add_On WHERE Add_On_OpName = '$addon_name'");
$prod_sel->data_seek(0);
while ($output = $prod_sel->fetch_assoc()) {
$prod_run .= $output['Add_On_OpName'] . $output['Prod_Name'] . $output['Add_On_Price'] . $output['Add_On_Select'] . '<br>';
$addon = $output['Add_On_OpName']; //echo out product name
$_SESSION['Prod_Name'] = $output['Prod_Name']; //echo out product desc
$_SESSION['Add_On_Price'] = $output['Add_On_Price']; //echo out price
echo "<p>$addon {$_SESSION["Add_On_Price"]}; </p>'";
}
Long time ago
I never use double quotes due to it require parse the whole string for special notations. However it.
Try not mix single quotes with double quotes. pick up a standard for you code you will not notice any difference than is easy to code and read without surprises
You're mixing single quotes and double quotes. Single quotes do not perform interpolation of variables so when you write this:
echo '... whatever including " char and $ sign';
PHP will just literally print everything inside.
You forget some ' or " !
echo '<p>' . $addon . ' ' . $_SESSION["Add_On_Price"] . '</p>';
Use double quotes
echo "<p>$addon $_SESSION['Add_On_Price']; </p>";
I've done hours of research on this now, so I believe I'm not repeating, even though this seems like it would have a simple solution.
I have an HTML form sending values to PHP, where it takes the value, and sets them all to a variable. When I submit the values and load the PHP, it completely breaks as if there is a syntax problem, but I can't find anything obvious.
I'm setting the variables from POST like so:
$ital1=$_POST['checkbox1'];
$bold1=$_POST['checkbox2'];
$ital2=$_POST['checkbox3'];
$bold2=$_POST['checkbox4'];
I'm then using these variables with simplexml to write to an xml document for databasing. Here's a snippet of that:
$xml = simplexml_load_file('settings.xml');
function loops()
{
$italvar = (eval('return $' . "ital{$string}"));
$boldvar = (eval('return $' . "bold{$string}"));
$alertvar = (eval('return $' . "alerttitle{$string}"));
$pagevar = (eval('return $' . "page{$string}n"));
$colorvar = (eval('return $' . "colorset{$string}"));
$string = strval($i);
for($i=1; $i<21; $i++)
{
if($xml->settings->checkbox->"ital{$string}" == $empty && $italvar == "on")//ITAL1
{
$xml->settings->checkbox->"ital{$string}" = $italvar;
}
else if($italvar == $empty && $xml->settings->checkbox->"ital{$string}" == "on")
{
$xml->settings->checkbox->"ital{$string}" = $empty;
}
else
{
continue;
}
}
$xml->asXML('settings.xml');
This is just a piece of the function, but the rest is basically this repeated for different types of variables. I know the issue is within the loops function as when I delete loops(), the PHP at least loads some echos at the top of the doc.
I'm not sure what in here is breaking. I'm guessing it's the syntax with how I'm combining and iterating variables, which explains the title.
So my questions is this. How do I combine strings and variables correctly?
$italvar = (eval('return $' . "ital{$string}"));
$string = strval($i);
In this instance I want the end result to be $ital#, # being the current iteration of the forloop, so I can correctly write to xml the value of the set variable from $_POST as shown at the top.
"ital{$string}"
$string = strval($i);
And here I just want it to be a string such as ital1, then ital2, as that's what the nodes are called in the xml. I'm sure what I'm doing wrong is very obvious, but I'm very new to PHP and I can't seem to figure it out. Thank you very much in advance for any input!
You have a $_POST array. Use it.
for( $i=1; $i<=20; $i++) {
$ital = $_POST['checkbox'.($i*2-1)];
$bold = $_POST['checkbox'.($i*2)];
// now do stuff with `$bold` and `$italic`
}
I've been struggling to echo the output of a function. I tried this:
echo 'myFunction('foo')';
.. which obviously won't work, due to the extra single quotes. Any suggestions?
Let's take this function :
function getStr()
{
return "hello";
}
It will simply return a string, which means, calling this :
echo getStr();
Has the same exact result as calling this :
echo "hello";
Which means, the result of your function can be treated just like a variable (except you cant modify it), so you can do whatever you want with the result :
$string = getStr() . ' - ' . getStr();
echo $string; // Will print "hello - hello";
After trying a little while, I tried calling echo as an function:
echo (myFunction('foo'));
This works perfectly. I couldn't find this elsewhere on the internet (maybe I'm just a bad googler). Anyways, I thought I could might share this with you guys. In case anyone ever runs into the same problem.
Try this:
echo myFunction('foo');
$m = 'this_is_m';
$this_is_m = 'this_is_m_not_full :(';
$this_is_m_full = 'this_is_m_FULL!! :D';
print ${$m};
(Hi first :P) Outputs:
this_is_m_not full :(
Any idea how to output this_is_m_FULL!! :D using $m??
What I've already tried:
print $"{$m}_full";
print $'{$m}_full';
print $'$m_full';
print ${$m}_full';
None worked... Thanks in advance,,
The solution would be:
print ${$m . '_full'};
But that feels very hackish.
To get your desired output, you need to do the following:
print ${$m . "_full"};
The following should work:
print ${$m.'_full'};
This is because the string inside the braces will get evaluated first, becoming
print ${'this_is_m' . '_full'}
-> print ${'this_is_m_full'}
-> print $this_is_m_full
Take a look at this manual page if you want more information on this.
I'm having trouble describing this issue, which is probably why I can't find the answer on google.. so I figured I would try getting help here. If I'm repeating this question, feel free to direct me to a link to the thread.
So basically the issue I'm having is I am trying to pass a variable to a function that contains some php code to be eval'd.
Here's the simplified version of the code:
function senduser($body) {
$query = mysql_query("SELECT * FROM User_tbl");
while ($row = mysql_fetch_array($query)) {
echo eval($body);
}
}
$body = 'Hello $row[\'user_first_name\'] <br>';
sendUser($body);
--
For some reason, the output isn't putting out what I want. I've gotten a few whitespace errors, and a few times I've gotten the code to output the plain text of the variable $body.
Any help is appreciated. Let me know if I need to clarify the issue further.
I would change it to this:
function sendUser($body) {
$query = mysql_query("SELECT * FROM User_tbl");
while ($row = mysql_fetch_array($query)) {
echo $body($row);
}
}
And then call it like this (php 5.3+):
$body = function ($row) {
return "Hello ".
htmlspecialchars($row['user_first_name'], ENT_QUOTES, 'UTF-8').
"<br />";
};
sendUser($body);
In php <= 5.2, it's a lot messier:
$body = create_function(
'$row',
'return "Hello ".'.
'htmlspecialchars($row["user_first_name"], ENT_QUOTES, "UTF-8").'.
'"<br />";'
);
sendUser($body);
That isn't now eval works; it returns null unless you explicitly return a value. You're also missing quotes around the string, and a semicolon at the end of the statement.
To get it to echo something, you'd have to pass the echo as part of the code to be evaluated:
$body = 'echo "Hello $row[\'user_first_name\'] <br>";';
or, to get your code working as written, you'd have to return the formatted string:
$body = 'return "Hello $row[\'user_first_name\'] <br>";';
This is a pretty contrived use of eval. You'd be far better off passing in a printf-style format string and using sprintf to substitute values into it, and returning that string for printing. As it stands you seem to be mixing your display logic with your database logic, which is a bad thing.
Your code, as is, will never work. Removing the mysql portion:
<?php
function senduser($body) {
$row['user_first_name'] = 'Fred';
echo eval($body);
}
$body = 'Hello $row[\'user_first_name\'] <br>';
sendUser($body);
Gives me:
PHP Parse error: syntax error, unexpected T_VARIABLE in /home/marc/z.php(5) : eval()'d code on line 1
Anything you pass in to eval() must be raw PHP code. It can't be plaintext with embedded <?php ?> PHP blocks - it has to be actual PHP code. When you fix up $body to account for this:
$body = 'echo "Hello {$row[\'user_first_name\']} <br>";';
Then you get:
Hello Fred <br>
I'm not exactly positive what you're trying to do, but I think your problem is in the definition of $body and your use of eval.
$body = 'Hello $row[\'user_first_name\'] <br>';
is not a valid line of php, and eval won't know what to do with it.
See if this fits what you want:
function senduser($body) {
$query = mysql_query("SELECT * FROM User_tbl");
while ($row = mysql_fetch_array($query)) {
eval($body);
}
}
$body = 'echo "Hello {$row[\'user_first_name\']} <br>";';
sendUser($body);