PHP - Get the id of the table row clicked - php

I'm currently creating the account management system of my website and I decided to add a feature that enables me to declare weather a specific account is active or inactive. The data is retrieved from my mysql table.
$query = mysqli_query($DBConnect,"SELECT * from REG");
echo "<table class = 'table' style = 'width:90%;text-align:center'>";
while($getData = mysqli_fetch_assoc($query))
{
$username = $getData['uname'];
$fname = $getData['fname'];
$mname = $getData['mname'];
$lname = $getData['lname'];
$bday = $getData['bday'];
$email = $getData['email'];
$contact = $getData['contact'];
$gender = $getData['gender'];
if($getData['userlevel'] == 1)
{
$userlevel = "user";
}
else
{
$userlevel = "admin";
}
if($getData['status'] == 1)
{
$status = "active";
}
else
{
$status = "disabled";
}
echo "<tr>";
echo "<td>$username</td><td>$fname</td><td>$mname</td><td>$lname</td><td>$bday</td><td>$email</td><td>$contact</td><td>$gender</td><td>$userlevel</td><td>
<a href ='..\status.php' >$status </a></td></tr>";
}
echo "</table>";
This is the content of status.php
session_start();
$DBConnect = mysqli_connect("localhost", "root","","kenginakalbo")
or die ("Unable to connect".mysqli_error());
$query = mysqli_query($DBConnect,"SELECT * from REG where id = '$_SESSION[id]'");
while($getData = mysqli_fetch_assoc($query))
{
$status = $getData['status'];
echo "'$_SESSION[id]'";
}
if($status == 1)
{
$query = mysqli_query($DBConnect, "UPDATE REG SET status = 0 where id = '$_SESSION[id]'");
}
else if ($status == 0)
{
$query = mysqli_query($DBConnect, "UPDATE REG SET status = 1 where id = '$_SESSION[id]'");
}
header("Location: admin/login.php");
What I need to do is get the ID of the row clicked and declare it in my session so that it can be used in the "status.php" file. But in this code, the last id in the table is the one that is declared into the session because of the loop. How do I get the value of the id of the row that is clicked? (is there sort of like onClick function in php? Thank you.

pass id parameter,
status.php?id=$id;
in status.php
$id = $_GET['id'];

Change:
echo "<td>$username</td><td>$fname</td><td>$mname</td><td>$lname</td><td>$bday</td><td>$email</td><td>$contact</td><td>$gender</td><td>$userlevel</td><td>
<a href ='..\status.php' >$status </a></td></tr>";
to:
echo "<td>$username</td><td>$fname</td><td>$mname</td><td>$lname</td><td>$bday</td><td>$email</td><td>$contact</td><td>$gender</td><td>$userlevel</td><td>
<a href ='..\status.php{$getData['id']}' >$status </a></td></tr>";
And in your status.php change $_SESSION['id'] to $_GET['id']. But make sure to first prevent SQL injection either through mysql_real_escape_string($_GET['id']) or through PDO.

There is no onclick function in PHP but you can create a form with a button on each row that holds the value of the row that it is in. Have that form simply do a post or a get request back to the status.php. Adding it to the session might be a bad idea.
Instead of a button you can also create a link modify your loop so that there is a property called $rowid and increment it within your loop.

Perhaps, what you really want is to use a GET superglobal here. You can switch
for
Then, you use $_GET["userid"] instead of $_SESSION[id] on the status.php page.
Also, you dont need a while for the status page. You should check the number of results, if it was 1 it means the user exists, and then you just do a $getData = mysqli_fetch_assoc($query) without the while

Related

PHP prevent URL input to delete row in database

I’m working on a blog website where the idea is that the current user that is logged in can edit and delete their own posts. I finally got it to work, but my question is how I can prevent that a user can write the following input in the URL and do the same actions as my delete.php action.
(Example) Manual URL input with topic_id:
/delete.php?del=133
Do anyone know how I can edit my existing code or know a better solution to the problem I will be much grateful!
This is how my code looks:
Profile.php:
if (#$_GET['id']) {
$check_d = mysql_query("SELECT * FROM users WHERE id ='".$_GET['id']."'");
while ($row_d = mysql_fetch_assoc($check_d)) {
echo "<div class='spacer'></div><h2 class='headertext'>Inlägg skapade av : ".$row_d['username']."</h2>";
$check_u = mysql_query("SELECT * FROM topics WHERE topic_creator='".$row_d['username']."' ORDER BY topic_id DESC");
while ($row_u = mysql_fetch_assoc($check_u)) {
$id = $row_u['topic_id'];
echo "<tr>";
echo "<td class='postmain'><a href='topic.php?id=$id' class='links'>".$row_u['topic_name']."<br /></a></td>";
echo "<td class='postmain'><p class='text'>".$row_u['topic_creator']."</p><br /></td>";
echo "<td class='postmain'><p class='text'>".$row_u['date']."</p><br /></td>";
if($_SESSION['username'] === $row_u['topic_creator']) {
echo "<td class='postmain'><a href='edit.php?edit=$id'><button>Redigera</button></a>";
echo "<a href='delete.php?del=$id'><button>Ta bort</button></a></td>";
}
echo "</tr>";
}
}
}
The highlighted code shows that only the current session (user) who made the post can edit and delete their own posts.
Delete.php:
if (isset($_GET['del'])) {
//getting id of the data from url
$id = $_GET['del'];
//deleting the row from table
$sql = "DELETE FROM topics WHERE topic_id='$id'";
$res = mysql_query( $sql );
//redirecting to the display page
header("Location:admin.php");
}
Using isset function is solution here . The isset function will check that whether user clicked the delete/modify link or not(i.e he pasted delete.php directly in link) . So your code will only execute when user clicks the link .
if (isset($_GET['del']))
{
// your profile.php code here
}
else
{
// error message
}
You can use the same $_SESSION logic to ensure anyone accessing the delete.php has the appropriate permissions.
if (isset($_GET['del'])) {
//getting id of the data from url
$id = $_GET['del'];
// Get the author for the specified post to ensure they are permitted to do so
// TODO
// Check that the author is the same as the $_SESSION user
if($_SESSION['username'] === $postAuthor) {
//deleting the row from table - FIX THIS (see below)
$sql = "DELETE FROM topics WHERE topic_id='$id'";
$res = mysql_query( $sql );
} else {
// User is not authorized, create error handling
// TODO
}
//redirecting to the display page
header("Location:admin.php");
}
Unrelated, beware of SQL injection. Bobby Tables is a good guide and you should not be using the mysql_ functions and should be using prepared statements.

How can I insert a value to DB by matching variable in url?

I have a two forms from one form. I can sucessfully store the data to database.when that form submitted user will directed to the second form. I am passing variable $uniqueid in the url from first form to second form. But, when I tried stored the data of the second form into the database that relevant to the same user its not stored.
I want to store mobile number of the user from second page.databse column also mobile number.
This is my code
<?php
include_once 'dbconnect.php';
$a = $_GET['uniquekey'];
if(isset($_POST['btn-signup']))
{
$mobilenumber = $_POST['mobilenumber'];
$xxx = mysql_query("SELECT * FROM who WHERE uniquekey = '$a'")or die(mysql_error());
$yyy = mysql_fetch_row($xxx);
if(mysql_num_rows($xxx) > 0) {
$aaa = mysql_query("INSERT INTO who(mobilenumber) VALUES('$mobilenumber')");
}
else{
echo 'wrong';
}
}
?>
$xxx = mysql_query("SELECT * FROM who WHERE uniquekey = '$a'")or die(mysql_error());
$yyy = mysql_fetch_row($xxx);
if(mysql_num_rows($xxx) > 0) {
$aaa = mysql_query("UPDATE who setmobilenumber='$mobilenumber' where uniquekey = '$a' ");
}
else{
echo 'wrong';
}
Here you can use update query for update user mobile number.
include_once 'dbconnect.php';
$a = $_GET['uniquekey'];
if(isset($_POST['btn-signup']))
{
$mobilenumber = $_POST['mobilenumber'];
$xxx = mysql_query("SELECT * FROM who WHERE uniquekey = '$a'")or die(mysql_error());
$yyy = mysql_fetch_row($xxx);
if($yy>0)
{
$update="update who set mobilenumber=$mobilenumber where uniquekey='$a'";
$query=mysql_query($update);
}
else
{
echo "wrong";
}
}

how can i display sql query in php? CLOSED

<?php
include 'config.php'; //connect to db
if(isset($_REQUEST["pwd"]) && isset($_REQUEST["name"])) {
$password = $_REQUEST['pwd']; //pass from previous page
$name = $_REQUEST['name']; //pass from previous page
$checkUserPass = mysql_query("SELECT * FROM validPersonnel WHERE Passkey = '$password' and Name = '$name'", $conn); //check if the user exist
if(mysql_num_rows($checkUserPass) == 1) {
$personnelId = mysql_query("SELECT PersonnelID FROM validPersonnel WHERE Passkey = '$password' and Name = '$name'", $conn); //query user id
while($row = mysql_fetch_assoc($personnelId)) {
echo $row['PersonnelD']; // print user id
}
mysql_close($conn);
//echo "<br/><br/>";
//echo "<script>alert('Logged In.')</script>";
//header("Refresh: 1; url=profile/profile.php?id="'.$id.');
//header('Refresh: 1; url=test.php?id=$personnelId');
} else {
echo "<br/><br/>";
echo "<script>alert('Wrong Password.')</script>";
header('Refresh: 1; url=personnelselect.php');
}
}
?>
i cannot echo the $row['PersonnelD'] the page shows blank. i cannot understand where did i go wrong. this page quesion have been solved
Looks like you have mistake in code:
echo $row['PersonnelD'];
shouldn't it be following?
echo $row['PersonnelID'];
check the mysql_fetch_assoc() function may be its parameter is empty so it can't enter the while loop
Try to debug and check the values came in the variables using var_dump() function. Ex: var_dump($row); in while loop.
In both your querys, you have
"SELECT * FROM validPersonnel WHERE Passkey = '$password' and Name = '$name'"
It should be:
"SELECT * FROM validPersonnel WHERE Passkey = '".$password."' and Name = '".$name."';"
PHP doesn't recognize the $var unless you close the quotes. The period adds the $var to the string.

Failed to assign variable taken from database to json array

I try to get the data from database to display data via ajax but failed to worked. It's partially working because data from mysql make this thing failed to function.
Here is my funds_transfer_backend.php page. This page will assign variable to json array.
session_start();
if(!isset($_SESSION['myusername']))
{
header("Location: ../index.html");
die();
}
include("../connect.php");
$myusername = $_SESSION['myusername'];
$sql="SELECT client_id FROM `client` WHERE username='$myusername'";
$result=mysqli_query($conn, $sql);
while ($row=mysqli_fetch_row($result)){
$id = $row['0'];
}
$index_num = $_POST['index_num'];
$to_account_num = $_POST['recipient'];
$amount = $_POST['amount'];
if ($amount == '' || $to_account_num == '' || $index_num == -1){
//echo "Please complete the form!";
$response = -1;
}
else {
// check account number exist
$query2 = "SELECT 1 FROM account WHERE id='$to_account_num' LIMIT 1";
if (mysqli_num_rows(mysqli_query($conn, $query2))!=1) {
//echo "Recipient account number is invalid!";
$response = -2;
}
else {
$query2 = "SELECT client.name, client.email FROM account JOIN client USING (client_id) WHERE account.id = '$to_account_num' LIMIT 1";
$result=mysqli_query($conn, $query2);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$name = $row['name'];
$email = $row['email'];
}
$response = 1;
}
} // check account num else bracket
$display = array('response' => $response, 'name' => $name);
echo json_encode($display);
However if I remove 'name' => $name from array the #stage div will trigger like image below:
Here is my funds_transfer.php page
<script type="text/javascript">
function update() {
var two = $('#index_num').val();
var three = $('#recipient_box').val();
var five = $('#amount_box').val();
$.post("funds_transfer_backend.php", {
index_num : two,
recipient : three,
amount : five
},function(data){
if (data.response==-1) {
$('#stage').show().html("Please complete the form!");
}
$('#stage').delay(2000).fadeOut();
},"json");
}
</script>
...other code goes here
<div id="stage" style="background-color:#FF6666; padding-left:20px; color: white;"></div>
<div id="confirm" style="background-color:#FF7800; padding-left:20px; color: white;"></div>
I try to check the data from db whether it exist using manual form method="post" and I can see the name being echo. Any help is appreciated and thanks in advance.
When your response is -1, your $name variable is undefined. So php could show a warning (depending on your settings) and you are trying to add an undefined variable to your array. This will invalidate your output / json.
You can set for example:
$name = '';
at the start of your script or check whether the variable is set with isset($name) before you try to use it to avoid these problems.
There are of course other solutions, like outputting your -1 directly and exiting the script there.
I always initialize my variables.
$myusername = isset($_SESSION['myusername']) ? $_SESSION['myusername'] : false;
Then you can safely do:
if ($myusername) {} without throwing warnings.
I do this weather I get my data from a db, post/get/session or json/ajax.
It takes a little extra time upfront but removes dozens of errors in the back end so you net more time.

