Grabbing Parts of Variable To Echo Within HTML - php

How how would I just grab the first few words of a variable such as $data for example. I'm trying to create an article preview section and that variable is an article. I'm trying to display of course only a preview of it.
<?php
$sql = "SELECT author, data, postdate, Title, previewimg FROM articlepreview ORDER BY RAND() LIMIT 1";
$query = mysqli_query($db_conx,$sql);
$prev = "";
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$a = $row["author"];
$data = $row["data"];
$postdate = $row["postdate"];
$title = $row["Title"];
$previewimg = $row["previewimg"];
$prev .= '
<div class="wrapPreviewArticle">
<div style="headerPreview"><h4>'.$title.'</h4></div>
<div class="wrapPreviewRow">
<div style="imagePreview"><img src="'.$previewimg.'" height="20%" width="20%" alt="'.$title.'" /></div>
<div clas="wordPreview">'.$data.'</div>
</div>
</div>
';
}
?>
Once I've got this I would spit out the variable
<body>
<div><?php echo $prev; ?></div> <!--with only the desired portion.-->
</body>
Any help is greatly appreciated.

You could use SUBSTRING_INDEX on your query:
"SELECT author, SUBSTRING_INDEX(data, ' ', 5) data, ... FROM articlepreview ..."
This will extract only the first 5 words from the field data.

You can grab for example the first 200 characters and display only this as a preview
$pos=strpos($data, ' ', 200);
$preview=substr($data,0,$pos );
This will also make sure you split it at the space not in the middle of the word

You could show the first X characters (X here is 20):
<div class="wordPreview">'.substr($data, 0, 20).'</div>

Related

PHP - echo data from tables using their relationship

Good day :)
I have 2 tables - one containing the main headings and another which contains the subheadings and related paragraphs, which are related with a foreign key on TitleID and LinkID as shown here:
The idea is that I create a number of divs containing the main titles - from sectionamain with the related subcontent from sectiona, linked thru LinkID and TitleID.
<?php
function confirm_query($result_set) {
if (!$result_set) {
die("Database query failed.");
}
}
function get_practices() {
global $connection;
$query = "SELECT * FROM sectionamain ";
$query .= "LEFT JOIN sectiona ";
$query .= "ON sectiona.HeadingID = sectionamain.TitleID ";
$query .= "ORDER BY sectionamain.TitleID ASC";
$A_list = mysqli_query($connection, $query);
confirm_query($A_list);
return $A_list;
}
function display_practices() {
$output = "<div class=\"container inner\">\n";
$A_set = get_practices();
while ($list_A = mysqli_fetch_assoc($A_set)) {
$output .= "<div class=\"info\">\n";
$output .= "<div class=\"wrap\">\n";
$output .= "<h1 class=\"showcontent\" id=";
$output .= "". htmlentities($list_A["TitleID"]) ."";
$output .= ">";
$output .= htmlentities($list_A["MainTitle"]);
$output .= "</h1>\n";
$output .= "<div class=\"content\" id=\"content".htmlentities($list_A["TitleID"]) ."\">\n";
*** code would go here -
put items from sectiona with LinkID = 1 where TitleID = 1, etc until all data is sorted
$output .="</div>\n</div>\n</div>\n";
};
mysqli_free_result($A_set);
$output .= "</div>\n";
return $output;
}
?>
The end result would be something as shown below:
<h1>Main Title 1</h1>
<h3>Sub 1 with LinkID 1<h1>
<h3> ... </h3>
<h3>Sub n with LinkID 1</h3>
...
<h1>Main Title n</h1>
<h3>Sub 1 with LinkID n<h1>
<h3> ... </h3>
<h3>Sub n with LinkID n</h3>
Thank you in advance
xx
To solve your grouping issue, it's a matter of creating a data structure in an array. Since the database will give rows with repeating information, use this repeated information as a key in an array.
<?php
function get_practices() {
global $connection;
// It's good practice to specify which fields you want to get from the database.
// for clarity, I'm using heredoc format.
$query = >>>SECTIONAQUERY
SELECT am.TitleID, am.MainTitle, a.HeadingID, a.title, a.content
FROM sectionamain am
LEFT JOIN sectiona a
ON a.HeadingID = am.TitleID
ORDER BY sectionamain.TitleID ASC
SECTIONAQUERY;
$A_list = mysqli_query($connection, $query);
confirm_query($A_list);
return $A_list;
}
/**
* group_items
*
* takes database results and groups them by ID
*
* #param mysqli_result
* #return array
*/
function group_items($db_results) {
$data = array();
while($row = mysqli_fetch_assoc($db_results)) {
$title_id = htmlentities($row['TitleID']);
// group Main Title by title id
$data[$title_id]['title'] = htmlentities($row['MainTitle']);
// group data by title id
$data[$title_id]['data'][] = array(
'HeadingID' => htmlentities($row['HeadingID']),
'title' => htmlentities($row['title']),
'content' => htmlentities($row['content'])
);
}
return $data;
}
Then in your view, you could have something like this:
<?php
$A_list = get_practices();
$data = group_items($A_list);
// or, alternatively, $data = group_items(get_practices());
// now, go into "html mode" instead of in PHP,
// using PHP only for looping and variable substitution:
?>
<html>
<head>
...
</head>
<body>
<div>Your header stuff</div>
<div class="info">
<div class="wrap">
<?php foreach($data as $row): ?>
<h1 class="showcontent" id="<?= $row['title'] ?>"></h1>
<?php foreach($row['data'] as $sub_row): ?>
<h3><?= $sub_row['title'] ?></h3>
<div class="content"><?= $sub_row['content'] ?></div>
<!-- bonus: link to a new page? -->
<div><?= $sub_row['title'] ?></div>
<?php endforeach; ?>
<?php endforeach; ?>
</div>
</div>
</body>
</html>
Note, I personally would not stick output into a function; that's mixing logic and presentation. By using PHP's built-in templating, you don't have to worry about escaping quotes. Just use the <?= ?> syntax to drop in PHP variables. Use an include statement instead of calling the function. (or, you could always have the function include a partial view.)
Hope this addressed your question!

Display row in database with same data in particular div

Lets say I have data in my database with some rows having the same data.
id|value|message
1|001. |one
2|001. |five
3|002. |four
4|001. |hello
5|001. |sup
6|002. |sure?
Is it possible i echo all message data with 001 together in one <div class="display"></div> and those with 002 with the same <div class="display></div> There by having two <div class="display"></div> display the count of the two different values.
I have tried with PHP using
$sql =<<<EOF
SELECT value, COUNT(value) AS NumOccurrences FROM table WHERE id != '$log_id' GROUP BY value, message ORDER BY id DESC;
EOF;
$ret = $db->query($sql);
while ($row = $ret->fetchArray(SQLITE3_ASSOC))
{
$value = $row['value'];
echo "<div class='display'>$value</div>";
}
But the above code echo six <div class="display"></div>. That is each div for each value
<div class="display">001</div>
<div class="display">001</div>
<div class="display">002</div>
<div class="display">001</div>
<div class="display">001</div>
<div class="display">002</div>
But i want something like this
<div class="display">001001001001</div>
<div class="display">002002</div>
Please I am new to PHP and searched hard for an answer. Is this possible?
Without changing query you can do something like that:
$by_val = array();
while ($row = $ret->fetchArray(SQLITE3_ASSOC))
{
$value = $row['value'];
if(!isSet($by_val[$value])) $by_val[$value] = '';
$by_val[$value] .= $value;
}
foreach($by_val as $key => $str) {
echo "<div class='display'>".$str."</div>";
}

how to sort post titles under their correct category names PHP and SQL

I have searched for about 4 hours today on how to do this.
I want to pull all post titles and categories from the posts table and
essentially want to list the "Funny" category and then list all post that have the funny category under that category. Right now I am getting the following:
Funny
-post title
Funny
-post title
I want to output
Funny
-post title
-post title
<?php
$query = "SELECT post_category,post_title FROM posts ";
$select_categories_sidebars = mysqli_query($connection, $query);
?>
<h4>Blog Categories</h4>
<div class="row">
<div class="col-lg-12">
<ul class="list-group">
<?php
while($row = mysqli_fetch_assoc($select_categories_sidebars)) {
$post_title = $row['post_title'];
$post_tags = $row['post_category'];
echo "<li class='list-group-item'>$post_tags</li><ul>";
echo "<li class='list-group-item'><a href='category.php?category=$post_title'> {$post_title}</a></li></ul>";
}
?>
</ul>
That should do the trick:
First you should sort your query by category:
$query = "SELECT post_category,post_title FROM posts ORDER BY post_category";
Then do this:
<?php
while($row = mysqli_fetch_assoc($select_categories_sidebars)) {
$post_title = $row['post_title'];
$post_tags = $row['post_category'];
$used_tag = null,
// check if you already posted that category/tag. If not, show it:
if($used_tag!=$post_tags) {
echo "<li class='list-group-item'>$post_tags</li>"; // I removed a '</ul>' here
// set this title as 'used'
$used_tag=$post_tags;
}
echo "<li class='list-group-item'><a href='category.php?category=$post_title'> {$post_title}</a></li>"; // I removed a '</ul>' here too
}
?>
BUT
In an ideal world you'd have two tables to accomplish this.
One for the categories, one for the posts. Each table with id's to work with
This way you produce a lot of redundant data, it's more complicated to filter, and so on...
You might want to have a look at relational database design.
Well I basically got it working how I want I just need to format it correctly now, but it is working with some help from this question. PHP Group sql query under the same title
<?php
$query = "SELECT post_category,post_title FROM posts ORDER BY post_tags";
$select_categories_sidebars = mysqli_query($connection, $query);
?>
<h4>Blog Categories</h4>
<div class="row">
<div class="col-lg-12">
<ul class="list-group">
<?php
$title = "";
while ($row = mysqli_fetch_array($select_categories_sidebars)) {
if ($row['post_category'] != $title) {
echo '<li class="list-group-item">'.$row['post_category'].'</li><br>';
$title = $row['post_category'];
}
echo '<li class="list-group-item">'.$row['post_title'];
}
?>

Get the ID of my clicked product

