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

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" />';
}
?>

Related

Personalized content

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>

How to generate form fields based on specific table columns fields names only?

I'm generating dynamic form inputs based on table column field names with this simple code :
<form id="generate-user-register-form" type="POST">
<?php
$queryuser= "DESCRIBE users";
$resultstmt_queryuser= $conn->query($queryuser);
$fields = array();
while($row = $resultstmt_queryuser->fetch_assoc()) {
$fields[] = $row['Field'];
}
foreach($fields as $field): ?>
<div class="col-md-6">
<?php echo "$field: "; ?>
<input class="form-control" type="text" name="<?php echo $field; ?>" />
</div>
<?php endforeach; ?>
<input type="button" name="submit" value="submit"/>
</form>
Ok this works great but the first 10 fields are unnecessary and the first column id is autoincrement so it is definitely not needed as a form input. Is there a way for me to only generate specific fields without having to manually hard code something like the below code 10 times?
if($field !="id"){
//generate input
}
I think what you are trying to do might have different approaches considering how to decide if a field should be an input or not. For example.
Consider that your table would look like this:
+----+------------+-------------+-------------+------------+
| id | name_input | email_input | phone_input | created_at |
+----+------------+-------------+-------------+------------+
| 1 | John Smith | not#me.com | 888 333 444 | 2018-08-26 |
| 2 | Lila White | not#us.com | 412 322 555 | 2018-08-27 |
+----+------------+-------------+-------------+------------+
So, with this table you could easily find the keyword input in the columns and assign only them to the form:
while($row = $resultstmt_queryuser->fetch_assoc()) {
if (strpos($row['Field'], '_input') === false) {
continue;
}
$fields[] = $row['Field'];
}
Or, as #IdontDownVote pointed out in the comments above, you can use a count inside the loop and only add the fields if after some number or betweem some, or before another, like:
$count = 0;
while($row = $resultstmt_queryuser->fetch_assoc()) {
if ($count < 1 /* adding extra clauses here as && $count > 5 */) {
continue;
}
$fields[] = $row['Field'];
}someone
But I would advise against it. Why? you might ask.
Well, by nature, each field is different. The machine will certainly not know what is the label for a specific field, or what validation it should have, or what kind of information it should hold.
Most commonly, ids are integers, thought they might not be. But what about date fields? Or phone numbers? Or Postal Codes?
Generating dynamic inputs for each of them you might also have to read the name of the column as the label of each field, but still, some information you are bound to hardcoded at some point.
Validations of phone numbers, validations of postal codes, emails, websites.
Most of it will have to be hardcoded anyway in the backend before this information reach the database. So, if you are gonna have to write some specific rules for specific fields, why not specify this fields in the form as well?
It makes your life easier when trying to track down each field and you won't be entirely dependent on creating ignore rules for certain fields to be displayed like: created_at, created_by. When these fields are commonly updated by the system and not by the user (knowing who did what and when, of course).
But well, TL; DR; sometimes hardcoding is clearer and faster (on the long run) than the opposite.
[Edit]
Adding the count to the answer to be visible, if #IdontDownVote post this answer, please choose his answer.

Linked list with PHP and AJAX

