In this code I have defined variable id now if I will use $id outside curly brackets I will get error undefined variable for $id. Is there any way in which I can use variables outside brackets.
<?php
if (isset($_GET['username'])) {
$check = $db->prepare("SELECT id, email, phone, FROM members WHERE username=:username");
$check->execute(array(':username'=>$username));
$get = $check->fetch(PDO::FETCH_ASSOC);
$id = $get['id'];
$email = $get['email'];
}
else {
// error
}
$posts =$db->prepare("SELECT * FROM posts WHERE id=:id");
$posts->execute(array(':id'=>$id));
$row=$posts->fetch(PDO::FETCH_ASSOC));
$title = $row['title'];
$body = $row['body'];
?>
<?php
$id=""; //initialize a variable with blank value
if (isset($_GET['username'])) {
// query to get data
$id = $_GET['id'];
}
else {
// error
}
?>
Try this:
You can define your variable id like global $id; define immediate after php tag started .
<?php
global $id;
if (isset($_GET['username'])) {
// query to get data
$id = $get['id'];
}
else {
// error
}
?>
Related
I want to pass the value of login.php variables $user_key & $user_id to another file statusdata.php for which I have used session. In statusdata.php I want to use those session variable value in sql query of statusdata.php file.
To achieve this in login.php I pass the value of variable $user_key & $user_id to session variable $_SESSION["key"] & $_SESSION["id"] respectively then in statusdata.php I call session variable and pass their value in variable $user_key & $user_id of statusdata.php
Now the problem is when using the variable $user_key & $user_id in SQL query it is not returning proper output but using the same variable in echo it is giving proper value mean session is working fine when I echo the variable but not working in SQL. I have also tried passing the session variable directly but the same thing is happening to work in echo but not in SQL.
login.php
<?php
// Start the session
session_start();
require "conn.php";
$user_key = '8C9333343C6C4222418EDB1D7C9F84D051610526085960A1732C7C3D763FFF64EC7F5220998434C896DDA243AE777D0FB213F36B9B19F7E4A244D5C993B8DFED';
$user_id = '1997';
$mysql_qry = "select * from applications where application_key = '".$user_key."' and application_id like '".$user_id."';";
$result = mysqli_query($conn, $mysql_qry);
if (mysqli_num_rows($result) > 0){
$_SESSION["key"] = ".$user_key.";
$_SESSION["id"] = ".$user_id.";
echo "Login Success";
}
else {
echo "Login Not Success";
}
?>
statusdata.php
<?php
// Start the session
session_start();
require "conn.php";
$user_key = "-1";
if (isset($_SESSION["key"])) {
$user_key = $_SESSION["key"];
}
$user_id = "-1";
if (isset($_SESSION["id"])) {
$user_id = $_SESSION["id"];
}
//creating a query
$stmt = $conn->prepare("SELECT applications.application_id, applications.applicant_name, applications.applicant_aadhaar, applications.applicant_phone, applications.subject, applications.date, applications.description, applications.chairperson_remark, applications.status, officer_accounts.name_of_officer, applications.officer_remark, applications.last_update_on
FROM applications INNER JOIN officer_accounts ON applications.account_id = officer_accounts.account_id
WHERE applications.application_id = '".$user_id."' AND applications.application_key = '".$user_key."';");
//executing the query
$stmt->execute();
//binding results to the query
$stmt->bind_result($id, $name, $aadhaar, $phone, $subject, $date, $description, $chairperson, $status, $officername, $officerremark, $lastupdate);
$applications = array();
//traversing through all the result
while($stmt->fetch()){
$temp = array();
$temp['applications.application_id'] = $id;
$temp['applications.applicant_name'] = $name;
$temp['applications.applicant_aadhaar'] = $aadhaar;
$temp['applications.applicant_phone'] = $phone;
$temp['applications.subject'] = $subject;
$temp['applications.date'] = $date;
$temp['applications.description'] = $description;
$temp['applications.chairperson_remark'] = $chairperson;
$temp['applications.status'] = $status;
$temp['officer_accounts.name_of_officer'] = $officername;
$temp['applications.officer_remark'] = $officerremark;
$temp['applications.last_update_on'] = $lastupdate;
array_push($applications, $temp);
}
//displaying the result in json format
echo json_encode($applications);
// Echo session variables that were set on previous page
echo "<br>key is " . $user_key . ".<br>";
echo "id is " . $user_id . ".";
?>
Output login.php
Login Success
Output statusdata.php
[]
key is .8C9333343C6C4222418EDB1D7C9F84D051610526085960A1732C7C3D763FFF64EC7F5220998434C896DDA243AE777D0FB213F36B9B19F7E4A244D5C993B8DFED..
id is .1997..
output I want from statusdata.php (I am getting it if I use direct value in variable $user_key & $user_id not session variable from login.php)
[{"applications.application_id":1997,"applications.applicant_name":"Tanishq","applications.applicant_aadhaar":"987654321","applications.applicant_phone":"123456789","applications.subject":"asdnjsnadnksncdnsjnvsavasdnjsnadnksncdnsjnvsav","applications.date":"2018-07-02 09:11:47","applications.description":"asdnjsnadnksncdnsjnvsavasdnjsnadnksncdnsjnvsavasdnjsnadnksncdnsjnvsavasdnjsnadnksncdnsjnvsavasdnjsnadnksncdnsjnvsav","applications.chairperson_remark":"asdnjsnadnksncdnsjnvsavasdnjsnadnksncdnsjnvsav","applications.status":1,"officer_accounts.name_of_officer":"Chayan Bansal","applications.officer_remark":"asdnjsnadnksncdnsjnvsavasdnjsnadnksncdnsjnvsav","applications.last_update_on":"2018-07-22 09:14:25"}]
key is 8C9333343C6C4222418EDB1D7C9F84D051610526085960A1732C7C3D763FFF64EC7F5220998434C896DDA243AE777D0FB213F36B9B19F7E4A244D5C993B8DFED.
id is 1997.
NOTE: I am taking the output of statusdata.php SQL query in JSON format as in the end I am extracting it in android.
Please help me I have tried everything which other similar questions are suggesting but nothing helps
Looks more like a typo situation. You have this in login.php:
$_SESSION["key"] = ".$user_key.";
$_SESSION["id"] = ".$user_id.";
Which is tainting your original values... by adding needless dots around them. Clean that up by simply assigning as so:
$_SESSION["key"] = $user_key;
$_SESSION["id"] = $user_id;
And it should begin working better.
Side note, you are using prepare, but not using bind_param. Change your SQL prepare to the following (note the ? placeholders), and add bind_param:
$stmt = $conn->prepare("SELECT applications.application_id, applications.applicant_name, applications.applicant_aadhaar, applications.applicant_phone, applications.subject, applications.date, applications.description, applications.chairperson_remark, applications.status, officer_accounts.name_of_officer, applications.officer_remark, applications.last_update_on
FROM applications INNER JOIN officer_accounts ON applications.account_id = officer_accounts.account_id
WHERE applications.application_id = ? AND applications.application_key = ?;");
$stmt->bind_param('ss',$user_id,$user_key);
I am getting the id from another page but i am not being able to pass it to the sql query. If i define any value to $id instead of 0 then the query works but otherwise it fails.
Secondly, i would like to display the values of the array in respective input fields. I tried using
<?php
echo $result_array['institutename'][0];
?>
in the body part but it didnt work out.
My rest code is as follows:
(I know the mysql functions are deprecated but i would move on to mysqli as soon as i have solved this problem)
<?php
include 'connect.php';
$id=0;
$result_array=array();
if(isset($_REQUEST['id'])){
$id=(int)$_REQUEST['id'];
//$uid=$id;
if(!empty($id)){
$sql = "SELECT * FROM institute WHERE id =$id";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$result_array[]=$row;
}
}
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['form_institutedetails'] == 'saveinstitutedetails')
{
$mysql_table='institute';
$institutename = $_POST['institutename'];
$established = $_POST['established'];
$regno = $_POST['reg_no'];
$branch = $_POST['branch'];
$initials = $_POST['initials'];
$address=$_POST['address'];
$pin=$_POST['pin'];
$contact1=$_POST['contact1'];
$contact2=$_POST['contact2'];
$contact3=$_POST['contact3'];
$fax1=$_POST['fax1'];
$fax2=$_POST['fax2'];
$email=$_POST['email'];
$website=$_POST['website'];
if(isset($_POST['head_office'])){
$head_office=$_POST['head_office'];
}
else{
$head_office="Branch";
}
if (!preg_match("/^.+#.+\..+$/", $email))
{
$error_message = 'Email is not a valid email address. Please check and try again.';
}
if (empty($error_message))
{
$newinstitutename = mysql_real_escape_string($institutename);
$newestablished = mysql_real_escape_string($established);
$newregno = mysql_real_escape_string($regno);
$newbranch = mysql_real_escape_string($branch);
$newaddress = mysql_real_escape_string($address);
$newpin = mysql_real_escape_string($pin);
$newemail = mysql_real_escape_string($email);
$newwebsite = mysql_real_escape_string($website);
$ho = mysql_real_escape_string($head_office);
include 'connect.php';
$sql = "UPDATE `".$mysql_table."` SET `institutename`='$newinstitutename', `established`='$newestablished', `regno`='$newregno', `branch`='$newbranch', `initials`='$initials', `address`='$newaddress', `pin`='$newpin', `contact1`='$contact1', `contact2`='$contact2', `contact3`='$contact3', `fax1`='$fax1', `fax2`='$fax2', `email`='$newemail', `website`='$newwebsite', `head_office`='$ho' WHERE `id`=$id";
$result = mysql_query($sql, $db);
mysql_close($db);
$error_message='Updated Successfully!.';
}
}
?>
When you are unsure about the structure of an array, you can always do a print_r during development.
print_r($result_array);
In this case, it is an index array of associative arrays.
To access the first record's institutename (and probably the only record since it looks like you used an unique key in your query), you can use
echo $result_array[0]['institutename'];
<?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.
EDIT:
PROBLEM IS FOLLOWING:
$pageTitle cannot be used outside the function.
Here is what I got so far:
function getMetaData($table, $rows){
echo $table;
echo $rows;
$selectTitle = "select * from $table";
$getTitle = mysql_query($selectTitle);
while ($showTitle = mysql_fetch_assoc($getTitle)){
$pageTitle = $showTitle[$rows];
}
}
getMetaData('metadata', 'Pagetitle');
My output
<?php echo $pageTitle ?>
--> this is undefined
Thank you
Your function does not return any value nor does it prints any value. based on your EDIT use
global $pageTitle;
at the beginning of your function and before using the variable.
You should initialize the variable $pageTitle first like,
function getMetaData($table, $rows){
echo $table;
echo $rows;
$selectTitle = "select * from $table";
$getTitle = mysql_query($selectTitle);
$pageTitle='';
while ($showTitle = mysql_fetch_assoc($getTitle)){
$pageTitle = $showTitle[$rows];
}
return $pageTitle; // returning the variable will work here
}
echo getMetaData('metadata', 'Pagetitle');
Just TRY with mysql_free_result() like
$selectTitle = "SELECT * FROM '".$table."'";
$getTitle = mysql_query($selectTitle);
$pageTitle = '';
while ($showTitle = mysql_fetch_assoc($getTitle)){
$pageTitle = $showTitle[$rows];
}
return $pageTitle; //Return even the pageTitle.
mysql_free_result() will free all memory associated with the result.
And as per your EDIT try like :
$pageTitle = getMetaData('metadata', 'Pagetitle');
echo $pageTitle;
I want to access the data in the php array. I have tried array[0] and array['Name'] but i dont get an output. here is my code:
session_start();
$user = $_SESSION['username'];
$sql_1 = "SELECT UserID FROM users WHERE username=$user";
$result_1 = mysqli_query($sql_1);
$uID = mysqli_fetch_array($result_1);
if ($uID=NULL) {
echo 'null';
} else {
echo $uID[0];
}
Now I am not getting any output from the echo command. So what am i doing wrong here?
The Part if ($uID=NULL) is always true[UPDATED:false], because you're doing an assignment rather than a comparism (that would be if ( $uID == NULL ))