Limiting chars for a content - php

I have content, in which I'm trying to limit using this query:
if(strlen($news_content < 35)){
$news_content = substr($news_content, 0, 30) . "";
}
But for some reason, it isn't limiting the chars.. Or It's my coding(which I'm sure is why it's not working) that's off a bit.
here's the full code:
<?php
$amount_get = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "'");
$comments = mysql_num_rows($amount_get);
$grab = mysql_query("SELECT * FROM articles WHERE id='" . mysql_real_escape_string($_GET['id']) . "' LIMIT 1");
$grab = mysql_query("SELECT id, news_title, news_content, news_author, news_day, news_month, news_year, news_date FROM articles ORDER BY id DESC limit 3");
$news_day =$row['news_day'];
$news_month =$row['news_month'];
$news_year =$row['news_year'];
$news_content =$row['news_content'];
if(strlen($news_content < 35)){
$news_content = substr($news_content, 0, 30) . "";
}
elseif (mysql_num_rows($grab)==0) {
echo "<div class='alert alert-note-x'>Sorry, it looks like their are no articles posted!</div>";
}
while($row = mysql_fetch_array($grab)){
?>
<div class="post-container">
<div class="post">
<div class="left">
<div class="date"><span class="day"><?php echo $row['news_day'] ?></span> <span class="month"><?php echo $row['news_month'] ?></span> <span class="year"><?php echo $row['news_year'] ?></span></div></div>
<div class="postcontent"><h5 class="posttitle"><?php echo stripslashes($row['news_title']); ?></h5>
<?php echo $row['news_content'] ?>
<p> (READ MORE)</p>
<p>Comments (<?php echo $comments ?>)</p>
</div>
</div>​
</div>
I'm simply trying to limit the "news_content", but I don't know where it is that I'm messing up at. Thanks!

Try changing the first line from:
if(strlen($news_content < 35)) {...}
To:
if(strlen($news_content) > 35) {
That includes switching the < to > , as presumably you want to truncate if it's longer than 35 characters rather than less ?
I think generally there are better ways to truncate though. Your approach could just cut text off in the middle of a word abruptly. Have a look at http://www.the-art-of-web.com/php/truncate/#.UNEbnmdaerI or http://www.ambrosite.com/blog/truncate-long-titles-to-the-nearest-whole-word-using-php-strrpos for other ideas.

In the html code you don't reference <?php echo $news_content?>, but <?php echo $row['news_content']?>, thus ignoring the shortened version.
Combine that with the proposed change to change the strlen($row['news_content']) < 35 to > 35 to get it working.

Following should work:
if (strlen($news_content) < 35))

Related

How can I get the information from one field in a query to use in another query?

I am still trying to finish fixing my details page and I need one more piece to fix it.
I start with this query.
NOTE:recordID actually comes in from the previous page by clicking an item.
Also, name, img, item_code, and type_id are fields in my table not outside sources.
$recordID = $_GET['recordID'];
$query_master_details = "SELECT * FROM master_list WHERE master_list.master_id = $recordID";
$master_details = mysqli_query($conn, $query_master_details) or die(mysqli_error());
$row_master_details = mysqli_fetch_assoc($master_details);
$totalrows_master_details = mysqli_num_rows($master_details);
Now, I have created this to determine how to display the details about said item:
<div class="container2">
<div class="category"><h2><?php echo $row_master_details['name']; ?></h2></div>
<?php
$crafted = "SELECT * FROM `master_list` WHERE `type_id` <= 3 AND `length` = $row_master_details.length ORDER BY RAND() LIMIT 1";
$result = mysqli_query($conn, $crafted);
$crafted = array();
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$crafted[] = $row;
}
}
if ($row_master_details['type_id'] > 3) {?>
<p><strong>Code 1</strong></p>
<p><?php echo $crafted['name']; ?></p>
<p><img src="img/<?php echo $crafted['img']; ?>" /></p>
<p><?php echo $crafted['item_code']; ?></p>
<br><br>
<p><strong>Code 2</strong></p>
<p><?php echo $row_master_details['name']; ?></p>
<p><img src="img/<?php echo $row_master_details['img']; ?>" /></p>
<p><?php echo $row_master_details['item_code']; ?></p>
<p><?php echo $row_master_details['length']; ?> Characters</p>
<?php }else { ?>
<p><?php echo $row_master_details['name']; ?></p>
<p><img src="img/<?php echo $row_master_details['img']; ?>" /></p>
<p><?php echo $row_master_details['item_code']; ?></p>
<p><?php echo $row_master_details['length']; ?> Characters</p>
<?php
mysqli_free_result($master_details);
?>
<?php } ?>
<!-- end .container2 --></div>
To explain what is happening here:
This looks at the item that was clicked on the previous page and finds the information about it.
If it has a type_id of 4 or higher, I need it to do the following:
Look at the "length" of the current item.
Select all the items from the master_list that has a type_id of 1, 2, or 3 and a matching length to the first one.
Choose 1 random match.
Output the "name, img, and item_code in the same fashion as the first one.
If the item selected originally has a type_id of less than 4, it just posts the original information. This part works. The part from the second query does not.
I have a feeling I need another $_GET[], but not exactly sure how to go about it. The recordID get was attached to the image used as a link.
Can anyone help me to query this so that I get what I am wanting?
Here is a pic of what I am trying to do to help make more sense:
This was done by manually choosing the item to match and putting them together. I want a random item to display.
Here is what the current code looks like. This is the same thing I get with MiK's answer:
I finally managed to fix this issue with a combination of tweaking and the answer from MiK.
Here is the final code I ended up with:
<div class="container2">
<div class="category"><h2><?php echo $row_master_details['name']; ?></h2></div>
<?php
$crafted = "SELECT * FROM `master_list` WHERE `type_id` <= 3 AND `length` = ". $row_master_details['length']." ORDER BY RAND() LIMIT 1";
$result = mysqli_query($conn, $crafted);
$citem = array();
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$citem[] = $row;
}
}
if ($row_master_details['type_id'] > 3) {?>
<p><strong>Code 1</strong></p>
<p><?php echo $citem[0]['name']; ?></p>
<p><img src="img/<?php echo $citem[0]['img']; ?>" /></p>
<p><?php echo $citem[0]['item_code']; ?></p>
<br><br>
<p><strong>Code 2</strong></p>
<p><?php echo $row_master_details['name']; ?></p>
<p><img src="img/<?php echo $row_master_details['img']; ?>" /></p>
<p><?php echo $row_master_details['item_code']; ?></p>
<p><?php echo $row_master_details['length']; ?> Characters</p>
<?php }else { ?>
<p><?php echo $row_master_details['name']; ?></p>
<p><img src="img/<?php echo $row_master_details['img']; ?>" /></p>
<p><?php echo $row_master_details['item_code']; ?></p>
<p><?php echo $row_master_details['length']; ?> Characters</p>
<?php
mysqli_free_result($master_details);
?>
<?php } ?>
<p><h4>(Need a different crafted item? Refresh the page!)</h4></p>
<!-- end .container2 --></div>
The answer provided by MiK fixed the query, but the results were not showing because I had an array inside the array and had to call the inner array. Also, I had to fix the array name so it wasn't the same as the query.
select
ml1.master_id, ml1.`name`,ml1.item_code,ml1.img,ml1.length,ml1.type_id,
IF(ml1.type_id > 3,ml2.master_id,null) as craft_master_id,
IF(ml1.type_id > 3,ml2.`name`,null) as craft_name,
IF(ml1.type_id > 3,ml2.item_code,null) as craft_item_code,
IF(ml1.type_id > 3,ml2.img,null) as craft_img,
IF(ml1.type_id > 3,ml2.length,null) as craft_length,
IF(ml1.type_id > 3,ml2.type_id,null) as craft_type_id
from
(select * from master_list where master_id = 4) ml1
JOIN
(select * from master_list) ml2
ON ml1.length = ml2.length
ORDER BY RAND() LIMIT 1;
This query will give exactly what you need. Not required two query to run.
no need to add if else. use only on block. in code.Where you have to add crafted it just add if(craft_master_id) then only display that block else dont show.
Instead of
$crafted = "SELECT * FROM `master_list` WHERE `type_id` <= 3
AND `length` = $row_master_details.length ORDER BY RAND() LIMIT 1";
try
$crafted = "SELECT * FROM `master_list` WHERE `type_id` <= 3
AND `length` = ".$row_master_details['length']." ORDER BY RAND() LIMIT 1";
Your query fails to find a matching thing since it will match against the string "Arraylength" instead of the actual value.

