Javascript not working in PHP foreach? - php

I'm using this code to get a maximum of text in a p tag. For one reason this code only runs on the first card in my foreach but not on the second.
Here you see the problem: https://gyazo.com/c3ef858fb233b21b31098fb1682a7ce4
Here is my javascript code:
<script>
function truncateText(selector, maxLength) {
var element = document.querySelector(selector),
truncated = element.innerText;
if (truncated.length > maxLength) {
truncated = truncated.substr(0,maxLength) + '...';
}
return truncated;
}
</script>
[PHP CODE]
<?php
$stmt = $conn->prepare("SELECT naam, prijs, beschrijving, id, image1 FROM salontafels");
$stmt->execute([]);
$rows = $stmt->fetchAll();
foreach ($rows as $row) : { ?>
<a class="formtitellink" href="productsalontafels.php?rowid=<?= $row['id'] ?>">
<?php } echo '
<div class="col-lg-4 col-md-6 mb-4">
<div class="card h-100">
<img class="card-img-top" src="data:image/jpeg;base64,' . base64_encode( $row['image1'] ) . '" />
<div class="card-body">
<h4 class="card-title">
' . $row['naam'] . '</a>
</h4><script> document.querySelector(\'p\').innerText = truncateText(\'p\', 100);</script>
<h5> Log in voor de prijs </h5>
<p class="card-text">' . $row['beschrijving'] . '</p>
</div>
<div class="card-footer">
<small class="text-muted">beschikbaar</small>
</div>
<!-- /.row -->
</div>
<!-- /.col-lg-9 -->
</div>'?>
Does anyone knows what is wrong?

Your problem is that document.querySelector('p') returns the first Element within the document that matches the specified selector. So it just returns the first p tag every time it's run.
This means that these two lines are your problem:
document.querySelector(\'p\').innerText = truncateText(\'p\', 100)
and
var element = document.querySelector(selector)
To fix it, you will need to select the specific element you're interested in each time
[If you want working code, rather than an answer to your question, I suggest just using substr($row['beschrijving'],0,100)]

Related

MYSQL Product listing grid

So i am trying to pull product data from a database and have it listed out in a nice grid. I have got everything to work and its layout is very nice apart from one issue, the image URL isnt pulling properly:
<?php
while ($row = mysql_fetch_array($query))
$rows[] = $row;
foreach ($rows as $row){
$etitle = $row['title'];
$eprice = $row['price'];
$eurl = $row['prod_url'];
$eimage = $row['image'];
echo ('<div class="col-sm-6 col-md-4">
<div class="card">
<div class="card-image" style="background-image: url("' . $eimage . '");">
<div class="card-image-rating">');
echo ('£' . $eprice);
echo ('
</div><!-- /.card-image-rating -->
</div><!-- /.card-image -->
<div class="card-content">
<h2><a href="' . $eurl . '">');
echo $etitle;
echo ('</a></h2>
</div><!-- /.card-content -->
<div class="card-actions">
<i class="md-icon">favorite</i>
Show More
</div><!-- /.card-actions -->
</div><!-- /.card -->
</div><!-- /.col-* -->');
} ?>
In the source code and on page everything look good apart from their being no image. The column in the database has a URL of the image location in it but in the source code it appears to be removing the / from the path.
Any help would be amazing.
Thanks,
Based on your script, I noticed something goes wrong
<div class="card-image" style="background-image: url("' . $eimage .'");">
you use double quotation marks in style section
your html will look like this
<div class="card-image" style="background-image: url(" ");">
which is shouldn't be like that.
you have to use Apostrophe inside style, since u use quotation mark for style
your html should like this
<div class="card-image" style="background-image: url(' ');">
here, an example for you
https://jsfiddle.net/have_full/kass6ukr/

Php search function displaying null

Hi guys so i am just using learning php for the first time and building my own site etc to try it out. I have a database of recipes. For each recipe it has a list of ingredients. Each recipe will have different amounts. So one will have 5, the other can have 3 etc. The problem with my code is. If someone searches for a recipe and they find it, it will return the ingredients but sometimes if it has more than the divs i put there it will give some null values back. Also i understand about the sql injections etc and the bad practice but i am just playing about with it first. I want to get it to work and then fix that part later :)
PHP:
<div class="panel panel-default">
<div class="panel-heading"><b>' . htmlentities($rN, ENT_QUOTES) . '</b></div>
</a>
}
?>
Now i am pretty sure in my white loop i am suppose to do an if statement after the div tags and say if the value == null then dont display but i have tried and nothing has worked so any help on this matter would be great
Thanks
Your HTML for ingredients seems be repeating, so you can resolve the empty <div> issue and short your code using a for loop and a if condition:
$output .= '<div class="panel panel-default">
(...)
<h3 class="media-heading">INGREDIENTS:</h3>';
for( $i=1; $i < 7; $i++ )
{
if( ${"rI$i"} )
{
$output .= '<div class="food-graph">
<span class="food-graph-title">' . htmlentities(${"rI$i"}, ENT_QUOTES) . '</span>
</div>';
}
}
$output .= ' (...) ';
If encountering null values is a problem, this will only print out the ingredients that your row contains.
while($row = mysql_fetch_array($query)) {
$rN = $row['recipeName'];
$i=1;
$recipes = '';
if (isset($row['recipe_ing'.$i]) {
while(isset($row['recipe_ing'.$i]) {
$value = htmlentities($row['recipe_ing'.$i], ENT_QUOTES);
$recipes .= <<< EOT
<div class="food-graph">
<span class="food-graph-title">$value</span>
</div>
EOT;
$i++;
}
$output .= <<< EOT
<div class="panel panel-default">
<div class="panel-heading"><b>' . htmlentities($rN, ENT_QUOTES) . '</b></div>
<div class="panel-body">
<div class="pull-left col-xs-12 col-sm-4">
<a href="#">
<img class="img-thumbnail img-responsive" src="Image/green.jpg">
</a>
<a class="btn btn-success btn-block btnrec" href="#">View Recipe</a>
</div>
<div class="col-xs-12 col-sm-6 col-md-6">
<div class="media-body">
<h3 class="media-heading">INGREDIENTS:</h3>
$recipes
</div>
</div>
</div>
</div>
<div class="panel-footer">Rating</div>
</div>
EOT;
}
}
EDIT: Also, i'm using Heredocs to set the strings. the lines with EOT; must have no whitespace or code in front of it. it must be at the start of the line. also no code may be on the same line behind it. Else, your documents will become a huge string.

PHP while loop different images

Okay let me clarify everything.
Chars table looks like http://prntscr.com/9v8jiv .
Here is the standard html
<div id="characterone">
<h1 class="charactername">Test_Name</h1>
<p class="characterstats">DOB: 12/01/1992</p>
<p class="characterstats">Origin: Mexican</p>
<p class="characterstats">Time in Los Santos: 56</p>
<button class="choosebutton">Choose</button>
</div>
<div id="charactertwo">
<h1 class="charactername">Angelo_Damce</h1>
<p class="characterstats">DOB: 12/01/1992</p>
<p class="characterstats">Origin: American</p>
<p class="characterstats">Time in Los Santos: 26</p>
<button class="choosebutton">Choose</button>
</div>
<div id="characterthree">
<h1 class="charactername">Moemen_Walid</h1>
<p class="characterstats">DOB: 12/01/1992</p>
<p class="characterstats">Origin: American</p>
<p class="characterstats">Time in Los Santos: 26</p>
<button class="choosebutton">Choose</button>
</div>
All I want to do is, to select someone's logged in characters and then he sees the 3 in front of him and then he chooses,
I began by normaling querying them
$getchars = mysqli_query($con,"SELECT * FROM `characters` where Username = '".$user."'") or die('Error: ' . mysqli_error($con));
$check = mysqli_num_rows($getchars);
Now I need to find a way so for every char the mysql query find, to be echo'ed or written in the html up.
Eg: echo ''.$row[1]["Name"].' ';
but in each div there should be a different echo
'.$row[2]["Name"].'
^ But of course this code isn't real. just trying to explain.
Ok Here is the complete answer for your question. Just replace the Name and Time Column names with the correct Column names in the database.
$i = 1;
while($rowget = mysqli_fetch_array($getchars))
{
$id1 = 'characterone';
$id2 = 'charactertwo';
$id3 = 'characterthree';
if($i<4){
echo'<div id="'.${'id'.$i}.'">';
echo '<h1 class="charactername">'.$rowchar["Name"].'</h1>
<p class="characterstats">DOB: '.$rowchar["Birthdate"].'</p>
<p class="characterstats">Origin: '.$rowchar["Origin"].'</p>
<p class="characterstats">Time in Los Santos: '.$rowchar["Skin"].'</p>
<button class="choosebutton">Choose</button>';
echo '</div>';
}
$i++;
}
just use a counter
$i=1;
while($rowget = mysqli_fetch_array($getchars)) {
$charpost = $rowget["Character"];
echo' <img src=$i.png> ';
$i++;
}

Return breaks my while loop when writing out rows from the database

I have a table with comments that contain users profilepicture, comment and userid. My code looks like this:
while($Msg = $event->fetch())
{
echo '
<div class="activity" id="'.$Msg['id'].'">
<div class="settings"><hr><hr><hr></div>
<div class="actSwine"></div>
<div class="act delete" id="delete">×<div class="abtSwine"></div><div class="abtbtn" id="deletewid">Radera</div></div>
<div class="act" id="favo" onclick="alert(\'hello world\');">Favorisera<br><div class="abtSwine"></div><div class="abtbtn" id="favowid">Inlägget kommer att hamna under "Mina favoriter"</div></div>
<div class="act" id="raport" onclick="alert(\'hello world\');">Anmäl<br><div class="abtSwine"></div><div class="abtbtn" id="raportwid">Det här inlägget är kränkande.</div></div>
<div id="clear"></div>
<div class="activitylabel">
<img src="'.$this->GetUserId($Msg['userid'], 'Profilepic').'" />
<div class="activityname"><?php echo "#".$username." , " . $fname . " " . $lname ?></div>
<div class="activitydomain"><?php echo $domain; ?></div>
<div id="clear"></div>
<p>
'.$Msg['message'].'
</p>
</div>
</div>
';
}
this returns only i 1 rows from the database. The functions that breaks my while loop is used here "<img src="'.$this->GetUserId($Msg['userid'], 'Profilepic').'"/>". It returns a value given in the parameters, in this case the profilepicture of my user.
how can i do this differently without breaking the while loop? because as it has come to my understanding, a return pauses the while loop. This result in only printing out 1 comment from the database.
return from the function doesn't break anything here.
All you have here is some error which breaks page rendering.
Errors are in these two lines:
'<div class="activityname"><?php echo "#".$username." , " . $fname . " " . $lname ?></div>
<div class="activitydomain"><?php echo $domain; ?></div>'
As you already start echoing, doing echo while echo is invalid. So - fix this lines.

Filtering Search Query with AngularJS and PHP

I have a music store type of application and I use php to get images and names of specific musical instruments from a database. I want to incorporate a search bar that dynamically filters the musical instruments, and I want to use AngularJS to do this. I'm having trouble after creating the $watch in AngularJS. I know how to filter using a JS object, but I am having trouble with this scenario.
I am assuming I could create a JS object from the innerHTML from the required elements. Then I could use an ng-repeat to filter through the object based on what is in the input search box. Is that a valid option? If so are there any other options available?
HTML/PHP
<div ng-controller="instController">
<div class="col-md-12" id="search-instrument-wrapper">
<input class="searchbar" type="text" ng-model="searchInst" placeholder="Search Instruments"/>
</div>
<?php foreach ($instruments as $singleInstrument) : ?>
<div class="col-md-4 instrument-wrapper">
<a href='instruments/<?php echo $singleInstrument; ?>.php#/'>
<span class="inst-thumbnail">
<img class="img-responsive instrument-images" src="images/<?php echo $singleInstrument; ?>"/>
</span>
</a>
<a href='instrument/<?php echo $singleInstrument ?>/<?php echo $singleInstrument ?>.php#/'>
<h3 class="instrumentName"><?php echo $instrumentInfo['instrumentName'];?></h3>
</a>
</div>
</div>
<?php endforeach; ?>
<?php endif; ?>
AngularJS
instApp.controller('instController',['$scope', function($scope){
$scope.searchInst = '';
$scope.$watch('searchInst',function(newVal,oldVal){
/*** MY ATTEMPT ***/
if(!$( ".instrumentName:contains('"+newVal+"')" )){
$(this).parent().css( "display",
"none" );}
/******************/
});
}]);
I was able to figure it out doing it the way that was described in the comments:
The key is to post your data from the database into a foreach loop and concatenate a string to create a JSON object. Then use ng-init to initialize the JSON for the ng-repeat to use. Works for me
PHP
foreach($instrumentsArray as $instruments){
$jsonStatement .= '{
name:"' . $instrumentInfo['instrumentName'] . '"' .
',url: "user/' . $instruments . '/' . $instruments . '.php#/"'.
',img: "user/' . $instruments . '/images/' . $instrumentPicInfo['instrumentPic'] . '"},';
$jsonComplete = 'instruments = [' . $jsonStatement . ']';
HTML
<div ng-init='<?php echo $jsonComplete;?>'></div>
<div class="col-md-12" id="search-instruments">
<input class="searchbar" type="text" ng-model="searchinstruments" placeholder="Search Instruments"/>
</div>
<div class="col-md-4 instrumentWrapper" ng-repeat="instrument in instruments | filter: searchinstruments">
<a href='{{instrument.url}}'>
<span class="instruments-thumbnail">
<img class="img-responsive user-images" src="{{instrument.img}}"/>
</span></a>
{{instrument.name}}</h3>
</div>

Categories