I need to disable or hide, button if existsusername in the table, and == logged in user
For example: username John exists in table paym we should disable button to John
table: paym
ID username column1 column2
+-------+-------------+-------------+-----------+
| 1 | John | Value | Value |
+-------+-------------+-------------+-----------+
| 2 | Alex | Null | Null |
+-------+-------------+-------------+-----------+
Only infrmation that I can provide you:((
This is button in Html:
<input class="reload-but" type="button" value="↻"">
** logic behind similar to this php code:**
<?php
$user_check_query = "SELECT * FROM paym
WHERE username = '" . $_SESSION['username'] . "' ";
$result = mysqli_query($db, $user_check_query);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
?>
Who can do fully workable code, with explained code!
Related topic to this!!
1 method is that you can populate the table in Php by echoing the Table in HTML.
Another method would be to use a for loop in ur html looping through your data and do an if else in the loop to check the existence of the username. If true, use this set of button codes, if false, use this set of button codes.
The code snippet is a little bit out of context, so it's hard to know if this is possible, but assuming your PHP and HTML are part of the same script file (or least the one with the HTML includes/requires the one with the database code), then you can do something simple like this:
<?php
$user_check_query = "SELECT * FROM paym WHERE username = '" . $_SESSION['username'] . "' ";
$result = mysqli_query($db, $user_check_query);
$showButton = (mysqli_num_rows ($result) > 0 ? true : false);
?>
...
<?php
if ($showButton == true) {
?>
<input class="reload-but" type="button" value="↻"">
<?php
}
?>
This will cause PHP to only send the button HTML to the browser when the if condition is true.
echo "<input class=\"reload-but\" type=\"button\" value=\"↻\"".(count($row) > 0 ? " disabled" : " ".">";
Or, as #Justinas said, you can just echo the button only when you have a positive result.
Related
So i have a notification page created using bootstrap alerts.
here's a snippet, each notification is an echo from a row of the database
<div class="container" >
<?php
$fetch = $conn->query("SELECT * FROM notifications");
while($row = $fetch->fetch_assoc()) {
$id = ''.$row["id"].'';
$notification = ''.$row["notifications"].'';
?>
<div class="alert alert-warning alert-dismissable ">
<a href="#" class="close" data-dismiss="alert" aria-label="close" id="close">
<form action='deletenotifications.php' method='post' id='myform' >
<input type='hidden' name='id' id='id' value="<?php echo $id ?>" />
<span type="submit">×</span>
</form></a>
<?php echo $notification; ?>
</div>
<?php } ?>
</div>
The user when pressing X needs to delete the notification, thus from the database too, so a hidden form containing the id of the alert to be sent to action deletenotication.php using jquery AJAX method
<script type="text/javascript">
$('#close').click(function(){
$.post(
$('#myform').attr('action'),
$('#myform :input').serializeArray(),
);
});
</script>
and here is the deletenotification.php snippet
$id = $_POST['id'];
$sqlf = $conn->query("SELECT * from notifications");
while($rown = $sqlf->fetch_assoc()){
$idbase = ''.$rown['id'].'';
if($id == $idbase){
$sql = $conn->query("DELETE FROM notifications WHERE id=$id");
}
}
it is deleting from the database but only if the alerts are closed in order, and only one alert is deleted, in order to delete the successive one, the page need to be refreshed.
closing the alerts 2, 3 and 4 wont delete the rows unless notification 1 is deleted,
I need if the user close ANY random alert to be deleted, and not in order
Thank you!
You don't need to iterate through all of the results just to delete a specific row by its ID. That costs you two queries instead of one, and the first one could potentially be costly if there are a ton of notifications in the database. Instead, you can just delete by the ID, like so.
if ( ! empty( $_POST['id'] ) && (int) $_POST['id'] ) {
$id = (int) $_POST['id'];
$conn->query("DELETE FROM notifications WHERE id=$id");
}
In the example above, I am casting the ID to an integer, for safety. But really, you should look at the database class you're using there, and instead use a prepared statement.
Aside: I noticed a couple of lines like this one with two single quotes. You don't need all of those. They are only helpful if you're concatenating. Or, if you were you defining a string literal.
$id = ''.$row["id"].'';
Instead, just assign it the value of the ID.
$id = $row['id'];
It's also a good idea to use and verify a CSRF token before responding to a request to delete a row from the database; i.e., make sure this request is a legitimate one. Maybe you're already doing this elsewhere, but I wanted to caution you in case.
See: https://en.wikipedia.org/wiki/Cross-site_request_forgery
I'm having a few problems with my "architecture". I'm really rusty in this field.
So the code below is basically PHP that reads a database table and prints row by row (columns are "name" (text), and "votes" (int) ) with a button near each row which is named by the "name" column as in the table.
Very simple by now, works perfectly.
Now, each button should add +1 to a row in table in the database (to votes column), by the name of the button, simple, but since the number of buttons is not constant and is changing by the number of rows in each table (dynamic), I need to create a JS event that will get a button pressed with its name/value, and call a php function (I need specifically with functions) with the name as a variable (parameter), so it will add +1 to the votes where the name is the name pressed).
$allsql = "SELECT * FROM `voting` ORDER BY `voting`.`groupName` DESC, `voting`.`votes` DESC";
$result = mysqli_query($conn, $allsql);
if (mysqli_num_rows($result) > 0) {
echo '<form method="post" id="voting_area">';// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$name = $row["name"];
$votes = $row["votes"];
echo 'name: ' .$name. ' - votes: ' .$votes. ' <button type="button" name="'.$name.'" value="'.$name.'">'.$name.'</button><br>';
}
echo '</form>';
}
Please try and explain me specifically each code (JS, AJAX, PHP).
I am building a site in which users have the ability to write post's and other users could comment on these posts.
By now I managed to create a div that contain the comment's that are posted, I have a "Like" button(not functional at this moment) and I have a "Comment" button that I want to trigger a small window that will open to recieve text from the user(the comment) and add it to my comment table(tblcomments).
The comment button has the same ID of the post it refers to(I built it that way when I echo'ed the page from php and everything sits in the same div). but I can't seem to find a way to pop-up that comment window to recieve the comment from the user and update my table with a comment for this specific post.
The section of the page that contains the comments is being refreshed every 5 seconds so adding a simple text field to the div is imposible cause it will get reset every 5 seconds.
that is how it looks on the page right now:
And that's the code that generate each and every post like this one on my main page while querying my DB:
<?php
include 'connectDB.php';
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$hash = mysqli_escape_string($conn, $_SESSION['login_user']);
$resultfr = mysqli_query($conn, "SELECT distinct U.userName,concat(U.firstName,' ',U.lastname) as fullName FROM tblUser U inner join tblfriendswith FW on FW.userName1=U.userName or FW.userName2=U.userName where U.userName!='$hash'");
$uName="";
if($resultfr!= FALSE){
while($row2 = mysqli_fetch_array($resultfr)){
$uName= $uName.$row2['userName']." ";
}
}
$result = mysqli_query($conn, "SELECT U.userName,concat(U.firstName,' ',U.lastname) as fullName,MONTHNAME(P.postDate) as dateM, DAY(P.postDate) as dateD, YEAR(P.postDate) as dateY, P.postID, P.content FROM tblUser U inner join tblPost P on P.userName=U.userName where U.userName in ('$uName','$hash') order by P.postDate desc");
if($result!= FALSE){
echo "<div class='forPosts'>";
while($row = mysqli_fetch_array($result)){
$fullName = $row['fullName'];
$day=$row['dateD'];
$month=$row['dateM'];
$year=$row['dateY'];
$content = $row['content'];
$postID=$row['postID'];
echo "<div class=\"divStyle2\"><span class=\"myText2\">Posted by " .$fullName." - ".$day." ".$month." ".$year."</span><br><div class=\"divStyle\">".$content."</div>";
echo "<br><button class=\"myButton\"> <span class=\"glyphicon glyphicon-heart pull-left\"></span> Like</button>   <button class=\"myButton\"><span class=\"glyphicon glyphicon-comment pull-left\"></span>  Comment</button>   <button class=\"myButton\" name=\"clickB\" id=\"".$postID."\"><span class=\"glyphicon glyphicon-triangle-bottom pull-left\"></span>  Show/hide comments</button></div>";
//echo "<p class=\"alignW\"><input class=\" col-sm-5\" type=\"text\" name=\"comment\" id=\"".$postID."\" placeholder=\"Write a comment\"></div>";
$result2 = mysqli_query($conn, "SELECT C.postID, C.commentID, C.userName, C.content,concat(U.firstName,' ',U.lastname) as fullN,MONTHNAME(C.commentDate) as dateM, DAY(C.commentDate) as dateD, YEAR(C.commentDate) as dateY FROM tblUser U inner join tblComment c on U.userName=C.userName where C.postID=$postID order by C.commentDate desc");
if($result2!= FALSE){
echo"<div class='forComments'>";
while($row2 = mysqli_fetch_array($result2)){
$fullN = $row2['fullN'];
$day2=$row2['dateD'];
$month2=$row['dateM'];
$year2=$row2['dateY'];
$content2 = $row2['content'];
echo "<div class=\"divStyle2\" id=\"".$postID."\"><span class=\"glyphicon glyphicon-comment\" ></span><span class=\"myText3\"> " .$fullN. " : ".$content2."</span></div>";
}
}echo"</div>";
}
echo "</div>";
}
echo" <script>
$(document).ready(function(){";
echo" $(\"button[name=clickB]\").click(function() {
link = $(this).attr('id');
$('div[id=\"'+link+'\"]').toggle();
$(\"span\", this).toggleClass(\"glyphicon glyphicon-triangle-bottom glyphicon glyphicon-triangle-top\");
});";
echo"}); </script>";
?>
I use mysqli and xampp.
I would be grateful if someone could help me to achieve my task.
Thank you!
Tom
I'm building a web App for a friend, this is my first async site and I'm learning lots of cool stuff, but there are some details that make me struggle.
This is the general idea:
This simple app gets specific tables from a database using PHP and jQuery and shows them asynchronously on the page. There's this specific table (a waitlist) that shows all atributes from all entries on the table plus a small button that SHOULD delete that specific entry, the PHP code for the creation of the table is as follows:
<?php
include("con.php");
$result = mysqli_query($c,"SELECT * FROM waitlist");
echo "<thead>";
echo "<tr>";
echo "<th>Nombre</th><th>Sillas</th><th>Hora de Llegada</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while ($places = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>". $places ['NAME']."</td>";
echo "<td>". $places ['CHAIRS']."</td>";
echo "<td>". $places ['CREATED']."</td>";
echo '<td>
<button class="btn btn-default" type="submit" name=' . $places ['ID'] . ' id="deleteWaitlist">X</button>
</td>';
echo "</tr>";
}
echo "</tbody>";
mysqli_free_result($result);
?>
This is the table schema:
CREATE TABLE WAITLIST (
ID MEDIUMINT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(255),
CHAIRS VARCHAR(255),
CREATED DATETIME NOT NULL,
PRIMARY KEY(ID)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
What is the best way of having the button delete the entry it apears on? The function refreshes the table every few seconds so deleting it from the database is all I need. I also have an incomplete PHP function that gets called on buttonpress that shold delete the entry, but Im unsure as to how to complete it. Here it is:
<?php
include("con.php");
$sql = "DELETE FROM waitlist WHERE id='.$_POST[id]'.";
mysqli_query($c,$sql);
?>
I need to replace the $_POST[name] with an identifier for the row, this is my problem. What's the best way of doing this? Can I pass it somehow though the jquery.ajax() call? Do I need a new table attribute ID? I'm sure the "this" keyword can be used somewhere. Is PHP and ajax even the best way of doing it?
Ajax writes the table on "#result_table", here's the relevant code if it's needed:
<div class="row">
<div class="col-lg-12" id="table_container">
<table class="table table-striped" id="result_table">
</table>
</div>
</div>
</div>
EDIT: I updated the code as recomended by #vnponce
This is the code for the ajax call:
$("#deleteWaitlist").click(function(){
// Get the varible name, to send to your php
var i = $(this).attr('name');
$.post({
url: 'deleteWaitlist.php',
data: { id : i},
success: function(result){
// do some code here
// here yo can see 'result' response of YOUR_PHP_FILE
console.log(result);
}
});
});
After fiddling with the code I got rid of all errors and updated the post, but the entries are still not getting deleted.
The best way is creating an ID identifier in your table, then this identifier can be added in your 'Delete' button.
The button trigger a function that send ID, and your PHP file recive it and delete de data comparing the ID.
The identifier can be added in table schema ( i don't know if it is the rigth code, I always made in phpMyAdmin )
CREATE TABLE WAITLIST (
ID MEDIUMINT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(255),
CHAIRS VARCHAR(255),
CREATED DATETIME NOT NULL
);
First add the ID in delete photo.
echo '<td>
<button class="btn btn-default" type="submit" name=' . $places ['ID']. ' "id="deleteWaitlist">X</button>
</td>';
The ajax
$("#deleteWaitlist").click(function(){
// Get the varible name, to send to your php
var i = $(this).attr('name');
$.post({url: "YOUR_PHP_FILE.php", {id: i}, success: function(result){
// do some code here
// here yo can see 'result' response of YOUR_PHP_FILE
// console.log(result);
}});
});
Now your PHP with ID
<?php
include("con.php");
$sql = "DELETE FROM waitlist WHERE id='.$_POST[id]'.";
mysqli_query($c,$sql);
?>
Well I hope help. If i have an error or you have a question let me know.
UPDATE*
Maybe there's an error deleteWaitlist.php , you can return error if it exist.
<?php
include("con.php");
$sql = "DELETE FROM waitlist WHERE id='.$_POST[id]'.";
if ( ! mysqli_query($c,$sql) )
{
return "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
I'm trying to work my way through a problem. It's two parts:
I want to create a loop that reads out each of my page's menu_name from the database and on the same line that it reads it out, put a radio button to change the visibility. So far It looks like my radio buttons are all connected because (instead of being checked "no" for each of them it is only checked no on the last <li> item:
//K's function:
function get_all_pages() {
global $connection;
$query = "SELECT *
FROM pages ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$page_set = mysql_query($query, $connection);
confirm_query($page_set);
return $page_set;
}
//K's function:
function list_all_pages(){
$output = "<ul>";
$page_set = get_all_pages();
while ($page = mysql_fetch_array($page_set)) {
$output .= "<li>{$page["menu_name"]}</li>";
$output .= " <input type=\"radio\" name=\"visible\" value=\"0\" checked=\"checked\" /> No <input type=\"radio\" name=\"visible\" value=\"1\" /> Yes";
}
$output .= "</ul>";
return $output;
}
I'm trying to do some sort of ajax thing with Javascript.. so I want the visible radio buttons to be next to my dynamically generated menu list. I want them to all be checked to no... when they are checked to yes I want a dropdown list to appear where they can pick the numbers 1-8 (the numbers will mean what position they will appear in).
I am new and trying to figure this out is a little out of my reach without some assistance from Javascript and php/mysql experts.
Your radio buttons all have the same "name" attribute, so you can only select one at a time. You could append some unique identifier to the attribute value. For example, visible_{$page_id}:
function list_all_pages(){
$output = "<ul>";
$page_set = get_all_pages();
while ($page = mysql_fetch_array($page_set)) {
$page_id = urlencode($page["id"]);
$output .= "<li>{$page["menu_name"]}</li>";
$output .= " <input type=\"radio\" name=\"visible_{$page_id}\" value=\"0\" checked=\"checked\" /> ";
$output .= "No <input type=\"radio\" name=\"visible_{$page_id}\" value=\"1\" /> Yes";
}
$output .= "</ul>";
return $output;
}
Advanced tip: With PHP you can simplify the processing of "page" data by using specially-formatted input names -- like so:
Let the radio buttons use names like pages[$page_id][visible].
Let the lists (aka select) use a name like pages[$page_id][order].
Once the user submits this data, PHP converts it into a "pages" array (with indices being page_id's). You can then do something like:
function process_pages($pages) {
foreach ($pages as $page_id => $data) {
$is_visible = $data['visible'] === '1';
$page_order = (int) $data['order'];
//... update page's visibility/page order
}
}
$pages = $_REQUEST['pages'];
process_pages($pages);
1. Change the name attribute of each radio button to disconnect them e.g. use visible1, visible2, ...
2. put the <input> tag within <li> after your <a> tag. That will show your radio buttons next to your dynamically generated menu.
3. You can create select list for number by creating and calling a javascript function that will be executed by onclick of Yes options, which will create and show the select fields.
Please comment on the answer if you need more clarification.