PHP - check if cell is empty - php

I'm writing a simple PHP page that is pulling information through into cards.
At the moment my script is hard coding the amount of "linktitle_1, linktitle_2, linktitle_3" etc that are able to be pulled through, at the moment it is 3, and if any of the 3 cells are empty they are still echoed out as empty, and with a comma afterwards.
What I want to do is to be able to print out any from 0-7 items of information. (The appropriate columns are present in the database)
Psuedo code would be something like this:
if (linktitle_1 = empty, linktitle_1_url = empty) {
echo '<p>linktitle_1</p>'}
else {
do nothing
};
I'm looking to do this with both the related links, and the link title sections. So I guess what I need to know is:
How do I escape the echo that these statements are to be inside of?
How do I use an if statement to check if something is empty/null?
Is there a more efficient way of doing this?
Code =
<?php
// DB details
$hostname = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($hostname, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM relevant_topics";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Removing special characters from rows.
while($row = $result->fetch_assoc()) {
$title_clean = $row["title"];
$title_clean = strtolower($title_clean);
$title_clean = preg_replace('/\s*/ ', '', $title_clean);
$class_clean = $row["class"];
$class_clean = strtolower($class_clean);
$class_clean = preg_replace('/\s*/ ', '', $class_clean);
$related_clean_1 = $row["related1"] ;
$related_clean_1 = strtolower($related_clean_1);
$related_clean_1 = preg_replace('/[.,]\s*/ ', '', $related_clean_1);
$related_clean_2 = $row["related2"] ;
$related_clean_2 = strtolower($related_clean_2);
$related_clean_2 = preg_replace('/[.,]\s*/ ', '', $related_clean_2);
$related_clean_3 = $row["related3"] ;
$related_clean_3 = strtolower($related_clean_3);
$related_clean_3 = preg_replace('/[.,]\s*/ ', '', $related_clean_3);
$related_clean_4 = $row["related4"] ;
$related_clean_4 = strtolower($related_clean_4);
$related_clean_4 = preg_replace('/[.,]\s*/ ', '', $related_clean_4);
echo'
<div class="mix item '.$class_clean.'">
<h3>'.$row["title"].'</h3>
<p>'.$row["description"].'</p>
</br>
<p>Related Items:</p>
<p>
'.$row["related1"].'
'.$row["related2"].'
'.$row["related3"].'
'.$row["related4"].'
'.$row["related1"].',
'.$row["related2"].',
'.$row["related3"].', </p>
</br>
<div class="item-bottom '.$row["class"].'_counter">
See more
</div>
</div>
<div id="myModal'.$title_clean.'" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 class="modal-title modal-top-health">'.$row["title"].'</h3>
<br>
<p>'.$row["details"].'</p>
<br>
'.$row["linktitle_1"].',
<p>'.$row["linktitle_1_desc"].'</p>
'.$row["linktitle_2"].',
<p>'.$row["linktitle_2_desc"].'</p>
'.$row["linktitle_3"].',
<p>'.$row["linktitle_3_desc"].'</p>
</div>
</div>
</div>
</div>
';
}
} else {
echo "0 results";
}
$conn->close();
?>

Optimize with a loop, store the output in a variable:
// build list of titles
$titles = '';
for($i=1; $i<=7; ++$i) {
// check for data
if($row['linktitle_'.$i.'_url'] != null && $row['linktitle_'.$i] != null) {
// add to output
$titles .= '
'.$row['linktitle_'.$i].',
<p>'.$row['linktitle_'.$i.'_desc'].'</p>';
}
}
echo '
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 class="modal-title modal-top-health">'.$row["title"].'</h3>
<br>
<p>'.$row["details"].'</p>
<br>'.$titles.'
</div>';
You can then change that 7 to any number.
You can use htmlspecialchars() to escape the values if they might break the HTML.
$titles .= '
<a href="'.htmlspecialchars($row['linktitle_'.$i.'_url']).'">'.
htmlspecialchars($row['linktitle_'.$i]).', </a>
<p>'.htmlspecialchars($row['linktitle_'.$i.'_desc']).'</p>';
The same logic can be applied to the related links.
It could be optimized further at the database level by having a dedicated table for the titles:
table: relevant_topics_titles
topic_id | title_id | name | url | desc
Where topic_id is a foreign key to join with your table relevant_topics while title_id is a number between 1 and 7 (or less or more).
You could then fetch all the titles associated with your topic id and loop through them to build the list of titles.

