Don't display the specific empty column of row from database - php

I have a working code that can insert and update information from the database and echoing it to page. but I like to hide the specific empty column while displaying all the information from the row. check this screenshot
my goal is to hide the "image" column when its null/empty; so the crock image wont display. here is my code below:
<?php
$result = mysqli_query($mysqli, "SELECT * FROM blogs ORDER BY id DESC");
while ($row = mysqli_fetch_array($result))
if (!empty($row['image'] != ""))
{
echo "<div class='row'>
<div class='col-lg-12 box'>
<div class='content-heading'>
<p>
<text>".$row['title']."</text>
</p>
</div>
<p>
<text1 class='pull-right' >".$row['image_text']."</text1><br/>
<img class='img-size' id='hp'src='admin/upload_images/".$row['image']."'/>
<text>".$row['definition']."</text>
</p>
</div>
</div>";
}
?>
but this code if (!empty($row['image'] != "")) is hiding the entire row from my database.
Can anyone have a right solution to my problem?

You could try using the style attribute of the <img> tag to selectively show or hide the image tag:
<img class='img-size'
id='hp'
style='display: '. ($row["image"] != "" ? "block" : "none") . ';'
src='admin/upload_images/".$row['image']."'/>

Instead of hiding entire row, you could just hide the image tag, like this:
<?php
$result = mysqli_query($mysqli, "SELECT * FROM blogs ORDER BY id DESC");
while ($row = mysqli_fetch_array($result))
{
echo "
<div class='row'>
<div class='col-lg-12 box'>
<div class='content-heading'>
<p>
<text>".$row['title']."</text>
</p>
</div>
<p>
<text1 class='pull-right' >".$row['image_text']."</text1><br/>
";
if (!empty($row['image'])) {
echo "<img class='img-size' id='hp'src='admin/upload_images/".$row['image']."'/>";
}
echo "
<text>".$row['definition']."</text>
</p>
</div>
</div>
";
}
?>

Your if condition will hide all other html elements as well instead you should hide only img tag when no value found for image.
Update your code as below :
while ($row = mysqli_fetch_array($result)) {
$image = (!empty($row['image'])) ? "<img class='img-size' id='hp'src='admin/upload_images/" . $row['image'] . "'/>" : "";
echo "<div class='row'>
<div class='col-lg-12 box'>
<div class='content-heading'>
<p>
<text>" . $row['title'] . "</text>
</p>
</div>
<p>
<text1 class='pull-right' >" . $row['image_text'] . "</text1><br/>
" . $image . "
<text>" . $row['definition'] . "</text>
</p>
</div>
</div>";
}

Related

How to fetch news from a db and print them on a PHP page?

