Personalized content - php

I would like to, clicking on a link, showing a content personalized.
<div class="tab_event">
<?php
do{
echo'
<table class="preview_event">
<td class="date_event">
'.$row["Date"].'
</td>
<td class="title_event">
<p>'.$row["Title"].'<br></p>
Read more !
</td>
</table>
';
} while ($row = $query->fetch(PDO::FETCH_ASSOC));
?>
My program consist at doing a "preview" of some articles from the database.
And when you click on "read more" i would like that, automatically, you get a page where the all article is written.
But I don't have any ideas about how to do it, bcs i don't want to create a page manually for each article.
Does anyone have any idea about how to do ?
Thanks

To achieve what you want, you need to generate a href to another/same PHP powered page along with a query parameter with some value which uniquely identifies the article in your database.
Assuming your database table structure is similar to
| Id | Date | Title |
|----|------------|------------------------|
| 1 | 0000-00-00 | Some catchy post title |
| 2 | 0000-00-00 | Yet another post title |
| 3 | 0000-00-00 | Some other title? |
I will use $row["Id"] using the above table structure
<div class="tab_event">
<?php
do {
echo '
<table class="preview_event">
<td class="date_event">
'.$row["Date"].'
</td>
<td class="title_event">
<p>'.$row["Title"].'<br></p>
Read more !
</td>
</table>';
} while ($row = $query->fetch(PDO::FETCH_ASSOC));
?>
Now access the aid parameter on your linked script (showArticle.php) to fetch the article from databse
<?php
if (!empty($_GET['aid']) {
// escape and verify value of `$_GET['aid']`
// fetch and return article from database using the `$_GET['aid']` parameter
} else {
// tell the user no `Id` was provided
}
?>

It's quite an easy task, first of all, you need to modify your table page, and edit the read more link this :
Read more !
Where article_idis whatever record's identification you wanna use to store that information when clicking the link, for example the article's id field in the database, now you create a read.php page, which will change its content based on the article's id in the link, so you only need to create that and not one page for each article.
Then in read.php you retrieve that information from the URL so that you can query the database with the correct article's ID and show its content:
...
...
$article_id = $_GET['article'];
// then you query the database using that variable (using whatever method you prefer, this in just an example)
$query = $db->prepare("SELECT title, date, content FROM articles WHERE articles.id = " . $article_id);
$query->fetch(PDO::FETCH_ASSOC);
This way you can retrieve the single's article information and show them on the read.php page , creating only one page which changes its content based on which link you click.
Also, worth mention that you should remove that do...while, for and foreach loops are way more elegant.
One example would be (assuming that the variable containing the results is called $rows) :
<table> <!-- table tag outside of the loop, otherwise for each article a table is created, which is wrong -->
<tbody>
<?php
foreach($rows as $article) {
echo "<tr>"; // since we need one row for each article, we include the tr tag in the loop
echo "<td>".$article['title']."</td>";
echo "<td>".$article['date']."</td>";
echo "<td>".$article['author']."</td>";
...
...
echo "</tr>"; // and we close the row
}
?>
</tbody>
</table>

Related

How to make php dynamic queries

im trying to change query depending on what user has selected. In my case there are displayed two photos with labels pulled from data base. And depending which image is clicked i want that label to be used in query who will display items associated in database with that label. I tried using global variables, but it i didn't work for me. I cant figure out how to insert data into query after user clicked something
There is code fragment where i pull photos with labels from database, and depending on which i select i want "$modeliai_results['Modelis']" (vehicle model label) to be sent and used in another query below
<div class="eile">
<?php
echo '
<a href="standartiniskatalogas.php?page=kategorijos"/>
<img src="data:image/jpeg;base64,'.base64_encode( $modeliai_results['Nuotrauka'] ).'"/>
<div class="description">'.$modeliai_results['Marke'].' '.$modeliai_results['Modelis'].'
</div></a>';
?>
Page from second image which should execute query depending on selection from previous page:
<?php
$kategorijos_sql="SELECT * FROM kategorijos (HERE SHOULD BE ADDED: "WHERE Modelis='MODEL NAME WHICH WAS SELECTED WHEN PRESSED ON IMAGE'";
$kategorijos_query=mysqli_query($dbconnect, $kategorijos_sql);
$kategorijos_results=mysqli_fetch_assoc($kategorijos_query);
do{
echo '
<div class="eile2">
<a href="isore/isore.html">
<img src="data:image/jpeg;base64,'.base64_encode( $kategorijos_results['Nuotrauka'] ).'"/>
<div class="description">'.$kategorijos_results['Kategorija'].'</div>
</a></div>'; /* uzdaro echo*/
}
while ($kategorijos_results=mysqli_fetch_assoc($kategorijos_query))
?>
ps. Im not using any extra tools or libraries.
Selecting object
Display data associated with object
My mistake was that i concentrated on "onclick" event which would set global variable and that global variable would be used in query. Problem was that, php with java script not so big friends and would create not linkable URLs to same content. The solution was to use simple thing "$_GET". Assign $_GET to some php variable, and then use it in "href". That way when you click on any kind of object with "a href="'.$variable.'"> bla bla /a>" you get redirected to page with added tail to URL from which you can access to use in other queries
<?php
$model= $_GET['model']; //variable from URL tail
$category= $_GET['category'];
$category_sql="SELECT * FROM service WHERE Model='$model' AND Category='$category'"; //my SQL where i use variables selected from URL
$category_query=mysqli_query($dbconnect, $category_sql);
$category_results=mysqli_fetch_assoc($category_query);
do{
echo ' //print html together with php code
<tr class="data">
<td>
<a href="catalogue.php? page=service&model='.$model.'&category='.$category.'&service='.$category_results['Name'].'"> //here i make href which when clicked will pass values named with $ sign
<img src="data:image/jpeg;base64,'.base64_encode( $category_results['Image'] ).'"/>//Here i take image from data base
<br><button>'.$category_results['Name'].'</button></a>
</td>
<td> <p>'.$category_results['Description'].'</p> //I take values from data base
</td>
<td>'.$category_results['Price'].' €</td>
</tr>';
}
while ($category_results=mysqli_fetch_assoc($category_query)) //loop which cycles through all data base items
?>

how can i find the tr with specific id and these ids comming from database dynamically...?

I have data in the form of a table. The data is coming from a database. Each row is assigned a dynamic ID coming from the database.
How can I select that row with specific ID and then be able to style that whole row, using jquery?
This is the data coming from the database:
You can generate table rows dynamically using php
for( $database_rows as $row ){
echo "<tr id=\"{$row->id}\">" . _content_of_row_ ."</tr>";
}
Yes you can use jQuery to do that.
for example if your generated row be like below
<tr id="31"> .... </tr>
you can select the row like this
$("tr#31")
then you can add css class to it:
$("tr#31").addClass("selected")
remove css class from it:
$("tr#31").removeClass("selected")
add attributes to it:
$("tr#31").attr("attribute", "value")
or anything else.
Try this into foreach or similar loop:
<tr id="<?php echo $database_row_id; ?>">...</tr>
Where $database_row_id is the id you get from database

Replace Content for PHP Variable (HTML tags Stored)

I want to replace <a> tag contents from PHP Variable ($html_content)...
The Variable $html_content Value looks like below:
$html_content= "<table>
<thead>
<tr><th>Customer</th><th>Age</th><th>A</th></tr>
</thead>
<tbody>
<tr><td>Test 1</td><td>25</td><td><a href='www.google.com'>Link</a></td></tr>
<tr><td>Test 2</td><td>30</td><td><a href='www.yahoo.com'>Link</a></td></tr>
<tr><td>Test 3</td><td>31</td><td><a href='www.rediff.com'>Link</a></td></tr>
...
...
...
</tbody>
</table>
I want to replace content in string every last <td> content of every <tr> which contains <a> tag.
The sample rows result:
<tr><td>Test 1</td><td>25</td><td>Action will be taken soon.</td></tr>
<tr><td>Test 2</td><td>30</td><td>Action taken yesterday</td></tr>
...
...
I need result to replace every row with different content values. The content is taken from table. The particular customer action only i want to replace.
CUSTOMER TABLE:
------------------------------------------------------
id customer age action
------------------------------------------------------
1 Test 1 25 Action will be taken soon
2 Test 2 30 Action taken yesterday
3 Test 3 31 Action will take tomw
4 Kumar 28 Suspended
...
...
...
------------------------------------------------------
using this table i have shown filtered result in one page without action description instead of <a> tag. (This result is part of that page named reports.php).
I want to export these records only with action field description to PDF(I'm using HTML to PDF class).
In that page i had sent to these HTML values to that page and storing in PHP Variable($html_content) in export_pdf.php page...
The table records is not fixed size... It's based on generating result from sorting.
Please anyone help me...
Thanks in advance...
Try following codes:
$html_content= preg_replace("/<a[^>]+\>(.*?)<\/a>/i", "Action will be taken soon.", $html_content);
With foreach in query
foreach($row = mysql_fetch_assoc($result))
{
$html_content = preg_replace("/<a[^>]+\>(\w+)<\/a>/i", $row['action'], $html_content);
}
Output
<table>
<thead>
<tr><th>Customer</th><th>Age</th><th>A</th></tr>
</thead>
<tbody>
<tr><td>Test 1</td><td>25</td><td>Action will be taken soon.</td></tr>
<tr><td>Test 2</td><td>30</td><td>Action will be taken soon.</td></tr>
<tr><td>Test 3</td><td>31</td><td>Action will be taken soon.</td></tr>
</tbody>
</table>
You can do it via regex:
$rgReplace = ['foo', 'bar', 'baz'];
$i = 0;
$html_content=preg_replace_callback('/\<td[^\<\>]*\>\<a[^\<\>]*\>[^\<\>]*\<\/a\>\<\/td\>/',
function($rgMatches) use ($rgReplace, &$i)
{
return $rgReplace[$i++];
}, $html_content);
(your $rgReplace is an array with desired replaces).
or, alternatively, via DOMDocument API.

How to create conditional button in HTML based on MySQL data?

I am trying to create a button that will either say "Follow" or "Unfollow", depending on whether or not the current user follows another user.
If John followed Tim, but not Sarah, the web view would look as follows, according to John's view:
_________________________________
| | |
| Tim | (unfollow) |
|________________|______________|
| | |
| Sarah | (follow) |
|________________|______________|
Where (" ") denotes a button.
I have a database that indicates who follows whom, but how would I display the correct button based upon validation with said database?
Assuming you have three fields "name_id","name" and "followed" where "name_id" is the id of the person, "name" is a string signifying the name of the person, and "followed" is a boolean:
<script type="text/javascript">
function toggleFollowing(name_id) {
window.location = 'toggleFollowing.php?name_id='+name_id;
}
</script>
...
<?php
...
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td>'.$row['name'].'</td><td><a href=""><button type="button" onclick="toggleFollowing('.$row['name_id'].')">'.($row['followed']==1 ? 'Unfollow':'Follow').'</button></td>';
echo '</tr>';
}
...
?>
You would have toggleFollowing.php receive the variable $_GET['name_id'] to toggle on the database and come back to this page. I'm assuming you have the current user's ID stored as a session variable or by other means since you would need that as a primary reference to update the record. If you're passing that from page to page by some other means, then you would want to pass that variable as well.
Apparently, this is more truncated code, but a better method would be to use AJAX to perform the toggling on the DB, and DOM manipulation (JQuery?) for a "real-time" update.
Hard to answer without examples of your code, but something like this?
<?php
if(follow){
echo '<input type="button" value="Follow" />';
} else {
echo '<input type="button" value="Unfollow" />';
}
?>

PHP, XML, Problems with repeating attributes when echoing

I got an XML file being echoed by PHP and all the code works fine but my problem is that inside a tag (exam and the attribute is chapter which is what's being echoed) there's more than one tag (ex, that's what is being echoed as exam #) and I am echoing the data to a table and I want it to display it like this:
| Chapter 1 | Chapter 2 |
|--Exam 1---|--Exam 1---|
|--Exam 2---|--Exam 2---|
| Chapter 3 | Chapter 4 |
|--Exam 1---|--Exam 1---|
But What I am getting is something like this: (I know why though)
| Chapter 1 |
|--Exam 1---|
| Chapter 1 |
|--Exam 2---|
| Chapter 2 |
|--Exam 1---|
It keeps on repeating the tag's attribute and I know why, because I am echoing the tag's attribute that I have as a variable in a table data. So the question is not why it is happening but how can I change it to display it the way I want it.
I guess maybe there's a way to delete the attribute if there's more than one (I know you can delete it but I don't know how to show it once and delete the others)
The code that I have is something like this:
In XML
<maintag>
<exam chapter="Chapter 1">
<ex id="1">Exam 1</ex>
<ex id="2">Exam 2</ex>
<ex id="3">Exam 3</ex>
</exam>
<exam chapter="Chapter 2">
<ex id="4">Exam 1</ex>
<ex id="5">Exam 2</ex>
</exam>
<exam chapter="Chapter 3">
<ex id="6">Exam 1</ex>
</exam>
<exam chapter="Chapter 4">
<ex id="7">Exam 1</ex>
<ex id="8">Exam 2</ex>
<ex id="9">Exam 3</ex>
<ex id="10">Exam 4</ex>
</exam>
</maintag>
The PHP
<?php
$xml = DOMDocument::load('examdata.xml');
$xpath = new DOMXPath($xml);
$exams = $xpath->query('//exam/ex');
$istyle = 1; //This is to add gray after every other row
echo " <table cellpadding=\"0\" cellspacing=\"3\" border=\"0\" width=\"60%\" align=\"center\">
<tr id=\"center\" bgcolor=\"#999\">
<td>Book</td>
<td>Exam</td>
<td>ID</td>
<td>Student's Exam Status</td>
</tr>
";
foreach($exams as $exams2) {
$chapter = $exams2->parentNode->getAttribute('chapter');
$examid = $exams2->getAttribute('id');
$examname = $exams2->nodeValue;
if ($examid < 5) { //where it says 5 there goes a php variable where it has the queried user's exam number from the database, again this is all finished no need to change this.
$exstatus = "You already took this exam.";
}elseif ($examid == 5) {
$exstatus = "This is your exam (exam link)";
}elseif ($examid > 5) {
$exstatus = "You are not yet on this exam";
}
echo "<tr id=\"center\"";
if ($istyle % 2 == 0)
echo " bgcolor=\"#ccc\"";
echo ">
<td>$chapter</td>
<td>$examname</td>
<td>$examid</td>
<td>$exstatus</td>
</tr>";
$istyle++;
}
echo "
</table>";
?>
Notice that the table structure is different than the way I said I want it and I was getting it above, I just changed it because I couldn't leave it the way it was.
Note that what I want to change is where it says chapter, I want it to display it once and below it to display exam 1 and below that exam2 ect. and next to the chapter put the next chapter (in this case chapter 2) and below that exam 1 and below that exam 2 ect. and after that create another table row below exam 2 and put two other chapters and below that the other exams.
Notice that the exams do not follow a pattern and this is an edited version of the file since there's hundreds of those and the values are different of what you see above.
The code above works, I just want to modify it so it could meet my requirements.
I've figured it out, it took me hours but I finally did it.
This is the code I used for the PHP, the XML stayed the same. I'll try to be as detailed as possible so it could help anyone with a similar problem or so they could extract info from it and modify it to their needs.
<?php
//self explanatory
$xml = DOMDocument::load('examdata.xml');
//again, self explanatory
$xpath = new DOMXPath($xml);
//looks for ex under exam in the xml I loaded above xml
$exams = $xpath->query('//exam/ex');
//I just put a number for testing purposes but it actually gets the user's exam id from the database
$studentexnum = "5";
//column counter, will be used to tell that after every 2 chapters, break the table data (td) and table row (tr) and create a new one
$_2chapters = 1;
//Opens the table and displays it to the client
echo "<table cellpadding=\"5\" cellspacing=\"5\" border=\"0\" width=\"25%\" align=\"center\">
<tr>"; //Opens the first table row and end the echoing
//starts the loop, for every exam, makes exam2 same as exam
foreach($exams as $exams2) {
//looks at my xml file for the tag ex (what I defined above) and gets the attribute called chapter from his parent (the tag above it)
$chapter = $exams2->parentNode->getAttribute('chapter');
//gets the attribute called id from the tag ex
$examid = $exams2->getAttribute('id');
//makes the tag ex a string so we could display it
$examname = $exams2->nodeValue;
////////////////////////////////////////Now for the Fun Part/////////////////////////////////////////////////////////////////////////////////
//conditional statement saying that if the variable chapter2 is set, display the conditions below, if it's not set (which is not when its starts the loop) do something else
if (isset($chapter2)){
//says if variable chapter defined above is equal to variable chapter 2 which is defined below do something. This is not true the first time but it is the rest of the loop, even is is a million.
if ($chapter == $chapter2) {
//variable chaptertd (which is called below) will equal to nothing if chapter equals to chapter2, this will happen at every exam (every ex tag in my xml file which is in the question above)
//this will avoid having repeated chapter, ie: chapter1 - exam one, chapter1 - exam 2, chapter1 exam 3, ect. will make it chapter 1, exam 1, exam 2, exam 3, ect
$chaptertd = "";
//if chapter does not equal to chapter2
}else {
//here we increment variable _2chapters that was 1 above, now is two, this is necessary so it could display two chapters side by side and break right before the third chapter, this will happen later
$_2chapters++;
$chapter2 = $chapter; //THIS PART IS EDITED, BUT NECESSARY
//Now we give a value to variable chaptertd, it was nothing before because I didn't want to repeat the title every time the loop found a new tag ex from my xml. This will only happen once in every chapter
$chaptertd = "
</td>
<td align=\"center\" valign=\"top\">$chapter2";//here we create the html that variable chaptertd will be displaying after a new name from the attribute chapter is found. This will display the name of the chapter to our table
}
//this else will only happen the first time the loop runs since only the first time is when the variable chapter2 is not defined, after this runs the variable chapter2 will have been defined
}else {
//chapter2 will be the same as chapter, if chapter equals to the string chapter1 so will chapter2.
$chapter2 = $chapter;
//here we create the same td as above since we want to display the name of the chapter the fist time it runs, if we don't do this the first chapter won't be display to the client
$chaptertd = "
<td align=\"center\" valign=\"top\">$chapter2";
}
//This part you don't have to concern yourself with it, I made this because I needed it to display different info depending whether the user was allow to see that exam.
//the variable examval is defined outside this code, that's on my html code which would do nothing here since it uses javascript and css. this gets the attribute id from our ex tag.
if ($examid < $studentexnum) {
$exval = "lessthan";
}elseif ($examid == 5) {
$exval = "equalto";
}elseif ($examid > 5) {
$exval = "greaterthan";
}
//here we say what happens when the variable _2chapters reaches the third attribute called chapter. we say if the remainder of variable _2chapters divided by 3 equals 0 do something
//else do nothing since we didn't define the else because we didn't needed it. this part will only happen at every third chapter, it will break from the previous chapter thus making
//it a new row right under the values of the tag ex which is under chapter 1 the third time the loops runs, but this will happen infinite amounts of time, after that it will be under
//chapter 3 and after that chapter 5 and so on.
if ($_2chapters % 3 == 0) {
//here we reset the count back to one because if we don't and there's more than one tag ex under chapter 3, it will be braking after every ex
$_2chapters = 1;
//here we echo the break from the previous chapter
echo "
</td>
</tr>
<tr id=\"center\">";
}
//here we echo the variable chaptertd which we gave different values to above depending whether the chapter's name has been declared already or not. If it has been declared, chaptertd
//won't show anything, if the chapter has never been declared it will create a new td and display the chapter's name and after that it will become nothing again
echo "$chaptertd<br />
$examname";//here we show the client what's the name of the exams under the given chapter, there could be one or one hundred of this and it will only display the chapter once and will display the rest
//of the exam names one after the other
//here we say that chapter2 equals to chapter, this way chapter2 will equal to the name of that loop, if the next time it repeats there's a new chapter the value of chapter will change
//thus making this statement false above and that will force it to create a new td with the new name until another name appears.
$chapter2 = $chapter;
}
//close the table to have a well formatted html file to display to the client.
echo "
</td>
</tr>
</table>";
?>
I actually figured it out a while ago, but this "smart forum" doesn't allow me to answer my OWN question before 8 hours because I don't have enough points or something. It's like as if it was trying to say that because I am new here I am dumb and can't find the solution to my problem on my own inside 8 hours. So I went to sleep. I just wanted to help other people that might come to this post in the future and hopefully the answer would answer some of their questions.
You probably meant...
foreach($exams as $exam)
...to get an item from the array, instead of...
foreach($exams as $exams)
BTW i would think of other names for the variables exam and ex, use names that describes what they are, maybe exam and chapter.

Categories