How to pass a variable from the url thru to a submit? - php

I am passing a variable fprs thru the URL and i can't seem to get it past the submit event. My Variable $userID which is from the URL becomes out of scope when I hit my submit button. How can I pass this variable to my query successfully?
As you can see, i am getting the fprs from the URL, transfering it to the $userID, then when I submit, the $userID becomes empty.
$userID ="";
$usID="";
if(isset($_GET['fprs'])){
$usID = substr($_GET['fprs'], 8);
}
$userID = intval($usID);
if(isset($_POST['btnChange'])){
if($Validate == true){
$link = mysqli_connect($servername,$username,$password,$database);
var_dump($userID);
$updatePassStr= "Update User set Pass='$hashPass' WHERE UserID='$userID'";
if($update = mysqli_query($link, $updatePassStr)){
echo "good";
}
else{
$Error = "Some error occured with the database, please wait a little and try again.";
}
}

Create a hidden field userIDin your form and store $userID there. After submit, retrieve the value with $userID=$_POST['userID'].

Related

PHP - Get the id of the table row clicked

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

Insert URL text into database using x-editable

I have a table with inline editing using X-editable and everything is working fine including the value being submitted to the database, but for some reason it will display my echo in the else section.
Here is my PHP code:
require("config.php");
$userid = $_SESSION['user']['id'];
$sql = "SELECT fb_url, tw_url, ggl_url FROM social_preferences WHERE user_id = :userID";
$stmt = $db->prepare($sql);
$stmt->bindParam(":userID", $userid, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch();
$pk = $_POST['pk'];
$name = $_POST['name'];
$value = $_POST['value'];
if(!empty($value)) {
try // save user selection to the database
{
$stmt = $db->prepare("UPDATE social_preferences SET tw_url = :twurl WHERE user_id = :userID");
$stmt->bindParam(":userID", $pk, PDO::PARAM_INT);
$stmt->bindParam(':twurl', $value);
$stmt->execute();
header("Location: admin-social.php");
die("Redirecting to admin-social.php");
} catch(PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); }
}else {
echo 'Something went wrong!';
var_dump($value);
}
Here is my HTML code:
<a name="tw-url" id="tw-url" data-type="text" data-pk="<?php echo ($userid);?>" title="Edit"><?php echo ($result['tw_url']);?></a>
Like I said above everything seems to be working but it redirects to a page that will display my echo Something went wrong!even though it submitted the value to the DB. I included the var_dump to see if there is a value and that returns NULL. Can someone please help me? Any ideas why it would submit the right value to the database but redirect to my error?
Also, at what point does it send it to the database? I have a table in a form with a save button, but when I open the editable text and submit the new value does it send to the database when I save from the pop-over or when I click the save button in my table form?
The else statement is executing because when your details inserted into DB, you have set a header which redirects to the same page, in that case the variable $value value set to empty and your else statement executes.
The above answer is only valid if you set your header to same page.

Reading data from session couse data reset(php)

I am having trouble with sending variable with session. Goal is to automaticaly add user id in tree menu item, after successfull login.
Login code:
in if clause when login is success
$data['login']=true;
$row = $db->fetchAssoc($res);
$data['username'] = $row['username'];
$_SESSION['id'] = $row['id_user'];
$data['id_user']=$row['id_user'];
}
else {
$data['login']=false;
}
$data['success']=true;
echo json_encode($data);
Function for adding tree node code bellow:
$_POST['action'] == "addNode"){
$uid= $_SESSION['id'];
$id = clean($_POST['id']);
$leaf = clean($_POST['leaf']);
if($leaf == "true"){
..insert clause
}
...insert clause(inserting in database)
}
When I try to add new item in tree node, the user id is read correctly once and doesn't work until I dont refresh page(checked with firebug).
If someone can help me I will apreciate.

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.

$_SESSION difficulties

I am creating a login script that stores the value of a variable called $userid to $_SESSION["userid"] then redirects the user back to the main page (a side question is how to send them back where they were?).
However, when I get back to that page, I am echoing the session_id() and the value of $_SESSION["userid"] and only the session id shows up. It had occurred to me that maybe my redirect page needs to have at the top, but if this were true, then the session_id I'm echoing would change each time I end up on the page that is echoing it. Here is the script:
<?php
session_start();
include_once("db_include.php5");
doDB();
//check for required fields from the form
if ((empty($_POST['username']) && empty($_POST['email'])) || empty($_POST['password'])) {
header("Location: loginform.php5");
exit;
} else if($_POST["username"] && $_POST["password"]){
//create and issue the query
$sql = "SELECT id FROM aromaMaster WHERE username='".$_POST["username"]."' AND password=PASSWORD('".$_POST["password"]."')";
$sql_res =mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
//get the number of rows in the result set; should be 1 if a match
if(mysqli_num_rows($sql_res) != 0) {
//if authorized, get the userid
while($info = mysqli_fetch_array($sql_res)) {
$userid = $_info["id"];
}
//set session variables
$_SESSION['userid'] = $userid;
mysqli_free_result($sql_res);
//redirect to main page
header("Location: loginredirect.php5");
exit; }
} else if($_POST["email"] && $_POST["password"]) {
//create and issue the query
$sql = "SELECT id FROM aromaMaster WHERE email='".$_POST["email"]."' AND password=PASSWORD('".$_POST["password"]."')";
$sql_res =mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
//get the number of rows in the result set; should be 1 if a match
if(mysqli_num_rows($sql_res) != 0) {
//if authorized, get the userid
while($info = mysqli_fetch_array($sql_res)) {
$userid = $_info["id"];
}
//set session variables
$_SESSION['userid'] = $userid;
mysqli_free_result($sql_res);
//redirect to main page
header("Location: loginredirect.php5");
exit;}
} else {
//redirect back to login form
header("Location: loginform.php5");
exit;
}
mysqli_close($mysqli);
?>
You're doing this:
while($info = mysqli_fetch_array($sql_res)) {
$userid = $_info["id"];
}
Where you should do this:
while($info = mysqli_fetch_array($sql_res)) {
$userid = $info["id"];
}
Make sure:
<?php
session_start();
Is at the top of each page.
Additionally, you can test by commenting out your redirects and echo'ing the value you're setting with to make sure you're retrieving/storing the correct value to begin with.
You need to call session_write_close() to store the session data changes.
Side answer: you can use the $SERVER["HTTP REFERER"] to redirect back, if it was filled by the browser

Categories