0v3k Shi3ld3r 0v3k Shi3ld3r - 1 year ago 57
MySQL Question

Make a varible accessable to other code on same page

Can someone please tell me how I can pass my variable

$name = $row['username'];
To my
if (isset($_POST['pass_submit']))

What is the best way to do this ? Which is best practice ?

My full code below I have mixed query's here just until I can sort out this problem then I will make the first query with prepared statements

include_once ('db.php');
$con = mysqli_connect($dbsrvname, $dbusername, $dbpassword, $dbname);
echo '<form action="code_verify.php" method="POST">
Enter Code:<input type="text" name="code_name" size="30" />
<input type="submit" name="code_submit" value="Submit" />
if (isset($_POST['code_submit']))
$new_password = $_POST['code_name'];
$mycodecheck = mysqli_query($con, "SELECT * FROM tbl1 where code='".$new_password."'");
if ($row = mysqli_fetch_assoc($mycodecheck))
// I want to make $name accessible to if (isset($_POST['pass_submit']))code below
echo $name = $row['username'];
echo '<form action="" method="POST">
Enter New Password:<input type="text" name="password_change" size="30" />
<input type="submit" name="pass_submit" value="Submit" />
echo "no match";

if (isset($_POST['pass_submit']))
require 'db.php';
$mysqli = new mysqli($dbsrvname, $dbusername, $dbpassword, $dbname);
$name =$_POST['myname'];
$password_change =$_POST['password_change'];
$password_change = password_hash($password_change,PASSWORD_DEFAULT);
$sqlpass = "UPDATE `tbl1` SET `password`=? WHERE `username`=? ";
$stmtpass = $mysqli->prepare($sqlpass) or die(mysqli_error($mysqli));
mysqli_stmt_bind_param($stmtpass, "ss", $password_change,$name);
if ( !mysqli_stmt_execute($stmtpass) )
echo "Died on bind variable parameters";
die( 'stmt error: '.mysqli_stmt_error($stmtpass) );
} // end error if

Sorry for not knowing but I need to know the best way as this is causing me confusing , Thanks in advance .

Answer Source

There are two methods (that I know):

Method 1:
Save the value in the session. Why? Then the var survives a page reload e.g. after a form submit. How could you do this?
Add on top of your page session_start(); and change
echo $name = $row['username']; to echo $_SESSION['name'] = $row['username'];
after accessing the var in your second if-statement you should delete the var e.g. $_SESSION['name'] = "";

Method 2:
Add a hidden input field with the name as it's value to the form below echo $name = $row['username'];:
<input type="hidden" name="username" value="<?php echo $name; ?>">
Now you can access it in your second if-statement with $_POST['username'];

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download