Related

mysqli_num_rows generates unlimited amount of data

so, I'll try to explain it as good as I can with my knowledge in english.
I am trying to count data from my database, basically - how many fields I have with the same ID. here's image from database.
image from database
for example, in posts i have review system and it works, i have this PHP code to count how many same fields i have with review and id.
Here's the code:
<?php
$revposid = $res['content_id'];
$pos="SELECT review FROM comments WHERE review='positive' and postid=$revposid";
$neg="SELECT review FROM comments WHERE review='negative' and postid=$revposid";
$neu="SELECT review FROM comments WHERE review='neutral' and postid=$revposid";
if ($result=mysqli_query($_db,$pos)){$rowcountpos=mysqli_num_rows($result);}
if ($result=mysqli_query($_db,$neg)){$rowcountneg=mysqli_num_rows($result);}
if ($result=mysqli_query($_db,$neu)){$rowcountneu=mysqli_num_rows($result);}
?>
<div class="reviews" id="reviews">
<span class="good"><b class="fa fa-thumbs-up"></b><?php echo $rowcountpos ?></span>
<span class="neutral"><b class="icon-thumbs-up"></b><?php echo $rowcountneu ?></span>
<span class="bad"><b class="fa fa-thumbs-down"></b><?php echo $rowcountneg ?></span>
</div>
and when I try to use the same code
$revposid = $cont['content_id'];
$pos="SELECT content_id FROM user_content_like WHERE content_id=$revposid";
if ($result=mysqli_query($_db,$pos)){$rowcountpos=mysqli_num_rows($result);}
in my other script I have like system, it should show all my likes and under likes total likes of the post but when I use it it shows unlimited amount of data, i have no idea why. Here's the full code, I would appreciate some help or explanation.
<?php $ususername = $_GET['user_username'];$sql = "SELECT * FROM user_details WHERE user_username='$ususername'";$usresult = mysqli_query($_db,$sql);?>
<?php if( ! mysqli_num_rows($usresult) ) {
echo " Ooops? <br> <br>User <b>".$_GET["user_username"]."</b> doesn't exist.";
} else {
while($usrow = mysqli_fetch_array($usresult,MYSQLI_BOTH)) {?>
<?php
$current_user = $usrow['user_id'];
if ($_db->connect_error) {
die("Connection failed: " . $_db->connect_error);
}
$sql = "SELECT * FROM user_content_like WHERE user_id=$current_user ORDER BY date_added DESC;";
$result = $_db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$content_id = $row['content_id'];
$sql1 = "SELECT * FROM content WHERE content_id=$content_id";
$result1 = $_db->query($sql1);
if ($_SESSION['user_id'] == $usrow['user_id']) {$output = '
<button type="button" class="unlike_button" onclick="unlike(this);" name="like_button" data-content_id="'.$row["content_id"].'" ><i class="fa fa-minus"></i></button>
';} else {
$output = '';
}
while($cont = $result1->fetch_assoc()) {
$revposid = $cont['content_id'];
$pos="SELECT content_id FROM user_content_like WHERE content_id=$revposid";
if ($result=mysqli_query($_db,$pos)){$rowcountpos=mysqli_num_rows($result);}
echo '
<div class="community-feed-thread">
<div class="community-icon-thread"></div>
<div class="community-comments-thread">'.$output.'</div>
<a href="'.$cont["content_id"].'" class="community-title-thread"><h3>'.$cont["title"].'</h3>
<span class="likes-desc"> Total likes: '.$rowcountpos.'</span>
</a>
</div>
';
}
}}
else {
echo " hmmmmmmmmmmmm.<Br><br>". $usrow["user_username"]." doesn't like anything. ";
}
$_db->close();
?>
<?php }}?>
this is how i want it to look
This is how it looks
Your re-using the same variable for different result sets in the code...
$result = $_db->query($sql);
and
if ($result=mysqli_query($_db,$pos))
You will need to ensure you only use the variable name once or it may have side effects in other loops.

How to get multiple records to display in webpage on mysql query?