php if else statement within a select box

I am working on a piece that allows user to create an article, but there are some restricted for an admin, which i identify as SgroupId 1. Now when I log in with my admin code, i realize i still cant post everything, except for what I identified in loadTypeUsers. I know i get the value of Sgroup1 with me, since the admin panel loads in the bar below. Also when I echo the value I get the return of 1, which should be fine.
But when I try to load the dropdown in my popup, it wont give me the full list. Instead, it loads just the list I specified in the LoadTypeUsers. Can somebody help me out here?
Thanks in advance.
~Dorv
function MakeArticleTypeDropdown(){
echo "<select name='ArticleTypeId'>";
if($SgroupId == 1 || $SgroupId == 1){
$results = LoadType();
}
else
{
$results = LoadTypeUsers();
}
while($row = mysql_fetch_array($results)){
echo "<option value='".$row['ArticleTypeId']."'>"
.$row['ArticleTypeName']."</option>";
}
echo "</select>";
}
This is tucked in the ArticleFunction.php file
function LoadTypeUsers(){
$query = "SELECT * FROM Articletype limit 1,3;";
$resultaat=SendQuery($query);
return $resultaat;
}
function LoadType(){
$query = "SELECT * FROM Articletype;";
$resultaat=SendQuery($query);
return $resultaat;
}
This is tucked in the Sentry.php file
session_start();
$UserName = $_SESSION['username'];
$result = mysql_query("select * from user where username='".$UserName."'");
while($row = mysql_fetch_array($result)){
$UserId = $row['UserId'];
$CharacterName = $row['CharacterName'];
$UserName = $row['UserName'];
$SgroupId = $row['SgroupId'];
};
$SgroupId is not defined in the function MakeArticleTypeDropdown() so it will always goes in else condition .Try something as follows
MakeArticleTypeDropdown($SgroupId)
{
//-----------your code
}
first of all, I don't see you passing the value of $SgroupId to MakeArticleTypeDropdown(). Maybe you have an scope problem and you're checking a variable $SgroupId that isn't set inside the function?
second: ($SgroupId == 1 || $SgroupId == 1) What is that || for?
I think that the LIMIT clause should be a WHERE clause.
i.e.
SELECT * FROM Articletype WHERE SgroupId = 1 OR SgroupId = 3
and perhaps the line
if($SgroupId == 1 || $SgroupId == 1){
should read
if($SgroupId == 1 || $SgroupId == 3){

Categories