Button function for all fetch row - php

I am doing project for my university. I create a page where user can send friend request. Here I fetch data from another table and put button for each row data.
My problem is that when one button click other row button also was change to friend request. I need a solution for it.
How to make one add friend request button is equal to one row id and how to avoid other button affected whenever click particular row.
My code is included below. I hope you guys will help me. Thanks in advance.
<?php
session_start();
$_SESSION['myid'];
$mysqli=new MySQLi('127.0.0.1','root','','learning_malaysia');
$sql = "SELECT * FROM tutor_register INNER JOIN tutorskill ON tutor_register.register_ID = tutorskill.register_ID ORDER BY
tutor_register.register_ID='".$_SESSION['myid']."'desc";
$result= mysqli_query($mysqli,$sql);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_array($result))
{
$register_ID=$row["register_ID"];
$username = $row['username'];
$profile = $row['profile'];
$email = $row['email'];
$address=$row['address'];
$gender=$row['gender'];
$main_subject=$row["main_subject"];
$subject_add=$row["subject_add"];
$rate_main=$row["rate_main"];
$rate_add=$row["rate_add"];
$qualification=$row["qualification"];
?>
<table><form method="post">
<tr class="border_bottom">
<td height="230"><img src='<?php echo $profile;?>'width="200" height="200"/> </td><td><td></td></td>
<?php
if($register_ID == $_SESSION['myid']){
?>
<td><label>Your Profile</label></td>
<?php
} else {
?>
<form method="post">
<td><button class='friendBtn unfriend' name="" data-type="unfriend">Unfriend</button>
<input type="hidden" name="id" value="<?php echo $row['register_ID'];?>" />
<input type="submit" name="addfriend" data-type='addfriend' id="addfriend" value="<?php
if($_SESSION['status'] == 'yes'){
echo 'Request Sent';
}
else {
echo 'Addfriend';}
?>" data-uid=<?php echo $row['register_ID'];?>/></td> </form>
<?php
}
}
?>
</tr>
</div>
</table>
</form>
<?php
if(isset($_POST['id']) ) {
$user_id = $_SESSION['myid'];
$friend_id = $_POST['id'];
$sql="INSERT INTO friends(user_id,status,friend_id)" ."VALUES('$user_id','yes','$friend_id') ";
if($mysqli->query($sql)=== true) {
$_SESSION['status']="yes";
$_SESSION['id']=$row['id'];
} else {}
}
}
?>
</body>
</html>

You need to replace the following block in your code:
<input type="submit" name="addfriend" data-type='addfriend' id="addfriend" value="<?php
if($_SESSION['status'] == 'yes'){
echo 'Request Sent';
}
else {
echo 'Addfriend';}
?>" data-uid=<?php echo $row['register_ID'];?>/>
With the one mentioned below. This will solve your problem.
<input type="submit" name="addfriend" data-type='addfriend' id="addfriend" value="<?php
if($_SESSION['status'] == 'yes' && $row['register_ID']==$_SESSION['id']){
echo 'Request Sent';
}
else {
echo 'Addfriend';}
?>" data-uid=<?php echo $row['register_ID'];?>/>

Related

Data transfer between php pages using sessions

I am trying to transfer data between php pages using session. My code is as below:
check_code.php:
<?php
session_start();
echo "<form action=\"check_code.php\" method=\"post\">";
echo "<h2>Your Name. *</h2><input type='text' name='user_name'>";
echo "<br><br>";
echo "<h2>Your age. *</h2><input type='text' name='age'>";
echo "<br><br>";
echo "<br><br><br>";
echo "<div><input type='submit' value='Review'></div>";
echo "</form>";
?>
<?php
if((empty($_POST['user_name'])) || (empty($_POST['age'])) ) {
echo "<h2>Please enter your user name and age</h2>";
} else {
echo "<form action=\"page2.php\" method=\"post\">";
$user_name = $_POST['user_name'];
$age = $_POST['age'];
echo "Below are the details entered:<br>";
echo "Name: $user_name";
echo "Age: $age";
echo "Select any one: ";
echo '<td bgcolor="#EAEAEA" style="color:#003399"><input type="checkbox"
name="subject[]" value="Science">Science</td>';
echo '<td bgcolor="#EAEAEA" style="color:#003399"><input type="checkbox"
name="subject[]" value="Math">Math</td>';
echo "<br>";
$_SESSION['user'] = $_POST['user_name'];
$_SESSION['age'] = $_POST['age'];
$_SESSION['subject'] = $_POST['subject'];
echo "<input type=\"submit\" value='Add to DB' >";
echo "</form>";
}
?>
page2.php:
<?php
session_start();
$user_name = $_SESSION['user'];
$age = $_SESSION['age'];
$subject = $_SESSION['subject'];
echo "<h2>Below are the details entered:</h2><br>";
echo "<h2>Name: </h2>$user_name";
echo "<h2>Age: </h2>$age";
echo "<h2>Subject selected: </h2>";
for ($i=0;$i<sizeof($subject);$i++) {
echo " $subject[$i] ";
}
?>
The name and age get displayed in the final page (page2.php). The subject does not get passed to the next page. What mistake am I making here?
Any help would be appreciated!!!
The code you gave had some issues, so I rewrote your code and you might try the one below:
check_code.php file:
<?php session_start(); ?>
<form method="POST" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<label>Your name</label>
<input type="text" name="name" />
<br>
<label>Your age</label>
<input type="number" name="age" />
<hr>
<button type="submit" name="review">Review</button>
<?php if(isset($_SESSION['details'])) { ?>
<button type="submit" name="unset">Unset</button>
<?php } ?>
</form>
<?php
if(isset($_SESSION['details'])) {
if(isset($_POST['unset'])) { // If pressed "unset", remove the session and the values and restart
unset($_SESSION);
session_destroy();
}
}
if(isset($_POST['review'])) {
if(!empty($_POST['name']) && !empty($_POST['age'])) { // If fields are not empty
?>
<p>Your Details:</p>
<table>
<tr>
<td>Name<td>
<td><?php echo $_POST['name']; ?></td>
</tr>
<tr>
<td>Age<td>
<td><?php echo $_POST['age']; ?></td>
</tr>
</table>
<?php
$_SESSION['details'] = array(
'name' => $_POST['name'],
'age' => $_POST['age']
// Storing them in array as $_SESSION['details'][name/age/whatever]
);
}
else {
echo 'Please fill in the fields.';
}
}
if(isset($_SESSION['details'])) {
?>
<p><?php echo $_SESSION['details']['name']; /* Stored name in session */ ?>, Please Select Subject:</p>
<form method="POST" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<label>Science</label>
<input type="checkbox" name="subject[]" value="science" />
<br>
<label>Math</label>
<input type="checkbox" name="subject[]" value="math" />
<hr>
<button type="submit" name="send">Remember My Choice</button>
</form>
<?php
if(isset($_POST['send'])) { // If you send the second form, then...
if(isset($_POST['subject'])) { // If selected subject
$_SESSION['subject'] = array();
for($i = 0; $i < count($_POST['subject']); $i++) {
$_SESSION['subject'][] = $_POST['subject'][$i]; // store all values of "subject" in the session
}
}
header('location: page2.php');
}
}
Explanation:
You wanted the user to choose a subject after submitting the form, and defined it when the user can not check subject - line 33. when the user can not define the variable, you can continue - but with errors - and that's what I got when I tried your code.
So what I did was the following steps:
Send the first form with the name and the age
Define $_SESSION variable named "details" (as array that held the required information)
If this variable exists - then allow the user to select a subject.
Then, when you choose one (or more) subjects, they're saved too in the session:
page2.php file:
<?php
session_start();
if(isset($_SESSION['details'])) {
?>
<p>Your name is <?php echo $_SESSION['details']['name']; ?> and your age is <?php echo $_SESSION['details']['age']; ?></p>
<?php if(isset($_SESSION['subject'])) { ?>
<p>And your subject(s) are <?php echo implode(', ', $_SESSION['subject']); ?></p>
<?php } else { ?>
<p>You don't have any subject</p>
<?php
}
}
else {
die('An Error Occurred');
}
On page2.php I checked if the details are set. if they are, then we can proceed and check if the subject(s) are set too. In case details are not set, the connection will die and print an error message. If you don't set the subject, you'll get a message about it, too.
Important note:
Your code, and this one too are vulnerable. Do not use these in a server, unless you take care about XSS protection. You may escape characters and use Regular expressions to "Sanitize" the input.
You can replace your current code with this one.
I hope it will be helpful

Building a checkbox list from a database query and retaining the checkbox after a form submit