php and mysql to create tabs with bootstrap 3

enter image description here
How can I make a loop with php where I separate the comments as rounds
All comments for the round 1
<div id="$row['round']">
$row['comments']
</div>
All comments for the round 2
<div id="$row['round']">
$row['comments']
</div>
but I can have many rounds, so I don't know the exact query to use
<div id="chat" class="chat">
<ul class="nav nav-tabs">
<?php
$stmt = $DB->query("SELECT * FROM messages WHERE $id = video_id GROUP BY round ORDER BY round DESC");
while ($row = $stmt->fetch()) {
echo '<li><a data-toggle="tab" href="#menu'.$row['round'].'">'.$row['round'].'</a></li>';
}
?>
</ul>
<div class="tab-content">
<?php
$i=-1;
$stmt = $DB->query("SELECT * FROM messages WHERE $id = video_id GROUP BY round ORDER BY round DESC");
while ($row = $stmt->fetch()) {
echo '<div class="tab-pane '.( $i = $i ? 'active' : '' ).'" id="menu'.$row['round'].'">';
$test = $row['round'];
$stmt2 = $DB->query("SELECT * FROM messages INNER JOIN system_users ON messages.user_id = u_userid WHERE $id = video_id AND $test = round ORDER BY date ASC");
while ($row2 = $stmt2->fetch()) { ?>
<br />
<p><b>round:</b> <?php echo $row2["round"]; ?></p>
<p><b>Message:</b> <?php echo $row2["message"]; ?></p>
<p><b>User:</b> <?php echo $row2["u_username"]; ?></p>
<p><b>time:</b> <?php echo date_format (new DateTime($row2["date"]), 'd|m|Y H:i:s'); ?></p>
<hr />
<?php
}$i =0;
echo '</div>';
}
?>
</div>
I am completely sure this is not the best solution, but it is working,
thanks anyway..