I want to fetch the last two news from a DB, then print them on a PHP page using a function.
The two news should be printed one next to the other.
This is what I've done so far, what am I doing wrong?
This is the problem:
<?php
function getAllNewsHome(){
$connection = mysqli_connect("localhost", "root", "", "serverName");
$connection->query("SET NAMES 'utf8'");
$rsNewsHome = mysqli_query($connection, "SELECT * FROM news ORDER BY id DESC LIMIT 2");
$newsHome = mysqli_fetch_all($rsNewsHome, MYSQLI_ASSOC);
mysqli_close($connection);
for($i=0; $i < count($newsHome); $i++){
echo "
<div class='container'>
<div class='row'>
<div class='col-xs-6'>
<h1>".$newsHome[$i]['title']."
</h1>
<p>".$newsHome[$i]['content']."
</div>
<div class='col-xs-6'>
<h1>".$newsHome[$i]['title']."
</h1>
<p>".$newsHome[$i]['content']."
</div>
</div>
</div>
";
}
}
?>
This might be the easiest: increment $i inside of your loop, then make sure that it exists before you echo it out. This will allow you to keep your divs aligned:
for($i = 0; $i < count($newsHome); $i++) {
echo "
<div class='container'>
<div class='row'>
<div class='col-xs-6'>
<h1>" . $newsHome[$i]['title'] . "
</h1>
<p>" . $newsHome[$i]['content'] . "</p>
</div>";
$i++;
echo "
<div class='col-xs-6'>";
if(array_key_exists($i, $newsHome)) {
echo "<h1>" . $newsHome[$i]['title'] . "
</h1>
<p>" . $newsHome[$i]['content'] . "</p>";
}
echo "
</div>
</div>
</div>
";
}
It's doing exactly what you told it to do! Inside the for($i=0; $i < count($newsHome); $i++) loop it produces 2 divs, each containing the same "news" ( $newsHome[$i]['title']) twice!
You want the first div to contain the first article and the second div to contain the second article.
If you remove the second div within the for loop, it will create one div for each "news".
(And you will likely have to move the 2 outer divs (<div class='container'> and <div class='row'> outside the loop)

Displaying data from while loop into html code

I need tips or direction on how can I display data from mysql using echo. But I want to display it in html code. I want to display $row["title"] of first title in mysql instead title1 and $row["content"] of first content in mysql instead content1 and do that for all 3 divs. php code works fine I just can't figure out how to make that possible.
<div class="carousel-inner" style="background-size:cover;">
<div class="item active">
<img src="img/road1.jpg">
<div class="carousel-caption d-none d-md-block">
<h2>title1</h2>
<p>content1</p>
</div>
</div>
<div class="item">
<img src="img/road2.jpg">
<div class="carousel-caption d-none d-md-block">
<h2>title2</h2>
<p>content2</p>
</div>
</div>
<div class="item">
<img src="img/road3.jpg">
<div class="carousel-caption d-none d-md-block">
<h2>title3</h2>
<p>content3</p>
</div>
</div>-->
<?php
session_start();
include_once("db.php");
$sql = "SELECT * FROM news";
$query = mysqli_query($conn, $sql);
if (mysqli_num_rows($query) > 0) {
while($row = mysqli_fetch_assoc($query)) {
echo "<h2>" . $row["title"] . "</h2>";
echo "<p>" . $row["content"] . "</p>";
}
} else {
echo "0 results";
}
?>
You're almost there. Just move the html into the echo of the while loop.
echo '<div class="carousel-inner" style="background-size:cover;">';
$counter = 1;
while($row = mysqli_fetch_assoc($query)) {
echo '
<div class="item ' . ($counter == 1 ? 'active' : '') . '">
<img src="img/road{$counter}.jpg">
<div class="carousel-caption d-none d-md-block">
<h2>' . $row["title"] . '</h2>
<p>' . $row["content"] . '</p>
</div>
</div>';
$counter++;
}
echo '</div>';
The only issue is the image, realistically you'd save the image in the database with the title and content then use the same method but for this simple case lets just use a counter
please note that I change your entire code a little bit to make the desired results...
<div class="carousel-inner" style="background-size:cover;">
<?php
session_start();
include_once("db.php");
$sql = "SELECT * FROM news";
$query = mysqli_query($conn, $sql);
if (mysqli_num_rows($query) > 0) {
while($row = mysqli_fetch_assoc($query)) { ?>
<div class="item active">
<img src="img/road1.jpg">
<div class="carousel-caption d-none d-md-block">
<h2><?php echo $row["title"]; ?></h2>
<p><?php echo $row["content"]; ?></p>
</div>
</div>
<?php
}
} else {
echo "0 results";
}
?>
Also note that I'm repeating just the first image... You need an extra on planning to determine how to handle images in code and then update this one.

Deleting specific article from database with PHP

I'm creating a blog site and I got stuck in this phase where I want to allow authors to delete their own posts, they can already see the delete button below each of their posts. In the DB table I have an author, content and ID of the article. Now I need to get the specific ID of the article that they want to delete, but I have no idea how to do this, the delete button is the same for every article, so I can't use that for help. I have this code to get articles from my DB and the button click code ready. For better imagination here is an image of the site -
... previous code
<?php }
$articles->ArticlesConn();
$result = mysql_query("SELECT * FROM articles_table");
while($row = mysql_fetch_array($result)){ // loop to generate content
?>
<div class="container"> // responsive stuff
<div class="row"> // responsive stuff
<div class="twelve columns"> // responsive stuff
<?php
echo "<h3>" . $row['Title'] . "</h3>
<p>" . $row['Content'] . "</p>"; ?>
</div>
</div>
<div class="row">
<div class="eight columns">
<address><?php echo "Author - " . $row['Author']; ?> </address><br><br><br> /// nick of the author below each article
</div>
<div class="four columns">
<?php
if ($row['Author'] == $_SESSION["username"]) // show delete button if the logged user is an author of generated article
{ ?>
<input type="button" name="delete" value="Delete article"/>
<?php } ?>
</div>
</div>
</div>
<?php
}
?>
To solve your problem, you should add a form to wrap your input.
This form will call the page itself. In this form there is a hidden input with the value of the article id. So when you submit the form, you can get the article id via $_POST['name of the hidden input'].
I will show you the code :
<?php }
if (isset($_POST['article-id'])) {
// prevent SQL injection
$articleId = mysql_real_escape_string($_POST['article-id']);
$res = mysql_query('DELETE FROM articles_tab WHERE id='.$articleId);
if (!$res) {
die(mysql_error());
}
}
$articles->ArticlesConn();
$result = mysql_query("SELECT * FROM articles_table");
while($row = mysql_fetch_array($result)){ // loop to generate content
?>
<div class="container"> // responsive stuff
<div class="row"> // responsive stuff
<div class="twelve columns"> // responsive stuff
<?php
echo "<h3>" . $row['Title'] . "</h3>
<p>" . $row['Content'] . "</p>"; ?>
</div>
</div>
<div class="row">
<div class="eight columns">
<address><?php echo "Author - " . $row['Author']; ?> </address><br><br><br> /// nick of the author below each article
</div>
<div class="four columns">
<?php
if ($row['Author'] == $_SESSION["username"]) // show delete button if the logged user is an author of generated article
{ ?>
<form method="post">
<input type="hidden" name="article-id" value="<?php echo $row['ID'] ?>"/>
<input type="submit" value="Delete article"/>
</form>
<?php } ?>
</div>
</div>
</div>
<?php
}
But you should use mysqli or PDO instead of the old mysql extension, look at this : http://php.net/manual/en/function.mysql-query.php

