I'm building a friend request system,But my problem is how to get each user value which is the id in my code,But with the code i have so far it only get and return only the first user id even when you try to add other friend it only get the first user id in my database please someone should fix my code.
users.php
<div class="users_b">
<?php
include 'db.php';
$sq = "select * from alert_users_account";
$query = mysqli_query($con,$sq);
while($row = mysqli_fetch_assoc($query)){
?>
<div class="user_dis_p">
<div id="user_img"><a href="alert_profile.php?id=<?php echo $row['id']?>"><img src="alert<?php echo $row['photo']; ?>">
</a></div> <div id="user_fs">
<a href="alert_profile.php?id=<?php echo $row['id']?>">
<?php echo $row['firstname']." "." "." "." ".$row['surname'];?></a>
<form id="f_form">
<input type="text" name="friend_id" id="friend_id" value="<?php echo $row['id']?>">
<input type="submit" id="add_user" value="ADD" onclick="return request()">
</form>
</div><?php }?>
</div>
</div>
<div id="msg"></div>
<script>
function request(){
var frnd = document.getElementById("friend_id").value;
alert(frnd);
$.ajax({
type:'get',
url:'user_request.php',
data:{
frnd:frnd
},
cache:false,
success: function(message){
$("#msg").html(message);
}
});
return false;
}
</script>
user_request.php
<?php
session_start();
include 'db.php';
if(isset($_SESSION['email'])){
$eml = $_SESSION['email'];
$sq = $con->prepare("select id from alert_users_account where email_phone=?");
$sq->bind_param('s',$eml);
$sq->execute();
$res = $sq->get_result();
$ro = $res->fetch_assoc();
$user = $ro['id'];
if($_GET['frnd']){
echo $id = $_GET['frnd'];
$sql = $con->prepare("select * from alert_users_account where id=?");
$sql->bind_param('i',$id);
$sql->execute();
$result = $sql->get_result();
$row = $result->fetch_assoc();
$frnd = $row['id'];
$sql = $con->prepare("insert into friend (user_id,friend_id)values (?,?)");
$sql->bind_param('ss',$user,$frnd);
$sql->execute();
$sql->close();
echo "successfully inserted!";
}else{
echo 'error';
}
}else{
echo 'you cant add a friend!';
}
?>
I also try to use post method but both still give the same feedback
It appears you will need to rewrite certain aspects of your code. Here is my explanation:
You're using a while loop to show many different form elements with the id of "friend_id".
By using document.getElementById("friend_id"), you're only able to get one of those input elements that has the id of "friend_id".
You might use class="friend_id" on your input elements and go from there.
Related
I want to indicate the currently newly added user through symbol or unique color, like when someone click on Save and the user that is added should be shown in a different color or highlighted at that glimpse and then disappear after refresh, something like what the stackoverflow does in commenting system.
This is my code of index.php in this page I'v form and after submitting this form I' added the user to the database and then I'v shown them in descending order
<form action="save.php" method="post">
<div class="text-center" id='input_tag'>
<input type="text" name="name" id= 'input'>
<input type="submit" name="submit" class="btn btn-dark " id = "button" value="Save">
</div>
</form>
<div class="container">
<div class="row">
<div class="col-md-4">
<table width="100" class="table" id = 'tb'>
<?php
$connect = mysqli_connect('localhost','root','root','user');
$query = "SELECT name from userdata order by id DESC";
$run = mysqli_query($connect,$query);
while($row = mysqli_fetch_array($run))
{
echo "<tr>";
echo "<td>".$row['name']."<td>";
echo "</tr>";
}
?>
</table>
</div>
</div>
</div>
This is save.php where the user are added to DB and then redirected to the index.php page
$connect = mysqli_connect('localhost', 'root' ,'root' ,'user');
if($connect){
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$query = "INSERT INTO `userdata`(`name`) values ('$name')";
if(mysqli_query($connect,$query)){
header('location:index.php');
}
}
}
else{
echo "not connected";
}
You can achieve this with simple CSS and JS.
Change the header function in save.php to
header('location:index.php?added=1');
Add CSS style to index.php
<style type="text/css">
tr:last-of-type {
transition: .7s background;
}
</style>
At the end of index.php add the following
<?php
if (isset($_GET['added'])){
print '<script type="text/javascript">
document.querySelector("tr:first-of-type").style.background = "red";
setTimeout(function() {document.querySelector("tr:first-of-type").style.background = unset"},2000);
</script>';
}
?>
I'm assuming that the new user is going to be displayed at first.
If you want to display the user differently the first time, then you will need
some sort of flag that says if the user has been shown yet or not.
At the time you insert the user, set the didShow flag to false.
When you show the user, check the flag and if false, show the user
with the symbol and set the didShow flag to true.
When you show the user, if the didShow flag is false, show the
user without the symbol.
Add a new column named didShow to your database. Set it to default to 0 (false).
Change the query like this:
$query = "SELECT id, name, didShow from userdata order by id DESC";
In the loop, use different formatting and update the rows that have to be updated.
$run = mysqli_query($connect, $query);
$style = 'style="color:#ccc"';
while($row = mysqli_fetch_array($run))
{
echo "<tr>";
if ( $row['didShow'] == 0 ) {
echo "<td><span {$style}>".$row['name']."</span><td>";
$updateQuery = "UPDATE `userdata` SET didShow=1 WHERE id = {$row['id']}";
mysqli_query($connect, $updateQuery);
} else {
echo "<td>".$row['name']."<td>";
}
echo "</tr>";
}
Good morning guys, I have a problem. I created one login page and connected it with another page. That page is like a sending friend request system. I want the sender to be able to view their own profile but not be able to send friend requests to their own id. How can I hide the details of the logged in user? How can I get the logged in user's id? I hope someone will help me. Thanks a lot.
Login page:
<?php
session_start();
$mysqli=new MySQLi('127.0.0.1','root','','accounts');
if(isset($_POST['login'])) {
$username =$mysqli->real_escape_string($_POST['username']);
$pass = md5($_POST['pass']);
$sql="SELECT * id FROM users WHERE username='$username' AND pass='$pass' LIMIT 1;";
$result = mysqli_query($mysqli,$sql);
if(mysqli_num_rows($result)>0)
$row = mysqli_fetch_array($result);{
$_SESSION['loggedIn'] = true;
$_SESSION['uid'] = $result['id'];
$result['id']= trim($row["id"]);
header ("Location:Home.php");
exit;
}
}
?>
Home page:
<?php
session_start();
$_SESSION['uid'];
$db = new PDO('mysql:host=127.0.0.1;dbname=accounts','root','');
require 'class/friends.php';
$query = $db->prepare("SELECT * FROM users");
$query->execute();
if($query->rowCount()>0)
{
while($fetch = $query->fetch(PDO::FETCH_ASSOC)) {
$id = $fetch['id'];
$username = $fetch['username'];
$profile = $fetch['profile'];
$email = $fetch['email'];
?>
<form method="post"><table>
<tr class="border_bottom">
<td height="230">
<img src='<?php echo $profile;?>'width="200" height="200"/>
</td>
<td><td></td></td>
<td><?php echo $username;?><br />
<?php echo $email;?>
</td>
<?php
if($id != $_SESSION['uid']) {
if(Friends::renderfriendship($_SESSION['uid'],$id,'isThereRequestPending')== 1){
?>
<td><button class="request_pending" disabled>Request Pending</button></td>
<?php
} else {
if(Friends::renderfriendship($_SESSION['uid'],$id,'isThereFriendShip')== 0) {
?>
<td><button class='friendBtn_add' data-uid='<?php echo $id;?>' data-type='addfriend'>Ad as friend</button></td>
<td> <button class="request_pending hidden" disabled>Request Pending</button></td>
<?php
}else{
?>
<td> <button class='friendBtn unfriend' data-uid='<?php echo $id;?>' data-type="unfriend">Unfriend</button></td>
<td> <button class='friendBtn_add hidden' data-uid=<?php echo $id;?> data-type='addfriend'>Ad as friend</button></td>
<td> <button class="request_pending hidden" disabled>Request Pending</button></td>
</td >
</tr>
</table>
</form>
<?php
}
}
}else{
}
?>
</div>
</div>
<?php
}
}
?>
</div>
</table>
Your login file seems a little big jumbled, but I will try to decipher your errors. From Progrock, the MySQLi query is wrong. You want it to look like: SELECT * FROM users WHERE username='$username' AND pass='$pass' LIMIT 1
RiggsFolly helped me notice a little error with a if statement as well. It should look like this:
if(mysqli_num_rows($result)>0) {
$row = mysqli_fetch_array($result);
$_SESSION['loggedIn'] = true;
$_SESSION['uid'] = $row['id'];
$result['id']= trim($row["id"]);
header ("Location:Home.php");
exit;
}
You had the curly bracket in the wrong column and you used the $result variable instead of the $row variable.
Apart from that, I would strongly recommend RiggsFolly's advice, as your code is very susceptible to lots of attacks and is not written very securely.
I have a script that prints in the screen all the data of a table. Associated to each row of data, I have a delete button, and I would like that, when a button of any row is cliked, the row is deleted. To do so, I have got the following code:
$con = mysqli_connect("","","","");
$result = mysqli_query($con,"SELECT * FROM `clientes_pmt`");
while($row = mysqli_fetch_array($result)){
?> <button name="delete" value="<?php echo $row['id']; ?>" type="submit"><img src="paginas/borrar.jpg" /></button>
<a href="page<?php echo $row['nombre']; ?>">
<div><p><?php echo $row['nombre']; ?></p></div>
<div><p><?php echo $row['pais']; ?></p></div>
</a>
<section class="clearboth"></section><br><?php
}
if(isset($_POST['delete'])){
$id = $_POST['delete'];
$result = mysqli_query($con,"DELETE FROM `clientes_pmt` WHERE id = '$id'");
}
mysqli_close($con);
I receive no errors but the row is not being deleted.
Enclose the button inside a form element and set appropriate action and method attributes, something like:
<form action="/delete.php" method="POST">
<button ...> [your button]
</form>
You have to modify these line
$con = mysqli_connect("localhost","root","","YOUR DATABASE NAME");
To see the result you can put a header() to the end of this part of code:
if(isset($_POST['delete'])){
$id = $_POST['delete'];
$result = mysqli_query($con,"DELETE FROM `clientes_pmt` WHERE id = '$id'");
header('location:your_page_where_the_rows_are.php');
}
I think it may be because the $id was not getting added into the query.
Try bellow?
if(isset($_POST['delete'])){ $id = $_POST['delete']; $result = mysqli_query($con,"DELETE FROM clientes_pmt WHERE id = '".$id."'); }
Use Form tag and Header for redirect your page on same page.
Try This -
<?php
$con = mysqli_connect("","","","");
$result = mysqli_query($con,"SELECT * FROM `clientes_pmt`");
while($row = mysqli_fetch_array($result)){
?>
<form action="" method="post" >
<button name="delete" value="<?php echo $row['id']; ?>" type="submit"><img src="paginas/borrar.jpg" /></button>
</form>
<a href="page<?php echo $row['nombre']; ?>">
<div><p><?php echo $row['nombre']; ?></p></div>
<div><p><?php echo $row['pais']; ?></p></div>
</a>
<section class="clearboth"></section><br><?php
}
if(isset($_POST['delete'])){
$id = $_POST['delete'];
$result = mysqli_query($con,"DELETE FROM `clientes_pmt` WHERE id = '$id'");
header('location:'.$_SERVER['PHP_SELF']);
}
mysqli_close($con);
?>
<form action="" method="post">
<?php
$sql = "select * from tb_transport";
$query = mysql_query($sql);
$a=1;
while($row=mysql_fetch_array($query))
{
$sql_2="select * from transport_two where transport_id='$row[name]'";
$query_2=mysql_query($sql_2);
$row_2=mysql_fetch_array($query_2);
?>
<input type="checkbox" name="courses[<?php echo $a; ?>][crs]" value="<?php echo $row["name"]; ?>" <?php if($row_2["transport_id"]=="$row[name]") { ?> checked="checked" <?php } ?> />< ?php echo $row["name"]; ?>
<?php
$a=$a+1;
}
?>
<input type="submit" name="save" />
</form>
Here is my form and I'm having a number of checkboxes dependent on my database records.
Here, also I have applied code that if a checkbox value exists in database then it is shown checked.
If I have checked a checkbox, then a row gets inserted with the checkbox value.
Now what I am looking for is that if I uncheck the checked checbox then that database row gets deleted.
How can I do this?
Here is my insertion code:
<?php
if(isset($_POST["save"])) {
$arr = $_POST["courses"];
for ($i = 0; $i < 20; $i++) {
if (!empty($arr[$i]['crs'])) {
$a = $arr[$i]['crs'];
mysql_query("insert into transport_two set transport_id='$a'");
}
}
}
?>
If you want to delete from a database at the moment when a checkbox is marked/unmarked, you need to use JavaScript or jQuery.
If you want to delete from a database at the moment a user clicks on the submit button, you have to send the value to your php - script which updates/deletes from a database.
just give a simple class to checkbox.
<form action="" method="post">
<?php
$sql="select * from tb_transport";
$query=mysql_query($sql);
$a=1;
while($row=mysql_fetch_array($query))
{
$sql_2="select * from transport_two where transport_id='$row[name]'";
$query_2=mysql_query($sql_2);
$row_2=mysql_fetch_array($query_2);
?>
<input type="checkbox" class="deleteFromDb" name="courses[<?php echo $a; ?>][crs]" value="<?php echo $row["name"]; ?>" <?php if($row_2["transport_id"]=="$row[name]") { ?> checked="checked" <?php } ?> /><?php echo $row["name"]; ?>
<?php
$a=$a+1;
}
?>
<input type="submit" name="save" />
</form>
Here click on any check box and jquery check it is check or uncheck. if it uncheck then ajax send request to delete this record from db.
$(document).ready(function(){
$(".deleteFromDb").change(function(e){
if ($(this).prop('checked')==false){
$.ajax({type: "POST",
url: "deleterecord.php",
data: { id:$(this).val().trim() },
success:function(result){
var response = JSON.parse(result);
if(response.error){
//here provide a error msg to user.
alert(response.error);
}
if(response.success){
alert("record deleted");
}
}});
});
}
});
Delete.php
Here perform your delete action.
$id = $_POST['id'];
$strSQL = mysql_query("DELETE FROM `table` WHERE id = ".$id);
if($strSQL){
$result['success'] = "success";
}
else
{
$result['error'] = "try again";
}
echo json_encode($result); die;
Now when you click any checkbox and if it ubcheck, the record will delete from db.
I'm creating a page which will allow an admin to select a user from a drop down list, which populates from a database. When the person is selected, the info associated with that person will then be viewed on the page. I already have a select statement which selects all the info and the drop down menu is populating correctly. However, I'm unsure on how to get that selected user's info to display on the page once selected. Would I need to do an entirely different select statement and query which checks which customer was selected? Or is there another way?
customer.php
<div id="view_form" class="view">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select name='selectCust' id='selectCust'>";
echo "<option></option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
echo "<option>$name</option>";
}
echo "</select>";
?>
</fieldset>
</form>
</div>
viewUser.php
if(isset($search)){
$select = "SELECT * FROM $cust WHERE acctNum='{$search}'";
$result = mysqli_query($db, $select);
if(mysqli_num_rows($result) > 0){
if($row = mysqli_fetch_assoc($result)){
$acct = "{$row['acctNum']}";
echo $acct;
}
}
}
script.js
$(document).ready(function(){
function searchAjax(){
var search = $('#selectCust').val();
$.post('includes/viewUser.php', {searchUsers: search}, function(data){
$('#view_form').append(data);
})
}
$('#selectCust').on('change', function(ev){
ev.preventDefault();
searchAjax();
})
})
Search.php
<script type="text/javascript "src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
$(".dropdown-users").on("change",function(event){
event.preventDefault();
search_ajax_way();
});
});
function search_ajax_way(){
var search_this=$("dropdown-users").val();
$.post("Ajaxsearch.php", {searchusers : search_this}, function(data){
$(".results").html(data);
})
}
</script>
<div id="view_form" class="view">
<form method="post">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select class="dropdown-users">";
echo "<option></option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
$acct = $row['acctNum'];
echo "<option value="$acct">$name ($acct)</option>";
}
echo "</select>";
?>
</fieldset>
</form>
</div>
<label>Enter</label>
<input type="text" name="search_query" id="search_query" placeholder="What You Are Looking For?" size="50"/>
<input type="<span id="IL_AD1" class="IL_AD">submit</span>" <span id="IL_AD6" class="IL_AD">value</span>="Search" id="button_find" />
<div class="results"></div>
//********************************************************************************************
********************************************************************************************//
Ajaxsearch.php
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db"); // Enter your information here
$term = $_POST['searchusers']
$term = mysqli_real_escape_string($con, $term);
if($term == "")
echo "Enter Something to search";
else {
$query = mysqli_query($con, "select * from USERDATEBASEHERE where ID = '{$term}' ");
$string = '';
if (mysqli_num_rows($query) > 0) {
if (($row = mysqli_fetch_assoc($query)) !== false) {
$string = "{$row['ID']}";
}
} else {
$string = "This Person does not exist";
}
echo $string;
}
?>
<div id="view_form" class="view">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select name=\"somename\" onchange=\"this.form.submit();\">";
echo "<option value=\"\">Select User</option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
$acct = $row['acctNum'];
echo '<option value="'.$acct.'">$name ($acct)</option>';
}
echo "</select>";
?>
</fieldset>
</form>
</div>
The options must have some refering value, through which you can retrieve the details of selected user, whenever the value of option is not initiated then the default value of the option will be option's label.