Paging received information from table in php

How can I page info that is received from mysql table..
I want to show on every page 4 rows
I have this code :
<?php
include_once "config.php";
$sql_select_product = "SELECT * FROM product ORDER BY date DESC;";
$result_select_product = mysqli_query($connection, $sql_select_product);
if (mysqli_num_rows($result_select_product) > 0) {
while ($row_select_product = mysqli_fetch_assoc($result_select_product)) {
echo "
<div class='col-6 col-sm-3' style='margin-bottom: 20px;'>
<img width='250' height='250' src='on_login_pages/uploads/$row_select_product[img]'/>
<div class='des'>
<div class='price\">$row_select_product[price]</div>
<div class='name\">$row_select_product[name]</div>
<div class=''>$row_select_product[weight]</div>
<div class=''>$row_select_product[work_type]</div>
</div>
</div>";
}
}
$connection->close();
?>
If you call servername/path/script_name.php?page=[page_number]the script will return only 4 elements of the query.
<?php
$page_number = fiter_input(INPUT_GET,'page',FILTER_VALIDATE_INT,1,1);
$rows_per_page = 4;
$offset = ($page_number - 1) * $rows_per_page;
include_once "config.php";
$sql_select_product = sprintf("SELECT * FROM product ORDER BY date DESC LIMIT %d OFFSET %d;",
$rows_per_page,$offset);
$result_select_product = mysqli_query($connection, $sql_select_product);
if (mysqli_num_rows($result_select_product) > 0) {
while ($row_select_product = mysqli_fetch_assoc($result_select_product)) {
echo "
<div class='col-6 col-sm-3' style='margin-bottom: 20px;'>
<img width='250' height='250' src='on_login_pages/uploads/$row_select_product[img]'/>
<div class='des'>
<div class='price\">$row_select_product[price]</div>
<div class='name\">$row_select_product[name]</div>
<div class=''>$row_select_product[weight]</div>
<div class=''>$row_select_product[work_type]</div>
</div>
</div>";
}
}
Use limit in your query. Something like this:
select * from table_name order by column_name asc limit $offset,$startfrom;