I am trying to build a simple form which queries a database, grabs a list of email addresses and then creates a table based on the results. What I would like it to do is retain the checked boxes after a submission but am having trouble figuring it out based on the way I've created my table. I can do it no problem if I manually build the table but that defeats the purpose. Here is the code I am working with, again the only change I would like it to do is retain the checked boxes.
<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="style/style.css"/>
</head>
<body>
<?php include('include/connect.php'); ?>
<h1>This is a test</h1>
<div class="emailform">
<form action="" method="post">
<table id="emails">
<?php
while($row = $result->fetch_assoc()) {
unset($email);
$email = $row['Email'];
?>
<tr><td><input type="checkbox" name="select[]" value="<?php echo $email;?>"/><?php echo $email; ?></td></tr>
<?php
}
?>
</table>
<br/><br/>
<input id="manual" type="text" name="select[]"><br/><br/><br/>
<button type="submit" name="SubmitButton">Select Email Addresses</button>
</form>
</div>
<?php
if(isset($_POST['SubmitButton'])){
if(isset($_POST['select'])){
$shift = $_POST['select'];
if (count($shift) > 1 ){
$list = implode(", ", $shift);
echo $list;
} else {
echo "$shift[0] <br/>";
}
}
}
?>
</body>
</html>
Help would be appreciated, thanks
Just check if the current email in the loop exists in $_POST['select'], if it is, you check it, if it is not, clear the check. This check will be displayed in the input checkbox as <?php echo $checked;?> :
<?php
while($row = $result->fetch_assoc()) {
unset($email);
$email = $row['Email'];
// IF EMAIL EXISTS IN $_POST, CHECK IT.
$checked = "";
if(isset($_POST['select'])){
$shift = $_POST['select'];
$list = implode(", ", $shift);
if (strpos($list,$email)===false)
$checked = ""; // EMAIL NOT IN $_POST.
else $checked = "checked"; // EMAIL IS IN $_POST.
}
?>
<tr><td><input type="checkbox" name="select[]" <?php echo $checked;?>
value="<?php echo $email;?>"/><?php echo $email; ?></td></tr>
<?php
}
?>
Check if $row['Email'] isn't empty, then output "checked" attribute.
<?php
while($row = $result->fetch_assoc()) {
unset($email);
$email = $row['Email'];
?>
<tr><td><input type="checkbox" name="select[]" value="<?php echo $email;?>"<?php if($row['Email'] != false) { echo ' checked'; } ?>><?php echo $email; ?></td></tr>
<?php
}
?>

edit_subject.php is not working, the error is saying about database query failed

