How do I add nl2br and htmlentities in this code - php

I'm in need of some help. How can I output the nl2br() and htmlentities() functions into my code? Both need to be applied to 'content' but htmlentities to 'title'.
<?php
$sql = "
SELECT
post.id AS postid, post.title AS title, post.created,
DATE_FORMAT(Created, '%d-%m-%Y') AS created,
post.content AS content, post.image AS image,
post.alttext AS alttext, blog.id, blog.blogname
FROM
post
LEFT JOIN
blog ON post.blogid = blog.id
WHERE
blogid = \"" .(int)$_GET['id'] . "\"
ORDER BY
postid DESC";
$results = $db->query($sql);
if ($results->num_rows) {
while ($row = $results->fetch_object()) {
echo "<hr>
<h3>{$row->title}</h3>
<p>{$row->created}</p>
<p>
<div id='blog-image'>
<img src='images/{$row->image}' alt='{$row->alttext}'>
</div>
{$row->content}
</p>";
}
} else {
echo 'No Results';
}
?>

You can use a new variable for that:
if ($results->num_rows) {
while ($row = $results->fetch_object()) {
$title = htmlentities($row->title);
$content = nl2br(htmlentities($row->content));
echo "<hr>
<h3>{$title}</h3>
<p>{$row->created}</p>
<p>
<div id='blog-image'>
<img src='images/{$row->image}' alt='{$row->alttext}'>
</div>
{$content}
</p>
";
}
}
Or break the string:
if ($results->num_rows) {
while ($row = $results->fetch_object()) {
echo "<hr>
<h3>". htmlentities($row->title) ."</h3>
<p>{$row->created}</p>
<p>
<div id='blog-image'>
<img src='images/{$row->image}' alt='{$row->alttext}'>
</div>
". nl2br(htmlentities($row->content)) ."
</p>
";
}
}