I'm having troubles when making a linked list in HTML, let me explain:
In HTML I have this two selects:
<!-- This select WORKS and read the opened projects from de database -->
<select name="project" id="project">
<option value="0">Select a project</option>
<?php if (isset($result2)): ?>
<?php foreach ($result2 as $res): ?>
<option value=<?php echo $res['c_project_id'] ?>><?php echo $res['d_name'] ?></option>
<?php endforeach ?>
<?php endif ?>
</select>
<!-- This doesn't work, but I want: When I select a project, the project's categories go here -->
<select name="category" id="category">
</select>
The REAL DATA are the next: Table PROJECT
c_project_id | d_name | d_description | n_budget | d_state
1 | Test | Test Project | 100 | Open
2 | Web | Web APP | 3000 | Open
3 | C Test |Closed Project | 100 | Closed
4 | Certif.| Certificates | 2500 | Open
Table Categories (conected with table project)
c_category_id | d_name | d_description | c_project_id
1 | General| General cat | 1
2 | Test | Test cat | 1
3 | General| General cat | 2
4 | General| General cat | 3
5 | Nothing| Nothing cat | 3
6 |Program | Programming | 2
...
I have a SELECT in html that takes the project name and ID, this works in the select nÂș1
$statement2 = $conexion->prepare("SELECT c_project_id, d_name FROM project WHERE d_state= 'Open'");
$statement2->execute();
$resultado2 = $statement2->fetchAll();
Now I want: When I "click" in the first select, the second select make the statement and fulfill the second select. For testing, I just wrote a simple option. I tried with AJAX and PHP but the 2nd option is empty:
AJAX:
$( "#project" ).change(function() {
var select = $( "#project option:selected" ).val();
console.log(select); //just for testing that I took the value.
$.ajax({
type: "POST",
url: "phpPage.php",
data: { selectedProject : select }
}).done(function(data){
console.log("Done");
$("#category").html(data);
});
});
AND PHP:
if(isset($_POST["selectedProject"])){
$proy = $_POST["selectedProject"];
$output = "<option value='100'> Select your category </option>";
if($proy != 0){
$output.= "<option>" . $proy . "</option>";
}
echo $output;
}
But this return me nothing, all is empty.
FINALLY, when I tried to debug, I noticed that in one of the PHP responses, the HTML code () is been written at start of the page (in the response):
<option value='100'> Select your category </option><option>1</option>
<!DOCTYPE html>
<html lang="es">
<head>
<title>
...
Sorry for that huge question, but I'm wasting a lot of time with that and I don't know what could happen.
Thanks you!
Lets look at the breakdown of what you have and want to do. First, you have an empty select element:
<select name="category" id="category">
// empty
</select>
Then, you are tripping off an ajax call which returns data from your PHP. This ajax is simply taking all the returned html from the PHP and putting it in the middle of that above select:
$("#category").html(data);
Your PHP is where you are creating too much information on output. This is usually where its a good idea to isolate your "ajax php scripts" from normal full html build php scripts. So that you are only outputting what you need for that specific ajax call.
In your above PHP, you have:
if(isset($_POST["selectedProject"])){
$proy = $_POST["selectedProject"];
$output = "<option value='100'> Select your category </option>";
if($proy != 0){
$output.= "<option>" . $proy . "</option>";
}
echo $output;
}
// you must have more page generation below this based on your Q (?)
You can either isolate the above code into a new ajax response script (include any needed db actions and pull of data from the database based on the POST arg value, etc).... OR, you can add exit; after your echo $output;... so long as no other extra html was being output BEFORE this if block.
if(isset($_POST["selectedProject"])){
$proy = $_POST["selectedProject"];
$output = "<option value='100'> Select your category </option>";
if($proy != 0){
$output.= "<option>" . $proy . "</option>";
}
echo $output;
exit; // <-- halt so none of the other following html spills out
}

reply to message: update mysql table where id matches?

I have a messaging system on my site that allows users to send and receive messages to each other.
the bit I am working on now is if a user sends another user a message and the user reads this message, they can reply to it.
at the moment my html form is set up with the message content echoing out in the text area, the user can then remove this content from the text area and re type what they want in it.
then as soon as they hit submit this then should go to message_reply.php and this should insert the new message content where the original message id exists and send it back to the user it came from so this means again update message content where the id, user_to_id and user_from_id is matched and it should insert the original subject with a :reply suffix and also update 'read_message' and set the enum value from 1 back to 0 (as in unread).
I'm struggling with this because I'm new to php and mysql. please can someone show me what I need to do.
my mysql table is called 'ptb_messages' and its laid out like so:
id | from_user_id(the person who sent msg) | to_user_id (recipient) | content | date_sent | read_message | deleted_to | deleted_from |
here's my html form:
<form action="message_reply.php?to=<?php echo "$profile_id"; ?>" method="post">
<textarea name="textarea" id="textarea">
<?php echo "{$message['content']}"; ?>
</textarea>
<?php
}
?>
<input type="image" src="assets/img/icons/email_send.png"
width="50" height="34" name="send_button" id="send_button">
</form>
mysql function (message_reply.php)
<?php
//We check if the form has been sent
if(isset($_POST['textarea'])) {
$textarea = $_POST['textarea'];
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc()) {
$textarea = stripslashes($textarea);
}
//We check if all the fields are filled
if($_POST['textarea']!='') {
$sql = "UPDATE ptb_messages SET (id, from_user_id, to_user_id, textarea) VALUES (NULL, '".$_SESSION['user_id']."', '".$message['from_user_id']."', '".$textarea."');";
mysql_query($sql, $connection);
echo "<div class=\"infobox1\">The message has successfully been sent.</div>";
}
}
?>
In your HTML code, the image is not going to submit the form, so nothing will happen when you click it. You need to either add an onclick or use a submit button (you can use CSS to show an image in the submit button):
onclick example:
<form id="need_an_id_here"
action="message_reply.php?to=<?php echo "$profile_id"; ?>"
method="post">
... your textarea
<input type="image" src="assets/img/icons/email_send.png"
width="50" height="34" name="send_button" id="send_button"
onclick="document.getElementById('need_an_id_here').submit();">
</form>
Also, though it is not your immediate question, your code is prone to security issues (SQL injection, XSS...). You should lookup some tutorials on Prepared Statements and apply it in your code.

Dynamic content in 2 columns (rather than one!)