This is kind of the error I'm getting:
Database query failed.
I've uploaded this webpage: http://widgetcorp.bugs3.com/public/edit_subject.php?subject=1
Here's my file:
<?php require_once("../includes/session.php"); ?>
<?php require_once("../includes/db_connection.php"); ?>
<?php require_once("../includes/functions.php"); ?>
<?php require_once("../includes/validation_functions.php"); ?>
<?php find_selected_page(); ?>
<?php
if (!$current_subject)
{
// subject ID was missing or invalid or
// subject couldn't be found in database
redirect_to("manage_content.php");
}
?>
<?php
if (isset($_POST['submit']))
{
// validations
$required_fields = array("menu_name", "position", "visible");
validate_presences($required_fields);
$fields_with_max_lengths = array("menu_name" => 30);
validate_max_lengths($fields_with_max_lengths);
if (empty($errors))
{
// Perform Update
$id = $current_subject["id"];
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
$query = "UPDATE subjects SET ";
$query .= "menu_name='{$menu_name}', ";
$query .= "position={$position}, ";
$query .= "visible={$visible} ";
$query .= "WHERE id={$id} ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) >= 0)
{
// Success
$_SESSION["message"] = "Subject updated.";
redirect_to("manage_content.php");
}
else
{
// Failure
$message = "Subject update failed.";
}
}
}
// else
// {
// // This is probably a GET request
// }
?>
<?php include("../includes/layouts/header.php"); ?>
<div id="main">
<div id="navigation">
<?php
echo navigation($current_subject, $current_page);
?>
</div>
<div id="page">
<?php
// echo message();
// $message is just a variable, doesn't use the SESSION
if(!empty($message))
{
echo "<div class=\"message\">" . htmlentities($message) . "</div>";
}
?>
<?php echo form_errors($errors); ?>
<h2>Edit Subject: <?php echo htmlentities($current_subject["menu_name"]); ?></h2>
<form action="edit_subject.php?subject=<?php echo htmlentities($current_subject["menu_name"]); ?>" method="post">
<p>Menu name:
<input type="text" name="menu_name" value="<?php echo htmlentities($current_subject["menu_name"]); ?>" />
</p>
<p>Position:
<select name="position">
<?php
$subject_set = find_all_subjects();
$subject_count = mysqli_num_rows($subject_set);
for ($count=1; $count <= $subject_count; $count++)
{
echo "<option value=\"{$count}\"";
if ($current_subject["position"] == $count)
{
echo " selected";
}
echo ">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible" value="0" <?php if ($current_subject["visible"] == 0) { echo "checked"; } ?> /> No
<input type="radio" name="visible" value="1" <?php if ($current_subject["visible"] == 1) { echo "checked"; } ?> /> Yes
</p>
<input type="submit" name="submit" value="Edit Subject" />
</form>
<br />
Cancel
Delete Subject
</div>
The problem is somewhere else and not with your UPDATE query actually. If you see the link you posted, you are passing subject parameter with url, whose value is 1 which is integer.
Now when you click submit it's changing the url to http://widgetcorp.bugs3.com/public/edit_subject.php?subject=About%20Widget%20Corp .
Here as you see the subject parameter is not integer but string value name of subject. And that is causing the problem.
You are getting error as it's not retrieving the subject data from database correctly because of wrong id type. You just need to make sure the form is being posted to right url, which would be http://widgetcorp.bugs3.com/public/edit_subject.php?subject=1.
You need to correct the action parameter on the <form> tag for that.
Look for the line below in your code:
<form action="edit_subject.php?subject=<?php echo htmlentities($current_subject["menu_name"]); ?>" method="post">
And change it to
<form action="edit_subject.php?subject=<?php echo htmlentities($current_subject["id"]); ?>" method="post">
If you see, now the form will be submitted to http://widgetcorp.bugs3.com/public/edit_subject.php?subject=1, which is the correct url.

A simple operation but it giving an error I want to update each id

It is simple but I am not getting values of radio buttons for updation when I press submit.
It is giving an error in foreach statement like :Warning: Invalid argument supplied for foreach() Please say how to get the values of radio button after pressing submit button,
here I am updating the status of state .
<?php
include("db.php");
?>
<html>
<body>
<?php
$state=$_POST['state'];
if(isset($_POST['submit']))
{
$result1 = mysql_query("select state,id,status from states ");
while($rr1=mysql_fetch_array($result1))
{
//getting values of radio buttons
$myval=$rr1['id'];
echo $myval;
$val=$_POST['yes.$rr1["id"]'];
echo $val;
$val1=$val.$myval;
$vall=yes.$rr1['id'];
foreach($vall as $values)
{
echo $values;
$update=mysql_query("UPDATE states SET status='". $values."'
WHERE id='$myval' ");
}
}
}
echo "ok";
?>
<form action="" name="form" id="form" method="post" >
<?php
//session_start();
include("db.php");
$result = mysql_query("select state,id,status from states ");
while($info1=mysql_fetch_assoc( $result))
{
echo $info1['city'];
echo "<br>";
/*echo "<br>";
echo "company Name:".$info1['company_name'];
echo "<br>";
echo "salary:".$info1['maxsalary'];
echo "<br>";
//echo $info1['company_name'];*/
?>
<label><?php echo $info1['state']; ?></label>
<input type="radio" <?php if($info1['status']=="yes"){ echo
"checked='checked'"; } ?> name="yes.<?php echo $info1[ 'id']; ?>[]"
value="yes">Yes
<input type="radio" <?php if($info1['status']=="no"){ echo
"checked='checked'"; } ?> name="yes.<?php echo $info1[ 'id']; ?>[]"
value="no">no
<br/>
<?php } ?>
<br />
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
I think you need to write
$vall=yes.$rr1['id'];
to
$vall="yes".$rr1['id'];
Thanks

change dropdown from array to check box

I would like a change from the drop down to the checkbox, I want to change it because I want firstly select the list in the array can be selected before store to database via the checkbox, so the dropdown script was as follows
<?php
session_start();
define('DEFAULT_SOURCE','Site_A');
define('DEFAULT_VALUE',100);
define('DEFAULT_STC','BGS');
include('class/stockconvert_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
if(isset($_GET['reset'])) {
unset($_SESSION['selected']);
header("Location: ".basename($_SERVER['PHP_SELF']));
exit();
}
?>
<form action="do.php" method="post">
<label for="amount">Amount:</label>
<input type="input" name="amount" id="amount" value="1">
<select name="from">
<?php
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
if((isset($_SESSION['selected']) && strcmp($_SESSION['selected'],$key) == 0) || (!isset($_SESSION['selected']) && strcmp(DEFAULT_STC,$key) == 0))
{
?>
<option value="<?php echo $key; ?>" selected="selected"><?php echo $stock; ?></option>
<?php
}
else
{
?>
<option value="<?php echo $key; ?>"><?php echo $stock; ?></option>
<?php
}
}
?>
</select>
<input type="submit" name="submit" value="Convert">
</form>
and i Changed it to the checkbox as follows
<?php
session_start();
define('DEFAULT_SOURCE','Site_A');
define('DEFAULT_VALUE',100);
define('DEFAULT_STC','BGS');
include('class/stockconvert_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
if(isset($_GET['reset'])) {
unset($_SESSION['selected']);
header("Location: ".basename($_SERVER['PHP_SELF']));
exit();
}
?>
<form action="do.php" method="post">
<label for="amount">Amount:</label>
<input type="input" name="amount" id="amount" value="1"><input type="submit" name="submit" value="Convert">
<?php
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
if((isset($_SESSION['selected']) && strcmp($_SESSION['selected'],$key) == 0) || (!isset($_SESSION['selected']) && strcmp(DEFAULT_STC,$key) == 0))
{
?>
<br><input type="checkbox" id="scb1" name="from[]" value="<?php echo $key; ?>" checked="checked"><?php echo $stock; ?>
<?php
}
else
{
?>
<br><input type="checkbox" id="scb1" name="from[]" value="<?php echo $key; ?>"><?php echo $stock; ?>
<?php
}
}
?>
</form>
but does not work, am I need to display Other codes related?
Thanks if some one help, and appreciated it
UPDATED:
ok post the first apparently less obvious, so I will add the problem of error
the error is
Fatal error: Call to undefined method st_exchange_conv::convert() in C:\xampp\htdocs\test\do.php on line 21
line 21 is $st->convert($from,$key,$date);
session_start();
if(isset($_POST['submit']))
{
include('class/stockconvert_class.php');
$st = new st_exchange_conv(DEFAULT_SOURCE);
$from = mysql_real_escape_string(stripslashes($_POST['from']));
$value = floatval($_POST['amount']);
$date = date('Y-m-d H:i:s');
$_SESSION['selected'] = $from;
$stocks = $st->stocks();
asort($stocks);
foreach($stocks as $key=>$stock)
{
$st->convert($from,$key,$date);
$stc_price = $st->price($value);
$stock = mysql_real_escape_string(stripslashes($stock));
$count = "SELECT * FROM oc_stock WHERE stock = '$key'";
$result = mysql_query($count) or die(mysql_error());
$sql = '';
if(mysql_num_rows($result) == 1)
{
$sql = "UPDATE oc_stock SET stock_title = '$stock', stc_val = '$stc_price', date_updated = '$date' WHERE stock = '$key'";
}
else
{
$sql = "INSERT INTO oc_stock(stock_id,stock_title,stock,decimal_place,stc_val,date_updated) VALUES ('','$stock','$key','2',$stc_price,'$date')";
}
$result = mysql_query($sql) or die(mysql_error().'<br />'.$sql);
}
header("Location: index.php");
exit();
}
Why I want to change it from dropdown to checkbox?
because with via checkbox list I will be able to choose which ones I checked it was the entrance to the database, then it seem not simple to me, I looking for some help< thanks So much For You mate.
You have not removed the opening <select> tag.
But you removed the <submit> button.
You changed the name from "from" to "from[]".
EDIT: After your additions:
Using the dropdown list you were only able to select one value for from. Now you changed it to checkboxes and thus are able to select multiple entries. This results in receiving an array from[] in your script in do.php. Your functions there are not able to handle arrays or multiple selections in any way.
You have to re-design do.php, change your form back to a dropdown list or use ratio buttons instead.

Categories