The neatest way is to abstract the fetch process, so that the fact that data needs demangling, is abstracted away from the view process which draws the result.
Add a function :-
function demangle_row($row) {
$row->content = nl2br($row->content);
$row->content = htmlentities($row->content);
$row->title = htmlentities($row->title);
}
Now change the while statement, to use the above code so
While($row = $results->fetch_object()) {
becomes
While($row = demangle_row($results->fetch_object())) {

Related

multiple echo statements in one echo?

I am relatively new to PHP and want to know a more efficient way of echo'ing the following in less steps or even just one statement.
$sql = "SELECT * FROM comments";
$result = OpenCon()->query($sql);
while( $row = $result->fetch_assoc()) {
echo "<div class='card'><p class: card-text>";
echo $row['uid']."<br>";
echo $row['date']."<br>";
echo $row['message']."<br><br>";
echo "</p></div>";
As #droopsnoot has commented on above, you should try doing the next thing here.
while( $row = $result->fetch_assoc()) {
echo "<div class='card'><p class: card-text>". $row['uid']."<br>" . $row['date']."<br>".$row['message']."<br><br>". "</p></div>";
}
It should work perfectly.
Another option is to close php tag (?>) and use html markup with <?=$var?>:
<?php
$sql = "SELECT * FROM comments";
$result = OpenCon()->query($sql);
while( $row = $result->fetch_assoc()) {?>
<div class="card">
<p class="card-text">
<?=$row['uid']?><br>
<?=$row['date']?><br>
<?=$row['message']?><br><br>
</p>
</div>
<?php
} // end while

Invalid argument supplied for foreach()

i'm coding a project and have some troubles when the system inform error:
Invalid argument supplied for foreach() in:
foreach($dbh->query($q1) as $row)
and can't get data from the database. How can i fix it, im a newbie, so if i don't understand, please teach me! thanks!
thank for your helps but i still can't fix it
<?php include("top.html"); ?>
<body>
<div id="main">
<h1>Results for <?php echo $_GET['firstname'] . " " . $_GET['lastname'] ?></h1> <br/><br/>
<div id="text">All Films</div><br/>
<table border="1">
<tr>
<td class="index">#</td>
<td class="title">Title</td>
<td class="year">Year</td>
</tr>
<?php
$dbh = new PDO('mysql:host=localhost;dbname=imdb_small', 'root', '');
$q1 = "SELECT id
FROM actors
WHERE first_name = '".$_GET['firstname']."' AND last_name = '".$_GET['lastname']."'
AND film_count >= all(SELECT film_count
FROM actors
WHERE (first_name LIKE'".$_GET['firstname']." %' OR first_name = '".$_GET['firstname']."')
AND last_name = '".$_GET['lastname']."')";
$id = null;
foreach($dbh->query($q1) as $row){
$id = $row['id'] ;
}
if($id == null){
echo "Actor ".$_GET['firstname']." ".$_GET['lastname']."not found.";
}
`
$sql2 = "SELECT m.name, m.year
FROM movies m
JOIN roles r ON r.movie_id = m.id
JOIN actors a ON r.actor_id = a.id
WHERE (r.actor_id='".$id."')
ORDER BY m.year DESC, m.name ASC";
$i = 0;
foreach($dbh->query($sql2) as $row){
echo "<tr><td class=\"index\">";
echo $i+1;
echo "</td><td class=\"title\">";
echo $row['name'];
echo "</td><td class=\"year\">";
echo $row['year'];
echo "</td></tr>";
$i++;
}
$dbh = null;
?>
</table>
</div>
</div>
<?php include("bottom.html"); ?>
</body>
</html>
Check that your query succeeded before iterating on the result:
if (false !== ($result = $dbh->query($d1))) {
foreach($result as $row){
$id = $row['id'] ;
}
}
By the way, I don't understand what you are trying to do with this pointless loop.
You could do this
$st = $dbh->query($q1);
if ( $st ) {
while ( $row = $st->fetch() ) {}
}
Try to make your code more readable
$result = $dbh->query($q1);
foreach($result as $row){$id = $row['id'];}

While function in echo

I have some php code that looks like :
echo"
<tr>
<td colspan=\"2\">" . get_comment(${'imgmodp_data_' . $i}['primid']) . "</td>
</tr>
";
My get_comment function:
function get_comment($primid)
{
$dbCon = mysqli_connect("localhost", "something", "something", "something");
$sql = "SELECT `id_sheep`, `text` FROM `comments` WHERE `primid`='$primid'";
$query = mysqli_query($dbCon, $sql);
while($row = mysqli_fetch_array($query))
{
return = "<div>" . $row['text'] . "</div></br>";
}
}
But this only returns one row each time even if they is multiple rows. If I use echo instead of return it returns all lines but at the top of my document, not in the blocks where it should be...
Any suggestions?
Use a variable before your loop, which you update inside your loop and return after your loop.
If you just use return, you'll stop the function, so after 1 loop.
With echo you output the string directly, but don't stop the loop.
For example:
function get_comment($primid){
$dbCon = mysqli_connect("localhost", "something", "something", "something");
$sql = "SELECT `id_sheep`, `text` FROM `comments` WHERE `primid`='$primid'";
$query = mysqli_query($dbCon, $sql);
$return = '';
while($row = mysqli_fetch_array($query)){
$return .= "<div>" . $row['text'] . "</div></br>";
}
return $return;
}
What about this
echo "<div>" . $row['text'] . "</div></br>";
and place the php code where you want it to show.
<div class="row">
<div class="col-sm-12">
<div class="col-sm-6">
<!-- PHP code goes here -->
</div>
</div>
</div>

Mysql select multiple queries inside eachother

I am having some trouble with selecting data from my database using data from a previous select. What I want to do is. First I let mysql select all vechiles from my database from the table vechiles. I echo them and inside the while loop I try to select the picture for the vechile from a diffrent table by select the picture with the vechile_id:
Now my first question is. Is this the right way to do it? I assume there must be a more neat way but I cant find how.
<?php
$sql = "SELECT id, brand FROM vechiles";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$sql1 = "SELECT * FROM fotos WHERE vechiles_id =". $row['id'];
$result1 = $conn->query($sql1);
echo '<li><p class="title">'. $row['brand'] .'</p>
<p class="type">type: 2387</p>
<p class="ez">ez: 1987</p>';
if ($result1->num_rows > 0) {
// output data of each row
while($row1 = $result1->fetch_assoc()) {
echo '<img src="admin/'. $row1['url'] .'" atl="tractor 1"/>';
}}else{
echo "there are no pictures";
}
echo '<div class="info">
<p class="prijs">Prijs: 1800,- EX BTW</p>
<p class="msg"> Prijzen onder voorgehoud</p>
</div>
<a class="button" href="#">Meer info</a></li>';
}
} else {
echo "0 results";
}
$conn->close();
?>
Noe the above example works fine but I want to only select the first picture instead of all uploaded pictures.
So to this code:
$sql1 = "SELECT * FROM fotos WHERE voertuig_id =". $row['id'];
I added
$sql1 = "SELECT TOP 1 * FROM fotos WHERE voertuig_id =". $row['id'];
And I also tried
$sql1 = "SELECT * FROM fotos WHERE voertuig_id =". $row['id'] . "LIMIT 1";
But when I do that it suddenly says there are no pictures. What am I doing wrong!
appreciate all the help!
You don't need to loop and execute another query for each vehicle, you can do it with a simple join.
select *
from vehicles v
left join fotos f
on f.voertuig_id = v.id;
If there is no matching photo for that vehicle, it will have a null value in your returned array.
This will change your php to something like this:
$last_vehicle = null;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if($row['brand'] != $last_vehicle) {
if($last_vehicle != null) {
echo '<div class="info">
<p class="prijs">Prijs: 1800,- EX BTW</p>
<p class="msg"> Prijzen onder voorgehoud</p>
</div>
<a class="button" href="#">Meer info</a></li>';
}
echo '<li><p class="title">'. $row['brand'] .'</p>
<p class="type">type: 2387</p>
<p class="ez">ez: 1987</p>';
$last_vehicle = $row['brand'];
if ($row['url'] != null) {
echo '<img src="admin/'. $row['url'] .'" atl="tractor 1"/>';
}
else {
echo "there are no pictures";
}
}
}
}
else {
echo "0 results";
}

Basic PHP SQL Query not working

We have a basic PHP script to extract the title and description for each job from a MySQL database as simply display this information. This is what it looks like:
$sql = "SELECT `title`, `desc` FROM jobs WHERE active = 'y'";
$query = mysql_query($sql) or die('<em><strong>SQL Error:</strong> ' . mysql_error() . '</em>');
$results = mysql_fetch_assoc($query);
<?php while($result = mysql_fetch_assoc($query)) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$results['title']}</h2>";
echo "<p>{$results['desc']}</p>";
echo '</div>';
} ?>
Now, this only extracts one row from the database, but it should extract two. So, I tried the following to replace the while statement:
<?php foreach($results as $result) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$result['title']}</h2>";
echo "<p>{$result['desc']}</p>";
echo '</div>';
} ?>
This statement doesn't work either. This just displays (weirdly) the first character of each column in the first row in the table.
Does anyone have any idea as to why this isn't working as it should?
In your while use same variable $result as you started:
while($result = mysql_fetch_assoc($query)) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$result['title']}</h2>";
echo "<p>{$result['desc']}</p>";
echo '</div>';
}
and remove the first $results = mysql_fetch_assoc($query);
Result variable you have used is result not results
Replace
$sql = "SELECT `title`, `desc` FROM jobs WHERE active = 'y'";
$query = mysql_query($sql) or die('<em><strong>SQL Error:</strong> ' . mysql_error() . '</em>');
**$results = mysql_fetch_assoc($query);** // remove this line
<?php while($result = mysql_fetch_assoc($query)) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$results['title']}</h2>";
echo "<p>{$results['desc']}</p>";
echo '</div>';
} ?>
to
$sql = "SELECT `title`, `desc` FROM jobs WHERE active = 'y'";
$query = mysql_query($sql) or die('<em><strong>SQL Error:</strong> ' . mysql_error() . '</em>');
<?php while($result = mysql_fetch_assoc($query)) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$result['title']}</h2>";
echo "<p>{$result['desc']}</p>";
echo '</div>';
} ?>
You already fetched the first row before your loop started, which is why it only prints the second row. Simply comment out that line:
#$results = mysql_fetch_assoc($query); # here is your first row,
# simply comment this line
<?php while($result = mysql_fetch_assoc($query)) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$result['title']}</h2>";
echo "<p>{$result['desc']}</p>";
echo '</div>';
} ?>
You are also looping over $result but using $results in your while loop body.
Check this:
$sql = "SELECT `title`, `desc` FROM jobs WHERE active = 'y'";
$query = mysql_query($sql) or die('<em><strong>SQL Error:</strong> ' . mysql_error() . '</em>');
<?php
while($result = mysql_fetch_assoc($query)) {
echo '<div class="left_content" style="margin-top: 15px;">';
echo "<h2>{$result['title']}</h2>";
echo "<p>{$result['desc']}</p>";
echo '</div>';
}
?>
Change this line
<?php while($result = mysql_fetch_assoc($query)) {
to
<?php while($results = mysql_fetch_assoc($query)) {

Categories