I'm currently using a php class for text gradients. (Mainly used for usernames) However i'm having a issue with it, I have added a screenshot to show what happens:
The gradient should have ended at:
<span style="color: #1a1a1a">g</span>
But it seems it's adding more span attributes to it, with weird characters.
I'm currently using this code to make the username:
if ($this->gradienttype == 3 && $this->gradientcolours != "" && $this->gradientdays > 0) {
$colours = explode("~", $this->gradientcolours);
$gradient = new ColourGradient(array(0 => $colours['0'], floor((strlen($this->username) / 2) - 1) => $colours['1'], (strlen($this->username) - 1) => $colours['2']));
$this->formattedname .= "<b><a title='" . $this->title . "' href='/profiles.php?id=" . $this->id . "'>";
foreach ($gradient as $i => $colour) {
if(!isset($this->username[$i])) { $this->username[$i] = ''; }
$this->formattedname .= "<span style='color:" . $colour . "'>" . $this->username[$i] . "</span>";
}
}
I'm not sure what's causing the weird characters, but I think it has something to do with this:
if(!isset($this->username[$i])) { $this->username[$i] = ''; }
Because when I remove that the characters are gone, but then I get:
Notice: Uninitialized string offset: 9 in
My question is how do I remove these characters and stop the gradient at the end of the last letter of the name?
If I need to submit the classes to make the gradient I will post them on a pastebin cause they're quite large.
replace with this
if(!isset($this->username[$i])) {
continue;
}
Credits to Aleksandar Popovic
Related
I'm learning PHP and i'm trying to show an " €" when and only when $autocollant_total_ht_custom isset.
This is what i wrote :
$euro = " €";
if (isset($autocollant_total_ht_custom)) {
$autocollant_total_ht_custom = $autocollant_total_ht_custom . $euro;
} else echo " ";
However my " €" is always showing even when $autocollant_total_ht_custom is not set.
I spent 75 minutes on it, trying and failing again and again despite researching.
I also tried with !is_null, !is_empty with the same result.
I'm fairly certain that my logic isn't wrong but the way to do it is.
Anyone to the rescue?
Have a nice Saturday everyone !
Mike.
Edit 1:
A little visual aid image
My goal was to only show the content of a cell if there was indeed something in it. By default i could see 0 in the empty cells.
if (!$autocollant_total_ht_lot10) {
$autocollant_total_ht_lot10 = " ";
} else echo "error ";
if (!$autocollant_total_ht_lot20) {
$autocollant_total_ht_lot20 = " ";
} else echo " ";
if (!$autocollant_total_ht_lot50) {
$autocollant_total_ht_lot50 = " ";
} else echo " ";
if (!$autocollant_total_ht_custom) {
$autocollant_total_ht_custom = " ";
} else echo " ";
I know my code must look primitive but it works and i don't see it making a conflict with what we are trying to achieve in the initial question.
Then, as asked, this is what i'm writing in the table row and table data :
<tr>
<td class=table_align_left>A partir de 100</td>
<td><?php echo $autocollant_prix ?></td>
<td><?php echo $autocollant_custom?></td>
<td><?php echo $autocollant_total_ht_custom?> </td>
</tr>
So in short, i'm trying to not show anything if there's no value to be shown (which is currently working) and then adding a " €" after the variable is there's something to be shown.
Edit 2 :
My primitive code : my_code
Edit 3 :
The $autocollant_total_ht_custom is already conditioned to be shown earlier in this statement :
} elseif($autocollant_quantité >= 90 && $autocollant_quantité <= 99){
$autocollant_quantité_lot50 = 2;
} elseif($autocollant_quantité >= 100 && $autocollant_quantité <= 1000){
$autocollant_custom = $autocollant_quantité;
} else echo "entrée invalide";
$autocollant_total_ht_custom = $autocollant_prix * $autocollant_custom;
$autocollant_total_ht_lot10 = $autocollant_prix_lot10 * $autocollant_quantité_lot10;
$autocollant_total_ht_lot20 = $autocollant_prix_lot20 * $autocollant_quantité_lot20;
$autocollant_total_ht_lot50 = $autocollant_prix_lot50 * $autocollant_quantité_lot50;
$pointeuse_total_ht = $pointeuse_prix * $pointeuse_quantité;
$pointeuse_autocollant_offert = $pointeuse_quantité * 10;
$pointeuse_autocollant_offert_total_ht = $pointeuse_autocollant_offert * $autocollant_prix;
$pointeuse_autocollant_offert_total_ht = $pointeuse_autocollant_offert * $autocollant_prix;
I posted my code if that can help.
Mike.
//$autocollant_total_ht_custom = null;
$autocollant_total_ht_custom = "something that isnt null";
//if you switch the variable assignment above you will see it behaves as expected.
$euro = "€";
if (isset($autocollant_total_ht_custom))
{
echo $autocollant_total_ht_custom = $autocollant_total_ht_custom . " " .$euro;
}
else
{
//$autocollant_total_ht_custom wouldn't be set at all if we reach this point, this is why im un-sure what your requirements are. Nothing would be echoed.
echo $autocollant_total_ht_custom;
}
Something like this maybe? It's hard to understand your exact requirements.
IsSet checks if a variable is set to something if its not null then it passes the test, and if you're manipulating strings at this variable then it will never be null, meaning the euro sign will always show up.
If the variable IS null then you fail the conditional test, hit else and echo nothing a null string.
If you can update your answer with what you would expect "$autocollant_total_ht_custom" to be set to, I can help better.
EDIT:
Seems to me you can simplify what you what, basically we are only concerned with echoing a string at all if there is something set, otherwise there's no point doing anything, so your checks could be as simple as
$autocollant_total_ht_lot10 = null;
$autocollant_total_ht_lot11 = "";
$autocollant_total_ht_custom = "1,000";
$euro = "€";
if (isset($autocollant_total_ht_custom))
{
echo 'ht custom';
echo TDFromString($autocollant_total_ht_custom, $euro);
}
//notice this doesnt output anything because it isnt set
if (isset($autocollant_total_ht_lot10, $euro))
{
echo 'lot 10';
echo TDFromString($autocollant_total_ht_lot10, $euro);
}
//notice this does because the string, while empty is something that isnt null
if (isset($autocollant_total_ht_lot11))
{
echo 'lot 11';
echo TDFromString($autocollant_total_ht_lot11, $euro);
}
//lets set it to null and see what happens
$autocollant_total_ht_lot11 = null;
if (isset($autocollant_total_ht_lot11))
{
echo 'lot 11 AGAIN';
echo TDFromString($autocollant_total_ht_lot11, $euro);
}
//it doesnt get printed!
//create a function that takes the string in question,
//and for the sake of your use case also the currency to output,
//that way you could change 'euro' to 'currency'
//and have the sign change based on what the value of the $currency
//string is, eg $currency = "£"
function TDFromString($string, $currency)
{
return '<td>' . $string . ' ' .$currency . '</td>';
}
Live example : https://3v4l.org/r5pKt
A more explicit example : https://3v4l.org/JtnoF
I added an extra echo to indicate (and newlines) which variable is being printed out you dont need it of course!
I'll just note the function name is a good example of a bad function name, as it not only returns a td around the string but also inserts the currency, you may want to name it a little better :)
EDIT EDIT:
A final edit outside the scope of your question, you should look into keeping your data in arrays and working on them instead.
Using the previous example we can reduce the code to just this !
$autocollant_total_ht_lot10 = null;
$autocollant_total_ht_lot11 = "";
$autocollant_total_ht_lot12 = "2,0000000";
$autocollant_total_ht_custom = "1,000";
$euro = "€";
//create an array, and stick all our strings in it, from now, if we need to do something to one of the strings(or all!), we do it through the array
$arrayofLots = array($autocollant_total_ht_lot10, $autocollant_total_ht_lot11, $autocollant_total_ht_lot12, $autocollant_total_ht_custom);
//go over each array 'entry' so the first time is '$autocollant_total_ht_lot10', then '$autocollant_total_ht_lot11' etc
foreach ($arrayofLots as $lot)
{
//and we've been over this bit :)
//$lot is a variable we set so we have something to refer to for the individual array entry we are on, we could just as easily name it anything else
if (isset($lot))
{
echo TDFromString($lot, $euro);
}
}
function TDFromString($string, $currency)
{
return '<td>' . $string . ' ' .$currency . '</td>';
}
Good day. It looks like you are missing the end brace
if (isset($autocollant_total_ht_custom)) {
$autocollant_total_ht_custom = $autocollant_total_ht_custom . $euro;
} else {
echo " ";
}
I´m stuck for 3 days trying to figure it out what is the cause of this problem. Lets go to the details:
A jquery ajax call loads a php file named HELPER, wich when loaded includes another php file called F1 that creates html table trough mysqli queries. Ajax get the response and paste the string in a html DIV. The response is a html table. The web server is apache2.2.
Problem is, the code runs in less than 1 second, but the response takes about 50 seconds. The response is only 20 KB.
Some simple HTML table code.
<?php
if (!$res = $sql->query("A QUERY")) { die('custom error 46'); }
if (!$res->num_rows > 0) { die('custom error 47'); }
$myStr = '';
while ( $row = $res->fetch_object() ) {
if ($row->summary == "1") {
$mysum = " class='qtfck-table-summary'";
$myIsSum = "Sim";
} else {
$mysum = "";
$myIsSum = "";
}
if(intval($row->id_centrodecusto) > 0) {
$mycc = "<input type='checkbox' name='" . $row->id_task . "' value='" . $row->id_centrodecusto . "' CHECKED />";
} else {
$mycc = "<input type='checkbox' name='" . $row->id_task . "' value='' />";
}
$myj = " style='padding-left:" . intval($row->depth) * 10 . "px'";
$myStr = "<tr%s><td>%s</td><td><center>%s</center></td><td><center>%s</center></td><td%s>%s</td><td><center>%s</center></td><td><center>%s</center></td></tr>";
echo sprintf($myStr,$mysum,$row->wbs,$row->depth,$myIsSum,$myj,$row->name,$row->uniqueid,$mycc);
}
?>
Html Table closure
The timmings:
PHP START: 0.92 sec
PHP END: 0.98 sec
JS RECEIVED DATA: 49.50 sec
JS PROCESSED DATA: 49.56 sec
I did some digging and it looks like the apache/httpd process (shell via top command) is going nuts, taking 100% CPU load during the full 50 seconds of wait.
BUT here´s something funny. If I change the string generated by the sprintf function and, let´s say, set some random string, there´s no problem at all.
Some simple HTML table code.
<?php
if (!$res = $sql->query("A QUERY")) { die('custom error 46'); }
if (!$res->num_rows > 0) { die('custom error 47'); }
$myStr = '';
while ( $row = $res->fetch_object() ) {
if ($row->summary == "1") {
$mysum = " class='qtfck-table-summary'";
$myIsSum = "Sim";
} else {
$mysum = "";
$myIsSum = "";
}
if(intval($row->id_centrodecusto) > 0) {
$mycc = "<input type='checkbox' name='" . $row->id_task . "' value='" . $row->id_centrodecusto . "' CHECKED />";
} else {
$mycc = "<input type='checkbox' name='" . $row->id_task . "' value='' />";
}
$myj = " style='padding-left:" . intval($row->depth) * 10 . "px'";
echo "<TR><TD>eZ6OnMCZgygePZeUQHcqbOmHQDxhDF4KzfkgOd198xhPFV2rRezlIqBdJLY2TcNlO0PLUmK6CQI9PQMZgkLrcoeYIYhM0x9xK4yQXIFb5SLdq32</TD><TD>UTuQPG9WCbOswuJMdkkckMoAW49C71IN9qKdk8OAdRRV3ZuCYxM5GEZKrXXrwE7cWHKTcXTiO4KwGjh1ejENvduZvEVkwA3zoHbWkzEjtFa1GMaNzD2rqswEDSoQix2CLziBNiHD8zliSWu5rvU8wd6dodWBvubvog</TD></TR>";
}
?>
Html Table closure
The response to this request is 50 KB in size.
The timmings:
PHP START: 0.78 sec
PHP END: 0.81 sec
JS RECEIVED DATA: 1.13 sec
JS PROCESSED DATA: 1.19 sec
What I have already tried:
Use ob_start() and ob_end_flush().
Set apache mpm prefork SendBufferSize to a higher value, but I believe it was a long shot, as the longer response (50KB) has no problem.
Use echo instead of sprintf.
Anyone has a clue?
Best regards.
I don´t know why but the problem was caused by the "center" html tags. Somehow the presence of the center tags slowdown the response. I just removed them and created appropriate css classes using "text-align: center" and the problem was gone.
I also did try avoiding PHP to echo the HTML. Even then the tags causes problems again.
Here´s the fix. I just don´t have an explanation for it.
I am making a photo gallery and with every photo I can see how many comments there are on that photo. The code that I have is working like it should except that if there are 0 comments it will give the 'Undefined Offset error: 2'
'Undefined Offset error: 3'
'Undefined Offset error: 4'
'Undefined Offset error: 5'
etc.
This is the code to check how many comments there are:
(reacties = comments)
// check how many comments every photo has.
$reacties;
$query = "select foto from fotosreacties where boek = '" . $_GET['boek'] . "'";
if($result = mysql_query($query)){
while ($r = mysql_fetch_array($result)){
while ($foto = current($fotoArray)) {
if ($foto==$r["foto"]){
$key = key($fotoArray);
} // end if
next($fotoArray);
} // end while
if(!isset($reacties[$key])){
$reacties[$key] = 1;
} // end if
else {
$reacties[$key]++;
} // end else
reset($fotoArray);
} // end while
} // end if
And this is the code to show the picture and the number of comments:
for($i=$begin; $i < $eind; $i++){
$thumb = str_replace($path2, $thumbPath, $fotoArray[$i]);
echo "<td align='center'><a href='" . $_SERVER['PHP_SELF'] . "?page=album&boek=" . $originalPath . "&fotoID=" . $i . "'><img border='0' src='" . $thumb . "' height='100'><br>";
echo "<small>reacties (";
if($reacties[$i]==0){
echo "0";
} // end if
else {
echo $reacties[$i];
} // end else
echo ")</small>";
echo "</a></td>";
$fotonr++;
if($fotonr == ($clm + 1)){
echo "</tr>\n<tr>";
$fotonr = 1;
} // end if
If anyone knows what I have done wrong and/or knows how to solve this it would be great!
You can embed the counter in your query:
select foto, count(*) AS counter_comments from fotosreacties where boek = '" . $_GET['boek'] . "'. In the result, you can use $r['counter_comments'] and check whether its 0 or more.
About your code:
Stop using MySQL-functions in new applications since they will be deprecated soon. Use MySQLi or PDO instead!
Never trust user input like $_GET, you at least sanitize it by (for example) mysql_real_escape_string().
Sorry for the huge ignorance on the topic, but I really have no idea where to look other than this website when I come into trouble with my PHP.
What I'm trying to do here is use pre-designated IDs to call particular movies from a database. But all I get is an 'Invalid argument supplied for foreach()' message on the second and third foreach's below.
Here's my code in the head:
//Custom lists of movies to bring in
//New Releases list
$films_new_releases = array(40805, 46705, 41630, 44564, 39451, 20352, 43933, 49009, 49797, 42194);
//Most Popular list
$films_most_popular = array(27205, 16290, 10138, 41733, 37799, 18785, 19995, 17654, 10140, 12162);
//Get information from address bar
$list = $_GET['l'];
if ($list == 'new releases') {
$list_chosen = $films_new_releases;
}
elseif ($list == 'most popular') {
$list_chosen = $films_most_popular;
}
else {
$list_chosen = $films_new_releases;
}
And in amongst the body:
// Loop through each film returned
foreach ($list_chosen as $list_chosen_film) {
$films_result = $tmdb->getMovie($list_chosen_film);
$film = json_decode($films_result);
// Set default poster image to use if film doesn't have one
$backdrop_url = 'images/placeholder-film.gif';
// Loop through each poster for current film
foreach($film->backdrops as $backdrop) {
if ($backdrop->image->size == 'poster') {
$backdrop_url = $backdrop->image->url;
}
}
echo '<div class="view-films-film">
<img src="' . $backdrop_url . '" alt="' . $film->name . '" />
<div class="view-films-film-snippet">
<h2>' . $film->name . '</h2>';
if ($film->certification != null) {
echo '<img src="images/bbfc-' . strtolower($film->certification) . '.png" alt="" />';
}
echo ' <h3>Starring</h3>
<p>';
$num_actors = 0;
foreach ($film->cast as $cast) {
if ($cast->job == 'Actor') {
echo '' . $cast->name . ' ';
$num_actors++;
if ($num_actors == 5)
break;
}
echo ' </p>
<h3>Director</h3>
<p>';
foreach ($film->cast as $cast) {
if ($cast->job == 'Director') {
echo '' . $cast->name . ' ';
}
}
echo ' </p>
</div>
</div>';
}
// End films
}
The little testing I've done is checking what $list_chosen, $list_chosen_film, $films_result and $film actually contain by printing them at the bottom of the page.
$list_chosen shows - Array, $list_chosen_film shows - 42194, $films_result shows the entire JSON string, $film shows - Array.
Try adding:
print_r($film->backdrop);
before the second foreach() loop. Before the error message it won't be an array or it will contain zero elements (not allowed). If you also add:
echo $films_result;
you will be able to debug it and fully understand what is wrong. If not, post the whole output in your question.
This happens, because - as error displayed by PHP informed you - you have provided wrong parameter to foreach loop, probably null or some other value. Make sure you are providing array to foreach.
Also, every time you use foreach, do it like that:
if (count($some_list) > 0) {
foreach ($some_list as $list_item) {
// code for each item on the list
}
} else {
// code when there is nothing on the list
}
This will ensure you will not see errors just because there is nothing on the list.
EDIT:
On the documentation page you can find some tip how to avoid such errors if the collection you are trying to iterate through is empty. Just cast the collection to array type:
foreach ((array) $some_list as $list_item) {
// code for each item on the list
}
Can you provide a dump of $film? The error is telling you that you are pointing to an object that cannot be iterated through (most likely null).
Please forgive the extreme-beginner style of coding. I'm working with PHP and JSON strings from an API for the first time.
What I'm trying to do here, which obviously doesn't work if you look through it, is print out multiple movie results that the user is searching for. This is a search results page - with a movie poster and some key details next to each item.
One of the things I want next to each result is a list of the first 5 actors listed in the movie, as "Starring" and then any directors listed in the movie as "Director".
The problem is no doubt the fact that I've nested foreach statements. But I don't know any other way of doing this.
Please please the simplest answer would be the best for me. I don't mind if it's bad practice, just whatever solves it quickest would be perfect!
Here's the code:
// Check if there were any results
if ($films_result == '["Nothing found."]' || $films_result == null) {
}
else {
// Loop through each film returned
foreach ($films as $film) {
// Set default poster image to use if film doesn't have one
$backdrop_url = 'images/placeholder-film.gif';
// Loop through each poster for current film
foreach($film->backdrops as $backdrop) {
if ($backdrop->image->size == 'thumb') {
$backdrop_url = $backdrop->image->url;
}
}
echo '<div class="view-films-film">
<img src="' . $backdrop_url . '" alt="' . strtolower($film->name) . '" />
<div class="view-films-film-snippet">
<h2>' . strtolower($film->name) . '</h2>
<img src="images/bbfc-' . strtolower($film->certification) . '.png" alt="" />
<h3>Starring</h3>
<p>';
$num_actors = 0;
foreach ($films[0]->cast as $cast) {
if ($cast->job == 'Actor') {
echo '' . $cast->name . ' ';
$num_actors++;
if ($num_actors == 5)
break;
}
}
echo ' </p>
<h3>Director</h3>
<p>';
foreach ($films[0]->cast as $cast) {
if ($cast->job == 'Director') {
echo '' . $cast->name . ' ';
}
}
echo ' </p>
</div>
</div>';
// End films
}
}
An example of the result would be this:
with line 120 being foreach ($films[0]->cast as $cast) { and line 131 being foreach ($films[0]->cast as $cast) {
Why are you using $films[0] when you're in a foreach ($films as $film)? You should be using $film->cast right? And you should dump $film at the start of your loop with var_dump and inspect it - make sure $cast is an array and is populated. If it's not, work back from there.