I'm new to this site and wondering if somebody could help. I'm creating a website using bootstrap. I added some products in my DB and have used a while loop to display them on the page.
If you click on one of the products it takes you too a new page which should display all the information from only that product.
if ($select_db) {
$SQL = "SELECT * FROM products";
$result = mysql_query($SQL);
?>
<?php
$c = 0;
$id = -1; // The counter
$n = 3; // Each Nth iteration would be a new table row
while ($db_field = mysql_fetch_assoc($result)) {
$itemName = $db_field['name'];
$itemDescription = $db_field['description'];
$itemPrice = $db_field['price'];
$myPic = $db_field['image_name'];
if ($c % $n == 0 && $c != 0) { // If $c is divisible by $n...
echo '<div class="row" ></div>';
}
$c++;
$id++;
?>
<div class="col-md-4 col-sm-4" style="background-color:lavender;" id = 1>
<a href="productInfo.php">
<p> <?php echo $c ?> </p>
<h2> <?php echo $itemName ?> </h2>
<p><img class="img-responsive" img src= '<?php echo $myPic ?>' alt="Oops, Image cannot be found!" height="300" width="300"/></p>
<h3><?php echo $itemDescription ?></h3>
<p><?php echo $itemPrice ?></p>
<div id="selector" class="btn-group">
<button type="button" class="btn btn-primary" id="<?php $id ?>">Add</button>
</div>
<?php
$productsArray[] = array(
"id" => $id,
"itemName" => $itemName,
"itemDescription" => $itemDescription,
"price" => $itemPrice
);
//$_SESSION['sessionArray']=$productsArray;
?>
</a>
</div>
<?php
Now when I click on one of the columns it takes me to productInfo.php. I'm stuck as to how to display the product that is clicked?
I have added a variable $id which is the same as the array, example array [0] has id of 0, array [1] has id of 1. I think I'm trying to say if ID = 0 then display the results in the array at place [0]. I'm not sure if this helps?
I tried to display just the $id for now on productInfo.php but it only shows the last $id in the array
<?php
session_start();
if (isset($_SESSION["id"])) {
$newID = $_SESSION["id"];
echo $newID;
}
?>
I know this because it doesn't know which one I'm selecting. Am I making this too complicated?
Any help would be appreciated greatly!
Within your while loop I would add:
View More
This would concatenate the value of $id++ into the href under each item. Then all you need to do is create a landing page for product_page.php, define the $id on that page again and pull the data for that product from the db. You can do this without using any arrays.
Edit:
You would define $id on your product_page.php using $_GET['id'], as it is in the url, supplied by your href above ^
A good practice to get into whilst in the development stages would be to echo $id; to see if it is echoing the correct data from your while loop. If it echo's the correct $id then you can send the $id to the url through the href.
Let me know if this works or not.
Pulling data from db of your ID:
$sql = "SELECT * FROM table WHERE id='".$myID."'";
$res = mysql_query($sql);
$row = mysql_fetch_assoc($res);
$data1 = $row['whatever'];
echo $data1;

How I can do client side pagination for DIV elements generated from MYSQL query?

I have this PHP code :
$query = "SELECT * FROM news WHERE news_active = 1 AND news_type = 1 ORDER BY id DESC";
$q2 = "SELECT * FROM st_photos WHERE id = 4 LIMIT 1";
$r2 = mysql_query($q2);
$row22 = mysql_fetch_array($r2);
$news_set = mysql_query($query);
$news_set2 = mysql_query($query);
if (mysql_num_rows($news_set) != 0) {
$r = mysql_fetch_array($news_set);
echo "<div id=\"d_coll\">
<div id=\"top_text\">$row22[img]</div>
<div id=\"d_image\"><img id=\"larg_p2\" src=\"photos/$r[news_image]\" width=\"320\" height=\"250\" border=\"0\"></div>
<div style=\"width:300px\"><div id=\"n_text2\">$r[news_part_en]</div>
</div>
</div>";
}
if (mysql_num_rows($news_set2) != 0) {
while ($news = mysql_fetch_array($news_set2)) {
echo "<div id=\"n_col\">
<div id=\"n_tittle\">$news[news_tittle_en] <img src=\"images/bu3.png\" border=\"0\" align=\"middle\"></div>
<div id=\"im\"><img onMouseOver=\"MM_swapImage('larg_p2','','photos/$news[news_image]','imgs[$news[id]]','','photos/$news[news_image]',1);up2('$news[news_part_en]')\" onMouseOut=\"MM_swapImgRestore()\" name=\"imgs[$news[id]]\" id=\"imgs[$news[id]]\" src=\"photos/$news[news_image]\" width=\"50\" height=\"50\"></div>
<div dir=\"ltr\" id=\"n_div\">$news[news_part_en] <div class=\"mo\">MORE</div></div>
</div>";
}
echo "<div align=\"right\" class=\"arr\"><img src=\"images/prev.png\"> <img src=\"images/next.png\"></div>";
}
There are 2 images at the end of the code (prev & next), I want to use them to do pagination but I don't want to view any numbers, only these 2 images.
How I can do that?
I think we can do that by using JQuery library, but I don't know how to use it.
Thanks in advance.
you can use one of many plugins, for example here .
you must just remoove thе numbers. you can, i believe;)
or you can write the script by yourself.
i'll give you only an idea. let's assume you have 30 rows( from DB).put them into <div> tags, and increase the id of div. the display proparty of first <div> you must set to '', and all others to none. and then, onclick on your buttons, you just change display proparty of div elements...

Categories