简体   繁体   English

如何在php中获取当前用户的用户名并在mysql查询中使用

[英]How to get the username of current user in php and use it in a mysql query

I'm a beginner in using php, and I want to send a query using the username of the current logged in user. 我是使用php的初学者,我想使用当前登录用户的用户名发送查询。

Where should I start the session? 我应该在哪里开始会议? in the login php file? 在登录php文件? how can i pass the variable to other php files? 如何将变量传递给其他php文件?

<?php

session_start();

//importing required script
require_once '../includes/DbOperation.php';

// Create connection
$con=mysqli_connect(" ","root"," ","myiosapp");

// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql = "SELECT * FROM ITEM WHERE username = $_SESSION['username']"; //?

// Check if there are results
if ($result = mysqli_query($con, $sql))
{
    // If so, then create a results array and a temporary one
    // to hold the data
    $resultArray = array();
    $tempArray = array();

    // Loop through each row in the result set
    while($row = $result->fetch_object())
    {
        // Add each row into our results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }

    // Finally, encode the array to JSON and output the results
    echo json_encode($resultArray);
}

// Close connections
mysqli_close($con);
?>
First u need to fetch data off logged-in user
then u have to set those data in session variable
and then u will be able to use that session variable in your query.

you need to create api 

http://example.com/testfile.php?username='abc';

then in php

<?php

//session_start();

//importing required script
require_once '../includes/DbOperation.php';

// Create connection
$con=mysqli_connect(" ","root"," ","myiosapp");

// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$username = $_GET['username'];

$sql = "SELECT * FROM ITEM WHERE username = $username"; //?

// Check if there are results
if ($result = mysqli_query($con, $sql))
{
    // If so, then create a results array and a temporary one
    // to hold the data
    $resultArray = array();
    $tempArray = array();

    // Loop through each row in the result set
    while($row = $result->fetch_object())
    {
        // Add each row into our results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }

    // Finally, encode the array to JSON and output the results
    echo json_encode($resultArray);
}

// Close connections
mysqli_close($con);
?>

Are you storing your login data to your IOS app? 您是否将登录数据存储到IOS应用程序? If yes, then pass your username for the query and then you might not get any problem. 如果是,则传递查询的用户名,然后可能不会出现任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM