Split text from the database in two columns - php

I have a bootstrap based website with 2 columns(col-lg-6 and col-lg-6).
I have the ability to add text from an admin panel (articles).
How can I make it so it splits in the second div (col-lg-6) after a specific number of characters or after I insert a character or something that will represent the breakage?
I prefer a PHP solution, but Javascript/Jquery would do too
edit *
if(isset($_GET['chapter']) && !empty($_GET['chapter'])){
$chapterid = (int)$_GET['chapter'];
$chaptertitle = mysql_query("SELECT bookname FROM books WHERE id=$chapterid");
$chaptertitle = mysql_fetch_array($chaptertitle);
$chaptertitle = $chaptertitle[0];
$chapter = mysql_query("SELECT bookContent FROM books WHERE id=$chapterid");
$chapter = mysql_fetch_array($chapter);
$chapter = $chapter[0];
$bookcontent = mysql_query("SELECT * FROM books WHERE bookid=$id");
$bookcontainer = '';
while($row = mysql_fetch_array($bookcontent)){
$bookcontainer .= '<h2>'.$row['bookname'].'</h2>' . $row['bookContent'];
}
and this is the place where the code is printed
<div class="row">
<div class="col-lg-6" id="paragraphs">
<div style="width:100%;">
<?php
//if($errors == false){
echo $chapter;
//}
//else{
//echo 'erorr madarfaker';
//}
?>
</div>
</div>
<div class="col-lg-6"></div>
</div>
If anyone is interested in this: I made 2 fields in the admin panel and the variable that was being sent to the database was "field 1 + ' | ' + field 2" and then I used explode to display the content on 2 sides, separator being " | "

Choose an arbitrary character for your split, like "|". Based on your posted code, use this as your echo statement:
echo str_replace($chapter, "|", "</div></div><div class='col-lg-6' id='paragraphs'><div style='width:100%;'>");

I am not sure if this solves your problem, but you can try :
<?php
// An array with your database data :
$arr = array('val1', 'val2', 'val3', 'val4');
$col1 = "";
$col2 = "";
$flag=false;
for($i=0; $i<sizeof($arr); $i++){
//Break condition :
$flag = ($arr[$i] == "val3" || $flag != true ) ? true : false;
if(!$flag){
$col1 .= $arr[$i];
}
else{
$col2 .= $arr[$i];
}
}
$html = "";
if($col1 != ""){
$html .= "<div class='col-lg-6'>".$col1."</div>";
}
if($col2 != ""){
$html .= "<div class='col-lg-6'>".$col2."</div>";
}
// The two div with your content (if the break rule is found) :
echo $html;
?>

If anyone is interested in this: I made 2 fields in the admin panel and the variable that was being sent to the database was "field 1 + ' | ' + field 2" and then I used explode to display the content on 2 sides, separator being " | "

Related

Php: While loop group output

I have two columns in my database, year and content i want to group the content by year (i have a lot of content and many years not only 2015 and 2016 as the example )
so i'll have this output in html
<div class="all">
<div class="2016">
2016
<div class="content_2016">
All the content of the column that is in the same ligne as 2016 in the database
</div>
</div>
<div class="2015">
2015
<div class="content_2015">
All the content of the column that is in the same ligne as 2015 in the database
</div>
</div>
</div>
<?php
$query = "SELECT * FROM publi where pub_type=0 order by pub_year DESC, pub_publi ";
$result = mysqli_query($connection, $query);
$previous =0;
while ($val = mysqli_fetch_array($result))
{
if ($previous <> $val['pub_year'])
{
$previous = $val['pub_year'];
$year = $previous;
echo $year;
echo '<br>';
$Temp = highlight("person1",$val['pub_publi'],"0000FF");
$Temp = highlight("person2",$Temp,"0000FF");
$Temp = highlight("person3",$Temp,"0000FF");
$Temp = highlight("person4",$Temp,"0000FF");
$Temp = highlight("person5",$Temp,"0000FF");
$Temp = highlight("person6",$Temp,"0000FF");
$Temp = highlight("person7",$Temp,"0000FF");
$Temp = highlight("person8",$Temp,"0000FF");
$Temp = highlight("person9",$Temp,"0000FF");
$Temp = highlight("person10",$Temp,"0000FF");
echo '<a target=blank href="http://www.test.com/query.f?term=' . $val['pub_pubmed'] . '";)><img border="0" src="img/test.gif" align=MIDDLE alt="Search in for ' . $val['pub_publi'] . '"></a>';
echo $Temp;
echo '<br>';
}
}
?>
It is outputing the years right
2016
2015
2014
etc...
but it is only showing the first ligne of each year not all the content for each year.
Run the following query:
Select Content From table order by year
echo like following (or concat):
while rs.hasNext(){
if (currentYear != lastyear){
echo div #with year As Class;
}
echo row # a single entry the way you want it dispalyed;
lastYear = currentYear;
}
what u are asking is huge chunk to write. so here are steps:
create array with this SQL statement below and fetch assoc in PHP
select distinct on year * from table
now use foreach($years as $year) on array and fetch content
select content from table where year=$year
to sandwich your code output in SQL keep concatenating like
$html = "";
$html .= "<div class=\"all\">";
foreach($years as $year){
$html .= "<div class=\"content_$year\">";
//then content fetched from second sql query
$html .= "</div>";
}
$html .= "</div>";
how to fetch data in sql | PHP.NET MANUAL
how to join/concat in php | PHP.NET MANUAL
LATER ADDITIONS, SNIPPET FROM MY OWN CODE :
$letter = $_POST['letter'];
$query_out = "SELECT link_id,singer_url FROM letter_mapping WHERE letter = '$letter'";
if($result_out = $conn_out->query($query_out)){
if($result_out->num_rows > 0){
while($row = $result_out->fetch_assoc()) {
$link_id = $row['link_id'];
$singer_url = $row['singer_url'];
/*
foreach($row as $name=>$value){
}
*/
}
}
$result_out->free();
}
if($conn_out->close()){
// Message for disconnect
//echo "Status : DISCONNECTED<br/>";
}

creating a dynamic search query in php and pdo

Ive been trying to get this to work but I dont think my sql is setup correctly.
For instance I am trying to get a search word from the URL and then insert it using prepared statements so that its safe to use in the database.
First I call the userid of the products they own from the sessions.
Then I check if they have more than 1 item, if they do I setup an array and insert into database, if they do not have more than 1 item then I just simply insert into database to retrieve data.
The reason why I am setting it into variables is because its being sent to the pagination class so it will paginate the results.
Here is the header of the html:
<?php
$searchword = $urlmaker->geturlandsearch($_GET["search"]);
$findcomma = strpos($_SESSION["SESS_USERSPRODUCTIDS"], ",");
if($findcomma == true){
$userproductid = explode(',', $_SESSION["SESS_USERSPRODUCTIDS"]);
$prep = array(':like' => "%$searchword%", ':like2' => "%$searchword%");
$q = '';
$e = '';
$i = 1;
foreach($userproductid as $productid){
$q .= 'productid=:productid' . $i . ' || ';
$prep[":productid{$i}"] = $productid;
$i++;
}
$q = rtrim($q, " || ");
} else {
$q = 'productid=:productid';
$prep = array(':productid' => $_SESSION["SESS_USERSPRODUCTIDS"], ':like' => "%$searchword%", ':like2' => "%$searchword%");
}
$maxlimit = 15;
$geturi = "/Search-Forum/" . $_GET['search'] . "/";
$string = "SELECT id,title,date,username,viewcount,replycount,replyuser,replydate FROM forum_topics WHERE " . $q . " AND title LIKE :like OR content like :like2 ORDER BY replydate DESC";
$pagstring = "SELECT id FROM forum_topics WHERE " . $q . " AND title LIKE :like OR content like :like2";
$pagurl = $geturi;
Here is the frontend code:
<?php
$topicQuery = $pagination->paginatedQuery($pdo, $string, $maxlimit, $prep);
if($topicQuery != "no query"){
while($fetchquery = $topicQuery->fetch()) {
$topicid = stripslashes($fetchquery["id"]);
$topictitle = stripslashes($fetchquery["title"]);
$topicdate = stripslashes($fetchquery["date"]);
$topicusername = stripslashes($fetchquery["username"]);
$topicviewcount = stripslashes($fetchquery["viewcount"]);
$topicreplycount = stripslashes($fetchquery["replycount"]);
$topicreplyuser = stripslashes($fetchquery["replyuser"]);
$topicreplydate = stripslashes($fetchquery["replydate"]);
?>
<li>
<div class="topiclisttitle"><p><b><?php echo ucwords($topictitle); ?></b><br><?php echo $topicusername ; ?> on <?php echo $betterTime->dateAndtime($topicdate); ?></p></div>
<div class="topiclistview"><p><b><?php echo $topicviewcount ; ?></b><br>Views</p></div>
<div class="topiclistview"><p><b><?php echo $topicreplycount ; ?></b><br>Replies</p></div>
<div class="topiclistlastposted"><?php if(!empty($topicreplyuser)){ ?><p>By: <b><?php echo $topicreplyuser ; ?></b> On<br><?php echo $betterTime->dateAndtime($topicreplydate); ?></p><?php } else { ?><p>By: <b><?php echo $topicusername ; ?></b> On<br><?php echo $betterTime->dateAndtime($topicreplydate); ?></p><?php } ?></div>
</li>
<?php } } else { ?>
<li><p class="morepadding">No Topics Regarding Your Search Words :(</p></li>
<?php } ?>
Here is the database input on the pagination class:
$freebiesquery = $pdo->prepare($string . " LIMIT " . $maxlimit);
$freebiesquery->execute($prep);
$freebiesquery_num = $freebiesquery->rowCount();
All this works on other pages so it has to be the way Im doing the header section of the code, the way im formating the sql query in the first place.
The only errors I am getting are as follows:
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number
And
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number
But this cant be as I have counted thema and they are the same?
Putting strings containing => into an array doesn't make associations. => is part of the syntax of array literals, they have to be outside the strings.
Replace:
$prep[] = "':productid{$i}' => {$productid}";
with:
$prep[":productid{$i}"] = $productid};
Replace:
$e = "':productid' =>" . $_SESSION["SESS_USERSPRODUCTIDS"];
With:
$prep = array(':productid' => $_SESSION["SESS_USERSPRODUCTIDS"]);
Replace:
$prep = array($e, ':like' => "%$searchword%", ':like2' => "%$searchword%");
with:
$prep[':like'] = "%$searchword%";
$prep[':like2'] = "%$searchword%";

How to split part of table into 2 columns over specific number of td's with PHP?

The site I'm working on wants data organized in a specific way. I need to split it into two columns if it's over 8 td's long. Here is my code right now. I've put it into an array as I had an idea about doing that and using the count to display data but I haven't figured out how to make that work.
$resultFound = false;
$prevWeek = -1;
$count = 0;
while($row = mysqli_fetch_array($result)) {
$adjustedWeek = dateToWeek($row['date']) - 35;
if($_GET['keywords'] != "") {
$id = search($row, $_GET['keywords']);
if($row['id'] == $id) {
if($validWeek) {
if($week == $adjustedWeek) {
include('test2.php');
}
}
else {
include('test2.php');
}
}
}
foreach($tableArray as $table) {
echo $table;
}
Here is my code for test2.php
$table = "";
if($prevWeek != $adjustedWeek) {
$table .= ('<th colspan=2>Week' . $adjustedWeek . '</th>');
$prevWeek = $adjustedWeek;
}
$table .= '<tr>';
$table .= ('<td colspan=12><a href="details.php?id=' . $row['id'] . '">'
. getGameTitleText($row) . '</a></td>');
$table .= '</tr>';
$resultFound = true;
$tableArray[] = $table;
$count++;
I need the code to do something like this:
If (all items of any week > 8)
write out 8 items to column one
then write the rest to column two
I've accounted for the total number of entries it's searching but not specific to a week, and I don't want to have to make lots of variables for that either to keep track.
How could I get the result like I want?
Warning!! the following code is to illustrate the idea only. Not tested on machine, but I think you can iron the possible error out.
pseudo code example:
$arr=array();
while($row = mysqli_fetch_array($result)) {
$arr[]['data']=$row['data'];
$arr[]['whatever']=$row['whatever'];
}
$columns=floor(count($arr)/8);
$output="<table>";
foreach ($arr as $i=>$a){
$output.="<tr>";
$output.="<td>{$arr[$i]['data']}</td>";
if ($columes>0){
for($j=0;$j<$columes;$j++){
$row_number=$i+($j+1)*8;
$output.="<td>{$arr[$row_number]['data']}</td>";
}
}
$output.="</tr>";
}
$output.="</table>";
This code will continue to add the third column if 2 is not enough.
You may still want to put a test for the end of array, so you don't get a bunch of warning when the $row_number is larger than count($arr)
This is how I ended up doing it. It's a bit "dirty" because it echo's out an extra /table and /tr at the beginning but it works for my purposes and is simpler than the code already posted. That was too complex for me
$table = "";
if($prevWeek != $adjustedWeek) {
$table .= '</tr></table><table class="vault_table">';
$table .= ('<tr><th>Week ' . $adjustedWeek . '</th></tr>');
$table .= '<table class="vault_table">';
$prevWeek = $adjustedWeek;
}
if($count % 2 == 0) {
$table .= '<tr>';
}
$table .= ('<td><a href="details.php?id=' . $row['id'] . '">'
. getGameTitleText($row) . '</a></td>');
$resultFound = true;
$tableArray[] = $table;
$count++;
The class is just for styling the table. Didn't have anything to do with how it's being layed out. other than each side of the table being 50% width of the container

how can I get these if statements working

i am trying to get my data from the database and wrap it with html tags. here is the working code so far:
function homethumb(){ $this->count; $i = 0;
while($row = mysqli_fetch_object($this->result))
{
$this->count++; $i++;
if($i == 1){echo '<div class="gal1">';}
echo ' <div class="gal"><img src="img/' . $row->thumb2 . '.jpg"></div>';
if($i == 2){
echo '</div> <!-- gal1 -->';
$i=0;
}
}
}
Here I am getting everything from the database (Select * from portfolio), but in the portfolio I have, websites, demos and graphics; so I wanted to get only the data where category = "web" from the above code, so I tried this:
function homethumb(){ $this->count; $i = 0;
while($row = mysqli_fetch_object($this->result))
{
if($row->category = "web"){
$this->count++; $i++;
if($i == 1){echo '<div class="gal1">';}
echo ' <div class="gal"><img src="img/' . $row->thumb2 . '.jpg"></div>';
if($i == 2){
echo '</div> <!-- gal1 -->';
$i=0;
}
}
}
}
now the nested if statements do not generate the divs I need, how can I get this working
thanks for your help
I can't see your SQL based on your question, but you could just modify your SELECT query to include WHERE category="web"
This way, you're only selecting the rows you need, instead of looping over every row in that table.
Additionally, it appears that you're using assignment = instead of comparison == for your if statement.
Do you just need to have == instead of =?
if($row->category == "web"){
But it would be best to restrict the query to the results you need at the database level, unless you need the other rows for some reason.
1)You missed an equal sign:
if($row->category = "web") => if($row->category == "web")
Or better yet
if($row->category === "web")
2)If you want to only get fields with a specific category field, you can simply change your query:
[rest of your query] WHERE category="web"
OK, it should go like this, assuming the fields are sorted as follows
ID, category, website, thumb2, demo, graphics
function homethumb(){ $this->count; $i = 0;
while($row = mysqli_fetch_object($this->result))
{
if($row[1] == "web"){
$this->count++; $i++;
if($i == 1){echo '<div class="gal1">';}
echo ' <div class="gal"><img src="img/' . $row[3] . '.jpg"></div>';
if($i == 2){
echo '</div> <!-- gal1 -->';
$i=0;
}
}
}
}
and there is no need for the nested if, you can just use it in one line as follows:
if($row[1] = "web")
{
echo '<div class="gal1">';
echo ' <div class="gal"><img src="img/' . $row[3] . '.jpg"></div>';
echo '</div> <!-- gal1 -->';
}
1) Change your query to contain a WHERE category="web" clause
2) You have an assignment operator in your if clause (=), when you need an equality operator (==)

php how to divide a list of while loop result

PHP:
function get_t_wrinkle_rel(){
global $mysqli;
$q = $mysqli->query("SELECT * FROM t_wrinkle_rel ORDER BY t_wrinkle_name ASC");
while ($r = $q->fetch_array()) :
echo '<p><input type="checkbox"' . $r['t_wrinkle_name'] . '</p>';
endwhile;
}
RESULT:
<input type="checkbox" value="Crows feet">Crows feet
<input type="checkbox" value="Frown lines" >Frown lines
<input type="checkbox" value="Lip augmentation">Lip augmentation
<input type="checkbox" value="Lip lines">Lip lines
<input type="checkbox" value="Marionette lines">Marionette lines
i want the result:
**LEFT** **RIGHT**
<input type="checkbox">Crows feet |<input type="checkbox" >Lip lines
<input type="checkbox">Frown lines | <input type="checkbox">Marionette lines
<input type="checkbox"">Lip augmentation
Could you not alternate a class on each second input that suggests clearing a float or something similar if you are not floating the inputs? Something along the lines of:
function get_t_wrinkle_rel(){
global $mysqli;
$flag = 1;
$q = $mysqli->query("SELECT * FROM t_wrinkle_rel ORDER BY t_wrinkle_name ASC");
while ($r = $q->fetch_array()) :
if ($flag = 1) {
$orientate=left;$flag=0;
} else {
$orientate=right;$flag=1;
}
echo '<p><input class="' . $orientate . '"type="checkbox"' . $r['t_wrinkle_name'] . '</p>';
endwhile;
}
while ($left = $q->fetch_array()) {
echo '<p>';
echo '<input...>' . $left['...'];
if ($right = $q->fetch_array()) {
echo '| <input...>' . $right['...'];
}
echo '</p>';
}
This way should fill the left column in order then the right column, keeping the order you want to achieve. I don't have access to your database so I can't test this, but it should do the job.
function get_t_wrinkle_rel(){
global $mysqli;
$q = $mysqli->query("SELECT * FROM t_wrinkle_rel ORDER BY t_wrinkle_name ASC");
$mid = floor($q->num_rows/2); // Get halfway point
$count = 0;
$array = array();
while($r = $q->fetch_array()){
$string = '<input type="checkbox" value="'.$r['t_wrinkle_name'].'" />'.$r['t_wrinkle_name'];
if($count <= $mid){
// Left column
$array[$count] = $string;
} else {
// Right column
$array[$count-$mid] .= '|'.$string;
}
$count++;
}
// Make single string
echo implode('', $array);
}
However I would recommend using the idea biscuitstack suggested, using CSS to position it the way you want, rather than doing it programatically. It's always better to try to keep presentation separate from the logic wherever possible.
You could use flag that increments everytime and
<input type="checkbox"' . $r['t_wrinkle_name'] .
if flag % 2 == 0 then echo '<br />'
Or something like that.

Categories