How to release pagination in "GET" search?

I use this code For search in database:
<?php
if(isset($_GET['keywords'])) {
$keywords = $CONNECT->escape_string($_GET['keywords']);
if(!$keywords){
echo("<script>location.href = '/news';</script>");
//if javascript disabled
$url='/news';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';
}
$Query = mysqli_query($CONNECT, "SELECT `id`, `title`, `himg`, `readed` FROM `news` WHERE `content` LIKE '%{$keywords}%' OR `title` LIKE '%{$keywords}%'");
?>
<div class="found">founded<?php echo $Query->num_rows; ?> </div>
</div>
</div>
<div class="ncontent">
<div class="keyword">phrase: "<p><?php echo htmlspecialchars($keywords); ?></p>"</div>
<?php
if($Query->num_rows){
while ($r = $Query->fetch_object()){
?>
<div class="nline"><a href="/news/content/id/<?php echo $r->id; ?>"><div class="prewnews">
<div class="imgh1"><img src="<?php echo $r->himg; ?>"/></div>
<span><i class="fa fa-heart-o" aria-hidden="true"> <p>124</p></i><hr style="background:#cd4436; border:0; height:3px" /><i class="fa fa-eye" aria-hidden="true"> <p><?php echo $r->readed; ?></p></i> </span>
<h3><?php echo $r->title; ?></h3>
</div>
</a>
</div>
<?php
}
}else echo '<div class="notfound"><img src="/resource/img/notfound.png" alt=""></div>';
}else {echo("<script>location.href = '/news';</script>");
$url='/news';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';}
?>
Search form:
<form action="/search" method="GET">
<input class="search red" placeholder="search..." type="search" name="keywords" autocomplete="off">
</form>
So, after search i get link like this: /search?keywords=test+search+phrase
As I think i can do like this: /search?keywords=test+search+phrase&page2
or like this: /page2/search?keywords=test+search+phrase
What you advise, which way pagination?
And can you provide links that will help to realize them?
Or anyone of you can help me here?
The following pagination solution will show at most 10 search results per page, and for navigating rest of the search results, use pagination links. The solution will show at most 5 links per page, kind of like this:
// user is on 1st page
1 2 3 4 5 ...
-
// user is on 7th page
... 5 6 7 8 9 ...
-
// user is on 10th page(lets say, 10th page is the last page)
... 6 7 8 9 10
-
So, to implement this pagination functionality, you need to make few changes in your code. Keep your HTML search form as it is, and change your PHP code in the following way,
First check if there's any ...&page=123 exists or not in the URL, and based on that, process your $_GET superglobal like this way,
if(isset($_GET['page']) && !empty($_GET['page']) && is_numeric($_GET['page'])){
$current_page = $_GET['page'];
}else{
$current_page = 1;
}
Define rows per page and calculate offset based on that, like this:
$per_page = 10; // rows per page
$offset = ($current_page - 1) * $per_page; // offset
And fetch table results based on these $per_page and $offset values, like this:
$Query = mysqli_query($CONNECT, "SELECT ... WHERE `content` LIKE ... LIMIT ". $per_page . " OFFSET " . $offset);
Now to display pagination links below the search results, follow the below procedure:
Get total number of rows from the queried result set and calculate total number of page/pagination links to display, like this:
// display pagination links
$Query = mysqli_query($CONNECT, "SELECT ... FROM `news` WHERE `content` LIKE '%{$keywords}%' OR `title` LIKE '%{$keywords}%'");
if($Query->num_rows){
$total_records = $Query->num_rows;
$total_pages = ceil($total_records / $per_page);
...
Find the superset range of pages, like 1-10, or 1-20 etc. For example, if $total_pages = 20 then this superset range would be 1-20. The code for this step is this:
// superset range of pages
$superset_range = range(1, $total_pages);
Find the subset range of pages to display, like 1-5, or 3-7 etc. For example, if $total_pages = 20 then this subset range would be 1-5, or 3-7, or 6-10 etc., it can be any consecutive five pages between 1 and 20. Also, adjust this range whenever necessary. The code for this step is this:
// subset range of pages to display
$subset_range = range($current_page - 2, $current_page + 2);
// adjust the range(if required)
foreach($subset_range as $p){
if($p < 1){
array_shift($subset_range);
if(in_array($subset_range[count($subset_range) - 1] + 1, $superset_range)){
$subset_range[] = $subset_range[count($subset_range) - 1] + 1;
}
}elseif($p > $total_pages){
array_pop($subset_range);
if(in_array($subset_range[0] - 1, $superset_range)){
array_unshift($subset_range, $subset_range[0] - 1);
}
}
}
Finally, display the pagination links and dots accordingly. The code for this step is this:
// display intermediate pagination links
if($subset_range[0] > $superset_range[0]){
echo "... ";
}
foreach($subset_range as $p){
if($p == $current_page){
echo "<a href='/search?keywords=" . $keywords . "&page=" . $p . "' style='text-decoration: underline;'>$p</a>";
}else{
echo "<a href='/search?keywords=" . $keywords . "&page=" . $p . "'>$p</a>";
}
}
if($subset_range[count($subset_range) - 1] < $superset_range[count($superset_range) - 1]){
echo " ... ";
}
Here's the complete code:
<?php
if(isset($_GET['keywords'])) {
$keywords = $CONNECT->escape_string($_GET['keywords']);
if(!$keywords){
echo("<script>location.href = '/news';</script>");
//if javascript disabled
$url='/news';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';
}
if(isset($_GET['page']) && !empty($_GET['page']) && is_numeric($_GET['page'])){
$current_page = $_GET['page'];
}else{
$current_page = 1;
}
$per_page = 10;
$offset = ($current_page - 1) * $per_page;
$Query = mysqli_query($CONNECT, "SELECT `id`, `title`, `himg`, `readed` FROM `news` WHERE `content` LIKE '%{$keywords}%' OR `title` LIKE '%{$keywords}%' LIMIT ". $per_page . " OFFSET " . $offset);
?>
<div class="found">founded<?php echo $Query->num_rows; ?> </div>
</div>
</div>
<div class="ncontent">
<div class="keyword">phrase: "<p><?php echo htmlspecialchars($keywords); ?></p>"</div>
<?php
if($Query->num_rows){
while ($r = $Query->fetch_object()){
?>
<div class="nline">
<a href="/news/content/id/<?php echo $r->id; ?>">
<div class="prewnews">
<div class="imgh1">
<img src="<?php echo $r->himg; ?>"/>
</div>
<span>
<i class="fa fa-heart-o" aria-hidden="true">
<p>124</p>
</i>
<hr style="background:#cd4436; border:0; height:3px" />
<i class="fa fa-eye" aria-hidden="true">
<p><?php echo $r->readed; ?></p>
</i>
</span>
<h3><?php echo $r->title; ?></h3>
</div>
</a>
</div>
<?php
}
// display pagination links
$Query = mysqli_query($CONNECT, "SELECT `id`, `title`, `himg`, `readed` FROM `news` WHERE `content` LIKE '%{$keywords}%' OR `title` LIKE '%{$keywords}%'");
if($Query->num_rows){
$total_records = $Query->num_rows;
$total_pages = ceil($total_records / $per_page);
if($total_records > $per_page){
echo "<center>";
// Superset range of pages
$superset_range = range(1, $total_pages);
// subset range of pages to display
$subset_range = range($current_page - 2, $current_page + 2);
// adjust the range(if required)
foreach($subset_range as $p){
if($p < 1){
array_shift($subset_range);
if(in_array($subset_range[count($subset_range) - 1] + 1, $superset_range)){
$subset_range[] = $subset_range[count($subset_range) - 1] + 1;
}
}elseif($p > $total_pages){
array_pop($subset_range);
if(in_array($subset_range[0] - 1, $superset_range)){
array_unshift($subset_range, $subset_range[0] - 1);
}
}
}
// display intermediate pagination links
if($subset_range[0] > $superset_range[0]){
echo "... ";
}
foreach($subset_range as $p){
if($p == $current_page){
echo "<a href='/search?keywords=" . $keywords . "&page=" . $p . "' style='text-decoration: underline;'>$p</a>";
}else{
echo "<a href='/search?keywords=" . $keywords . "&page=" . $p . "'>$p</a>";
}
}
if($subset_range[count($subset_range) - 1] < $superset_range[count($superset_range) - 1]){
echo " ... ";
}
echo "</center> ";
}
}
}else{
echo '<div class="notfound"><img src="/resource/img/notfound.png" alt=""></div>';
}
}else {
echo("<script>location.href = '/news';</script>");
$url='/news';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';
}
?>

MySQL query doesn't show all the records correctly

The query am running against my database to get the 3 records order it by Random. The problem is that sometimes it shows all 3 records sometimes it only shows 2, 1 and other times its just blank. In the database I have around 28 records.
What I have tried
I have tried without LIMIT - Problem Same
I have echoed out $suggested_profile_id found all 3 records coming out.
This is the query that gets the records LIMIT it by 3
<?php
$sql = "SELECT * FROM members WHERE member_status='activated' ORDER BY RAND() DESC LIMIT 3";
$query = $db->SELECT($sql);
if($db->NUM_ROWS() > 0){
$rows = $db->FETCH_OBJECT();
?>
This is the code that runs and gets all 3 records in a loop.
<!-- Suggested Friends -->
<div class="col-md-0 media-body">
<?php
foreach($rows as $row){
$member_id = $row->member_id;
$sql = "SELECT * FROM profile WHERE profile_id='$member_id' LIMIT 1";
$query = $db->SELECT($sql);
$rows = $db->FETCH_OBJECT();
foreach($rows as $row){
$suggested_profile_id = $row->profile_id;
$suggested_profile_photo = $row->profile_photo;
$suggested_profile_username = $row->profile_username;
$suggested_profile_name = $row->profile_name;
if(
$suggested_profile_id != GET_SESSION_ID_VALUE(ENCRYPTION_KEY)&&
!is_in_ARRAY($make_string_to_ARRAY, $suggested_profile_id)
){
?>
<div class="row margin0">
<div class="col-md-4 pad0">
<a href="/<?php echo $suggested_profile_username; ?>" title="<?php echo $suggested_friends_profile_name; ?>" >
<?php
global $suggested_friends_profile_id;
$member_dir = dirname(dirname(dirname(__FILE__))) . "/members/" . $suggested_profile_id ."/smalll_" . $suggested_profile_photo;
if(file_exists($member_dir)){
?>
<img alt="<?php echo $suggested_profile_name; ?>" title="<?php echo $suggested_profile_name; ?>" src="/members/<?php echo $suggested_profile_id; ?>/smalll_<?php echo $suggested_profile_photo; ?>" width="50" height="50">
<?php
} else {
?>
<img alt="<?php echo $suggested_profile_name; ?>" title="<?php echo $suggested_profile_name; ?>" src="/assets/images/default.jpg" width="50" height="50">
<?php
}
?>
</a>
</div>
<div class="col-md-8 pad0">
<?php echo $suggested_profile_name; ?>
<span class="f12 gray">271 Mutual Friends</span>
Add as friend
</div>
</div>
<?php
}
}
}
?>
</div>
<!-- ** Suggested Friends -->
What am I missing? Is there any alternative way I can achieve this...thanks!
It looks to me like you're overwriting your $rows variable within the inner select.
foreach($rows as $row){ // <-- first $rows / $row
$member_id = $row->member_id;
$sql = "SELECT * FROM profile WHERE profile_id='$member_id' LIMIT 1";
$query = $db->SELECT($sql);
$rows = $db->FETCH_OBJECT(); <-- $rows overwritten
foreach($rows as $row){
Break your display from your application logic and you won't have such a hard time debugging this kind of thing. Besides, you have a lot of duplicated code and that makes things hard to manage as well as being hard to debug.
Further, you wouldn't have this problem if you ran one query: SELECT * FROM members JOIN profile ON members.member_id = profile.profile_id and not only does your code get simpler and your double-foreach loop problem disappear, but your database access will also be a lot more efficient.

Categories