I know this is a stupid question, and I've tried looking at the other answers, but they are not working for me. I have taken over maintaining a site with a lot of pre-existent code, and need to add in a new query.
I have managed to get the query to work and to display in the webpage, but only the first record displays. I know somehow I'm missing the looping function, but I can't figure out how to add it to the function so all records display.
I've been fighting with this for hours, and would really appreciate some pointers!
Here's the code in the main listing.php file - the first query is pre-existing, the new query is to the getFeedback procedure starts with "$sql2 = "CALL sp_GetFeedback(".$listing['unique_listing_id'].")";".
if(($PMDR->get('Authentication')->checkPermission('admin_view_real_prices')) || ($PMDR->get('Session')->get('user_id'))) {
$admin_user_can_view_prices = true;
$template_content->set('admin_user_can_view_prices',$admin_user_can_view_prices);
$sql = "CALL sp_Entertainers_Contact_Info(".$listing['unique_listing_id'].")";
//all variables come from db.php
$mysqli = new mysqli($dbserver, $dbuser, $dbpass, $dbnameaf);
$rs = $mysqli->query($sql);
while($row = $rs->fetch_assoc())
{
$template_content->set('primaryEmail',$row['PrimaryEmail']);
$template_content->set('secondaryEmail',$row['SecondaryEmail']);
$template_content->set('cellPhone',$row['CellPhone']);
$template_content->set('homePhone',$row['HomePhone']);
$template_content->set('alternatePhone',$row['AlternatePhone (Please Specify)']);
$template_content->set('streetAddress',$row['StreetAddress']);
$template_content->set('entertainerCity',$row['City']);
$template_content->set('entertainerState',$row['State']);
$template_content->set('entertainerZip',$row['Zip']);
$template_content->set('entertainerNotes',$row['Note']);
}
$data = "";
$griddata = "";
$grid = "";
$entertainerid = $_POST['unique_listing_id'];
$mysqli = new mysqli($dbserver, $dbuser, $dbpass, $dbnameaf);
$sql2 = "CALL sp_GetFeedback(".$listing['unique_listing_id'].")";
$rs = $mysqli->query($sql2);
$numrows = mysqli_num_rows($rs)." Rows";
while($row = $rs->fetch_assoc()) {
$allRows[] = $row;
$style = ($altRowCount % 2 == 0 ? ' class="row" ' : ' class="row tdg" ');
$template_content->set('eventID',$row['EventID']);
$template_content->set('dateOfEvent',$row['DateOfEvent']);
$template_content->set('clientFollow',$row['ClientFollowUp']);
$template_content->set('performerFollow',$row['PerformerFollowUp']);
$griddata .= "
<div $style>
<div class='col-xs-2 col-sm-2 col-md-2' onclick=\"popupEvent('".$row['EventID']."')\">".$eventID."</div>
<div class='col-xs-2 col-sm-2 col-md-2'>".$dateOfEvent."</div>
<div class='col-xs-4 col-sm-4 col-md-4'>".$clientFollow."</div>
<div class='col-xs-4 col-sm-4 col-md-4'>".$performerFollow."</div>
</div>
";
$altRowCount = $altRowCount + 1;
}
$mysqli->close();
$grid = "
<div style='max-height: 110px; overflow: scroll;'>
<table class='fancygrid'>
<tbody>
".$griddata."
</tbody>
</table>
</div>
<!-- <div style='width: 100%; font-weight: bold; color: red;'>".$numrows."</div> -->
";
echo $gridHeader.$grid;
} //getEntertainerFeedback
} // is an office user logged in? -- end
Here's the code that is in the included listing.tpl file that contains the HTML for the webpage:
<div class="row">
<div class='col-xs-2 col-sm-2 col-md-2' onclick="popupEvent(".$row['eventID'].")"><?php echo $eventID ?></div>
<div class='col-xs-2 col-sm-2 col-md-2'><?php echo $dateOfEvent ?></div>
<div class='col-xs-4 col-sm-4 col-md-4'><?php echo $clientFollow ?></div>
<div class='col-xs-4 col-sm-4 col-md-4'><?php echo $performerFollow ?></div>
</div>
I tried adding
<?php
foreach ($allRows as $row) {
?>
<?php } ?>
around the html code above but that just causes no records to display at all, not even one.
Since you have to be logged in to view this data, I can't share the link, but here's what the blue logged in area looks like with the one record showing at bottom of blue box:
ETA: FYI - I also tried just echoing .grid in my html code - but that gives me not results at all, not sure why.
Any help to point me in the right direction or tell me what I'm missing is greatly appreciated!!
Thanks!
First of all, you have opened database connection twice
$data = "";
$griddata = "";
$grid = "";
$entertainerid = $_POST['unique_listing_id'];
# remove this line, just to be sure it doesn't cause any problems
$mysqli = new mysqli($dbserver, $dbuser, $dbpass, $dbnameaf);
$sql2 = "CALL sp_GetFeedback(".$listing['unique_listing_id'].")";
Secondly, debug your query result by printing something in while loop, just to be sure that query returns multiple rows as result
And last thing I should try is to declare $allRows as an Array before your while loop, just for safety
$allRows = array();
while($row = $rs->fetch_assoc()) {
$allRows[] = $row;
Then try this approach
<?php
foreach ($allRows as $row) {
?>
<!-- HTML -->
<?php } ?>
Edit:
This looks like some kind of View object, so you have predefined HTML code in it and you just fill it with your values from database, so I think your while statement is overriding values in your view with each loop and that's the reason why you probably get one record. Your View is probably designed to hold one row/data
$template_content->set('eventID',$row['EventID']);
$template_content->set('dateOfEvent',$row['DateOfEvent']);
$template_content->set('clientFollow',$row['ClientFollowUp']);
$template_content->set('performerFollow',$row['PerformerFollowUp']);

How to display data twice from a mysql table in php

Im making a page that will display top ten voters in a table and show the number one voter aswell. I got the top ten table to work but I can't figure out how to get the second part to work. What would I do to get it to work where it would show the top voter in a img tag like this example
img src="https://minotar.net/avatar/TOPVOTERHERE"
First part
<div class="col-md-6">
<table class="table table-striped">
<tr>
<td><strong>Username</strong></td>
<td><strong>Votes</strong></td>
</tr>
<?php
$username2 = "exampleuser";
$password2 = "pass";
$hostname = "127.0.0.1";
$dbhandle = mysql_connect($hostname, $username2 , $password2)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("mc711",$dbhandle)
or die("Could not select database");
$result = mysql_query("SELECT * FROM GALTotals ORDER BY votes DESC");
$count = 0;
while ($row = mysql_fetch_assoc($result)) {
$count++;
if($count>10){
}else{
echo "<tr>";
echo "<td>".$row['IGN']."</td>";
echo "<td>".$row['votes']."</td>";
echo "</tr>";
}
}
?>
</table>
</div>
Second Part - This is the part I dont know how to do
<div class="col-md-6">
<center>
<img src="https://minotar.net/avatar/TOPVOTERHERE">
</center>
</div>
The simplest way to do it would be to create a variable to store the top voter data before you start your while loop. Then, in the while loop, you can set this variable if you're in the first iteration.
First part:
$result = mysql_query("SELECT * FROM GALTotals ORDER BY votes DESC");
$count = 0;
$topVoterIGN = NULL;
while ($row = mysql_fetch_assoc($result)) {
$count++;
if($count>10){
}else{
echo "<tr>";
echo "<td>".$row['IGN']."</td>";
echo "<td>".$row['votes']."</td>";
echo "</tr>";
if(is_null($topVoterIGN)) {
$topVoterIGN = $row['IGN'];
}
}
}
Second Part:
<div class="col-md-6">
<center>
<img src="https://minotar.net/avatar/<?php echo $topVoterIGN; ?>">
</center>
</div>
Alternatively, you can store the top 10 voters in an array and then retrieve the first item later.

WHERE not working when it should be?

before I start I have looked over the answers related but I cannot figure this out
Hello, I am trying to fetch the values with just the data from formtype = 'Question1'
the value is in the database under column formtype as Question1, it is a radio option value which is one of 3 values that I use to redirect information over to one page, so I have to do this on each page to get that specific information. My question is, why is it not selecting the values that contain Question1? it doesn't grab anything at all, but if I get rid of WHERE it grabs all the information just fine(which i only wanna grab the one containing Question1). Why is this? it isnt showing any errors with SELECT so I don't know what I did wrong.
I am connected to the database
<?php $db_name = 'submissions';
$db_user = 'root';
$db_pass = '';
$db_host = 'localhost';
mysql_connect("localhost", $db_user, $db_pass) or die(mysql_error());
mysql_select_db("submissions") or die(mysql_error());
$query1 = mysql_query("SELECT actual_quote,poster,formtype FROM data WHERE formtype = 'Question1'");
$info = mysql_fetch_array($query1);
while($info = mysql_fetch_array($query1)){
echo '
<div class="wrapper">
<div class="submissions">
<div class="logo-logo"><h2>Questions.</h2>
<div class="checkboxes">'.$info['formtype'].'
</div>
</div>
<div class="top-submit">
&#8220'. $info["actual_quote"] . '”
</div>
<div class="poster">- '. $info["poster"].'
<div class = "like">
Like
<p id = "like" style = "color:green;">0</p>
</div>
<div class = "dislike">
Dislike
<p id = "dis" style = "color:red;">0</p>
</div>
</div>
<!-- use select to get the items to stay on the page-->
</div>
</div>
</div>
';
}
?>
Any suggestions?
Fix these lines:
$link = mysql_connect("localhost", $db_user, $db_pass) or die(mysql_error());
mysql_select_db("submissions",$link) or die(mysql_error());
$query1 = mysql_query("SELECT actual_quote,poster,formtype FROM data WHERE formtype = 'Question1'",$link);
//delete this-> $info = mysql_fetch_array($query1); ?
while($info = mysql_fetch_array($query1)){

PHP shows top 4 rows on different places

I have the following html code:
<div class="content-block1">
<div class="image-block1"></div>
<div class="bear1"></div>
<div class="where-block1"></div>
<div class="intro-block1"></div>
<div class="map-block1"></div>
<div class="extra-block1"></div>
<div class="coordinates-block1"></div>
<div class="button-block1">More...</div>
</div>
<div class="content-block2">
<div class="image-block2"></div>
<div class="bear2">/div>
<div class="where-block2"></div>
<div class="intro-block2"></div>
<div class="map-block2"></div>
<div class="extra-block2"></div>
<div class="coordinates-block2"></div>
<div class="button-block2">More...</div>
</div>
..and the following PHP code:
$host = "localhost";
$user = "username";
$pass = "password";
$database = "db";
mysql_connect($host,$user,$pass,$database) or die(mysql_error());
mysql_query("SET NAMES 'utf8'");
$query = mysql_query("select image,where,intro,map,extra,coordinates from content limit 2");
mysql_close();
Now, I've tried so hard to do following: I need to select top 2 rows in table content which include columns image,where,intro,map,extra and coordinates (bear excluded). Okay, I've selected them with query, BUT I have next problem -> I need to put content from first row in first DIV element called content-block1, so, columns image,where,intro,map,extra and coordinates need to fit in their divs in content-block1.
Also, I need to put data from second row (image,where,intro,map,extra and coordinates) into DIV element called content-block2 into DIVs where they belong. Can you help me please?
I think this could be what you are looking for...
$host = "localhost";
$user = "username";
$pass = "password";
$database = "db";
mysql_connect($host,$user,$pass,$database) or die(mysql_error());
mysql_query("SET NAMES 'utf8'");
$query = mysql_query("select image,where,intro,map,extra,coordinates from content limit 2");
$i = 0;
while($row = mysql_fetch_array($query , MYSQL_ASSOC))
{
$i++;
echo '
<div class="content-block{$i}">
<div class="image-block{$i}">{$row['yourvaluehere']}</div>
<div class="bear{$i}">{$row['yourvaluehere']}</div>
<div class="where-block{$i}">{$row['yourvaluehere']}</div>
<div class="intro-block{$i}">{$row['yourvaluehere']}</div>
<div class="map-block{$i}">{$row['yourvaluehere']}</div>
<div class="extra-block{$i}"></div>
<div class="coordinates-block{$i}">{$row['yourvaluehere']}</div>
<div class="button-block{$i}">More...</div>
</div>
';
}
Try changing your Query to this
$query = mysql_query("select * from content limit 0, 2");
Source = https://dev.mysql.com/doc/refman/5.0/en/select.html
Then do the following to get your query values
while($row = mysqli_fetch_array($query))
{
$image = $row['image'];
$where = $row['where'];
$map = $row['intro'];
$extra = $row['extra'];
$coordinates = $row['coordinates'];
}
This would be your query if you were selecting the top two only
$query = mysql_query("select TOP 2 * from content");

Categories