gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:44:33 25 4
gpt4 key购买 nike

我是使用 php 的初学者,我想使用当前登录用户的用户名发送查询。

我应该从哪里开始 session ?在登录php文件中?我怎样才能将变量传递给其他 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);
?>

关于php - 如何在 php 中获取当前用户的用户名并在 mysql 查询中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50020143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com