I have one table which display data as from Dynamic Content in 1 column. I would like the content to move to a second column when the number of cell is >3. (ie. if there are 3 cells to display, it would be display in 1 col, and 4 cells or more it would be displayed in 2 columns. Note that the dynamic content will never go over 6 cells.
I have to say I can find my way with css and html but javascript is another issue... however I do realize it might be the only way.
Any Javascript , jQuery script available to get my result?
Data to be displayed like so:
| Col1 | | Col1 || Col2 |
--------- -----------------
| Data1 | ----> | Data1 || Data4 |
| Data2 | | Data2 | etc...
| Data3 | | Data3 |
Not sure if this would help but the Code calling for the dynamic content (and putting it in the table) is:
<table id="myTable">
<?php
$str1="";
$flag1=1;
while($rowReview1=mysql_fetch_array($resultReview1)){
$st1="";
$val=$rowReview1["ratingValue"];
$sName=$rowReview1["criteriaName"];
if($val>0){
for($ii=1;$ii<=$val;$ii++){
$st1.="<img src=\"$directory/images/orange.gif\" \>";
}
for($jj=$val;$jj<5;$jj++){
$st1.="<img src=\"$directory/images/gray.gif\" \>";
}
}else{
$st1="";
}
if($val > 0){
$str1.="<tr><td>$sName</td><td>$st1</td></tr>";
}else{
$str1.="<tr><td>$sName</td><td>N/A</td></tr>";
}
}
echo $str1;
?>
</table>
The page can now be seen live here: http://www.top10banques.com/avis/index2.php?item_id=1
The tables I'm trying to edit are the ones below the page break "l'evaluation des clients".
Thanks again for any help you could provide and Happy Holidays to all!
Assuming you're using standard table structure, first I would put all your data into one column, regardless of how many there are. Then I would move them dynamically:
EDIT
Here's a working sample of what you're trying to do. The problem was you have TWO div cells per row, I thought you only had one:
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
</head>
<body>
<script type="text/javascript">
$(function(){
var allRows = $('#myTable tr');
if(allRows.length > 3) {
var extraData = $('#myTable tr:gt(2) td')
var j = 0;
for (i=0;i<extraData.length/2;i++) {
$(allRows[i]).append(extraData[j])
$(allRows[i]).append(extraData[j+1])
j=j+2;
}
$('#myTable tr:gt(2)').remove();
}
});
</script>
<table id="myTable">
<tr><td>Data1</td><td>Data11</td></tr>
<tr><td>Data2</td><td>Data21</td></tr>
<tr><td>Data3</td><td>Data31</td></tr>
<tr><td>Data4</td><td>Data41</td></tr>
<tr><td>Data5</td><td>Data51</td></tr>
<tr><td>Data6</td><td>Data61</td></tr>
</table>
</body>
</html>
NOTE the above solution will only work to your exact specifications. If you want this to be reusable (ie, takes any number of rows with any number of cells), you may have to do some additional tweaking.
WORKING UPDATE FOR MULTIPLE TABLES
See the code I posted here on Pastie: http://pastie.org/755963
Note that the tables are now referenced by classes instead of ids. Also, I want to say that I agree that this solution could (and maybe should) be handled server side, I am merely answering the question as the OP asked...
I would probably build a JSON object with this data in the PHP instead of injecting it into the DOM at ALL at first. This way, you don't have the overhead of the javascript restructuring existing data in the DOM, its just positioning it from scratch.
I would have thought this would be straightforward using CSS (but I'm no CSS expert).
Something like this deals with a more generic case in PHP:
function multi_columns($inp_array)
{
$max_cols=4;
$target_rows=3;
if (count($dyn)>$max_cols*$target_rows) {
// won't fit in this number of cols/rows
// add more rows
$rows=count($dyn)/$max_cols;
$target_rows= ($rows==(integer)$rows) ? $rows : $rows+1;
} elseif (count($dyn)>$max_cols*$target_rows) {
// reduce to number of cols needed
$cols=count($dyn)/$target_rows;
$max_cols= ($cols==(integer)$cols) ? $cols : $max_cols;
}
print "<table>\n";
for ($y=1; $y<=$target_rows; $y++) {
print "<tr>\n";
for ($x=1; $x<=$max_cols; $x++) {
print "<td>";
if (array_key_exists($y+$x*$target_rows, $inp_array)) {
print $inp_array[$y+$x*$target_rows];
}
print "</td>";
}
print "</tr>\n";
}
print "</table>\n";
}
This problem begs to be solved at the server and improve page performance by eliminating a JavaScript script.
Secondly, you can simplify life by not using a table, but rather div's.
Let us have a look first at a proposed data structure. We will hold all output in an array since you are using PHP.
$data=array[0...n];
That simply sorts the business logic generation.
Now let us look at the presentational logic, first visually the proposed divs!
$data_length=m
j=0 j=1 j=2 j=3 ..... j= x
i=0 [1] [4] [7] [10] []
i=1 [2] [5] [8] [11] []
i=2 [3] [6] [9] [12] []
y [] [] [] [] []
All divs will be floated left.
A clearing div will be printed once the row is completed.
Now we need to define the relationships of our data versus the position. A bit of observation of the table, shows that all horizontal positional values are separated by 3 and all vertical by one (i.e we need to iterate over our array $data in steps of three!), effectively floating our divs as follows:
j=0 j=1 j=2 j=3 ..... j= x
i=0 [1] [4] [7] [10] []
Pseudo algorithm
$imax=2; // spec
$number_cells = m/imax // total number of cells
$jmax=$number_cells/3 // check rounding etc left out at this stage
// you can use mod % to see if there are
// remainders etc.. on second script iteration
And now for the iteration
for ($i=0;$i<$imax-1;$i++){
for ($j=0;$j<$jmax;$j++){
$out.=wrap_in_div($data[($j*3)+(i+1)]);
}
}
Note that I have not bothered to define lay out the function wrap_in_div as is trivial.
Hope it helps Merry Christmas! Program was off my head so please translate the pseudo-code into real $! :)

Categories