Looping results to insert new div with complexities

How can I loop results to insert new div with complexities for each result?
I have the following database table with following columns:
ID | UserID | Title | Introduction | Content | Images | Background | Date | Pinned
I have the following PHP code:
if($latest = $con->query("SELECT * FROM Posts WHERE Pinned='0' LIMIT 4")) {
if($latest->num_rows > 0) {
//<-- result loop here
} else {
echo '<h1 class="alert fade">No Posts</h1>';
}
$latest->close();
};
I would like to format the output as follows:
<div class="post standard" style="background-image:url([1]);">
<a href="view.php?id=[2]">
<div class="shader"></div>
<div class="info">
<h1>[3]</h1>
<p>[4] - [5]</p>
</div>
</div>
[1] - Background
[2] - ID
[3] - Title
[4] - UserID
[5] - Date
How would I accomplish this?
Here is the code which should do what you need. I used just one echo, you can split it into more echoes, or go out of PHP block. Doesn't matter.
<?php
if ($latest->num_rows > 0) {
while ($row = $latest->fetch_assoc()) {
echo '
<div class="post standard" style="background-image:url(' . $row['background'] . ');">
<a href="view.php?id=' . $row['id'] . '">
<div class="shader"></div>
<div class="info">
<h1>' . $row['title'] . '</h1>
<p>' . $row['userID'] . ' - ' . $row['date'] . '</p>
</div>
</div>
';
}
}
?>
Example with putting HTML code outside PHP block.
<?php
if ($latest->num_rows > 0) {
while ($row = $latest->fetch_assoc()) {
?>
<div class="post standard" style="background-image:url('<?php echo $row['background']; ?>');">
<a href="view.php?id=<?php echo $row['id'] ?>">
<div class="shader"></div>
<div class="info">
<h1><?php echo $row['title']; ?></h1>
<p><?php echo $row['userID']; ?> - <?php echo $row['date']; ?></p>
</div>
</div>
<?php
}
}
?>
Well, what I do is the following
let's say that we're inside the loop for example
if($latest = $con->query("SELECT * FROM Posts WHERE Pinned='0' LIMIT 4")) {
if($latest->num_rows > 0) {
//<-- result loop here
// end the php tag here
?>
<div></div>
<!-- you html tags here-->
<?php // reopen your php tag here again
} else {
echo '<h1 class="alert fade">No Posts</h1>';
}
$latest->close();
};

Nivo slider + php

I created a custom cms for a website and trying to make the nivo slider work with my db but im having issues with my while loop.
im only storing the name of the image in the db and the image itself its in a folder, images are working somewhat but they appear on above the other the the actual slideshow is broken.
my guess is that the title id is breaking it but not sure on how to go from here. any help is appreciated
here is my code:
<div id='slider' class='nivoSlider'>
<?php
$sql = 'SELECT * FROM slider';
$result = $db->query($sql) or die(mysqli_error());
while($row = $result->fetch_assoc()){
$slideshow = $row['slider_id'];
print"
<img src='images/slider/".$row['image'].".jpg' alt='' title='#htmlcaption'>
</div>
<div id='htmlcaption' class='nivo-html-caption '>
<span>".$row['title'] . "</span>
</div> ";
}
?>
<div id='preloader'></div>
</div>
while($row = $result->fetch_assoc()){
$slideshow = $row['slider_id'];
print"
<img src='images/slider/".$row['image'].".jpg' alt='' title'#htmlcaption'>
</div> // ---------------> Here you are closing div slider
<div id='htmlcaption' class='nivo-html-caption '>// ----> Error
<span>".$row['title'] . "</span>
</div> ";
}
In while loop you are closing </div> without opening it,This cause broken slide show.In HTML syntax id's must be unique. So <div id='htmlcaption' class='nivo-html-caption '> so change this part.
[Update]
change print to
print" <div class='some_wraper'>
<img src='images/slider/".$row['image'].".jpg' alt='' title='#htmlcaption'>
</div> // ---------------> Here now you are closing div some_wraper
<div class='nivo-html-caption htmlcaption'>// ----> added new class htmlcaption
<span>".$row['title'] . "</span>
</div> ";
Update
Fixed code
<div id='slider' class='nivoSlider'>
<?php
$sql = 'SELECT * FROM slider';
$result = $db->query($sql) or die(mysqli_error());
for($i = 0;$row = $result->fetch_assoc();$i++){
$slideshow = $row['slider_id'];
echo "<img src='images/slider/".$row['image'].".jpg' alt='' title='htmlcaption_$i'>";
$tiles[$i]=$row['title'];
}
?>
</div>
<?php //caption divs for slider
for($i=0;$i<count($tiles);$i++) {
echo "<div id='htmlcaption_$i' class='nivo-html-caption '>";
echo "<span>".$tiles[$i]."</span> </div>";
}
?>
<div id='preloader'></div>
</div>

Categories