1

I'm a beginner in using php, and I want to send a query using the username of the current logged in user.

Where should I start the session? in the login php file? how can i pass the variable to other php files?

<?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);
?>
Reema
  • 11
  • 3
  • `$sql = "SELECT * FROM ITEM WHERE username = '$_SESSION[username]'";` Text values must be wrapped in quotes – RiggsFolly Apr 25 '18 at 10:40
  • 2
    But that would leave your script wide open to [SQL Injection Attack](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) Use [prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) in either the `MYSQLI_` or `PDO` API's – RiggsFolly Apr 25 '18 at 10:41
  • echo what you get in `$_SESSION['username']`... – Yash Parekh Apr 25 '18 at 10:41
  • Thank you @RiggsFolly, I tried it but it is not working.. Sorry I'm new to php so the problem might be in starting the session. – Reema Apr 25 '18 at 10:57
  • Do you have any HTML code before this PHP code in the same file? – RiggsFolly Apr 25 '18 at 10:58
  • No I don't have HTML. – Reema Apr 25 '18 at 11:00
  • If you think its the session, add `if ( ! isset($_SESSION['username']) { echo 'NO SESSION VAR'; }` Then we will know what problem we are chasing – RiggsFolly Apr 25 '18 at 11:00
  • I'm sorry @RiggsFolly I'm a complete beginner but I'm designing an iOs app (Xcode) as a course project in the university .. I've done almost everything except the functionalities related to getting the current user's info .. I would be so thankful for the help. – Reema Apr 25 '18 at 11:10
  • Oh in the PHP above – RiggsFolly Apr 25 '18 at 11:11
  • I don't know how to run the php and check if "'NO SESSION VAR'" appears .. I just checked in my app simulator that the query isn't successful. @RiggsFolly – Reema Apr 25 '18 at 11:16
  • Ok try `if ( ! isset($_SESSION['username']) { echo json_encode(['error'=>'NO SESSION VAR']); exit; }` and look at the browser debugger and see what gets returned on the AJAX call – RiggsFolly Apr 25 '18 at 11:20
  • Would it be okay if you moved this discussion to chat so i can explain the problem further? I'm a new user and I'm not able to start one. @RiggsFolly – Reema Apr 25 '18 at 11:23
  • I dont think you have enough reps for chat – RiggsFolly Apr 25 '18 at 11:26

2 Answers2

1
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_node
  • 35
  • 4
  • How can i fetch the data ? I already have this code in the DbOperation class : public function getUserByUsername($username) { $stmt = $this->conn->prepare("SELECT id, email, username, name, password, friend FROM USER WHERE username = ?"); $stmt->bind_param("s", $username); $stmt->execute(); $stmt-> bind_result($id, $email, $username, $name, $password, $friend); $stmt->fetch(); $user = array(); $user['id'] = $id; $user['email'] = $email; $user['username'] = $username; .... Is this enough? @php_node – Reema Apr 25 '18 at 13:04
  • what parameters u r passing to make user logging into your system? – php_node Apr 25 '18 at 13:11
  • username and password @php_node – Reema Apr 25 '18 at 13:12
  • Is it easier if I pass the username as a variable from xcode to php? I'm trying this now but I'm a little bit confused since I'm not good at using php @php_node – Reema Apr 25 '18 at 13:14
  • what u can do is u can fetch user details from username and store that data in your app and then u can pass username as variable in every request u made to fetch user specific data. – php_node Apr 25 '18 at 13:17
  • yes I've already done that using Xcode (I've displayed the user's info as text fields) but I'm trying now to send it to php .. but I don't exactly know how. @php_node – Reema Apr 25 '18 at 13:19
  • you have to create a url which will be pointing to your php script.So when you click submit button from your app. it will call the url with the form data.example http://example.com/register?username='abc'&pass='xyz' this way have to make a call. – php_node Apr 25 '18 at 13:24
  • Is it okay if you contact me via email so I can show you the php files and tell me what I should do? Sorry for bothering but I have searched a lot without success :( @php_node – Reema Apr 25 '18 at 13:27
  • i would suggest u to use postman it is a chrome browser extension using this extension u can make api call for your testing purpose and this will also help u to understand the api follow. – php_node Apr 25 '18 at 13:31
  • Yes thanks I'm using it. Retrieving (all) and adding to the database is all fine. Just dealing with specific user is the case. Thank you so much for your help. @php_node – Reema Apr 25 '18 at 13:34
  • so when u register user store his username in your app and while fetching the data related to the user or doing anything specific to user just pass that username in your apis that's it.If your using postman and you have a api to get the data related to user u can call that api through postman and u can pass username as a parameter in your api to fetch deatils. – php_node Apr 25 '18 at 13:40
  • session wont work in case of api u have to store user's username or any unique identity to get details of a scpecific user. – php_node Apr 25 '18 at 13:42
  • Thank you so much I'll work on it. I appreciate your help. @php_node – Reema Apr 25 '18 at 13:43
  • So knowing the name in Xcode and sending it as a parameter to php is enough? – Reema Apr 25 '18 at 13:44
  • In the above code .. how can i edit it to let it accept parameters? @php_node – Reema Apr 25 '18 at 13:46
  • Thank you so much @php_node – Reema Apr 25 '18 at 13:52
  • Check answer i have edited based on your requirement. Hope this will help u. – php_node Apr 25 '18 at 13:59
0

Are you storing your login data to your IOS app? If yes, then pass your username for the query and then you might not get any problem.

  • I only know how to retrieve ALL, because I've followed this tutorial (https://codewithchris.com/iphone-app-connect-to-mysql-database/) so I don't really know how to pass a variable. And the above php accepts no variable too. @Vishalkumar – Reema Apr 25 '18 at 14:23
  • Just create your api calling string like this: `http://example.com/testfile.php?username='abc';` In xcode, then add this to your php file `$username = $_GET['username'];` `$sql = "SELECT * FROM ITEM WHERE username = $username";` it find the data of username **abc** – Vishalkumar Monpara Apr 25 '18 at 14:34
  • Thank you so much I'll try it. – Reema Apr 25 '18 at 15:23
  • I tried it with a name i typed and it worked perfectly fine! but how can i send the current user's name .. what I've done is displaying his info in a page with this code : let defaultValues = UserDefaults.standard if let username = defaultValues.string(forKey: "uusername") ... { //setting the name to label labelUserName.text = username } .. but when i wrote the same in the class i want to send the api from it says : has no member 'defaultValues' .. the controller is of type NSObject. @Vishalkumar – Reema Apr 25 '18 at 16:13
  • check it here please : https://www.dropbox.com/s/ggp5kgjribpc1gb/Screen%20Shot%202018-04-25%20at%207.29.42%20PM.png?dl=0 I think it doesn't work because it sends the variable as a string (it doesn't send what it contains). @Vishalkumar – Reema Apr 25 '18 at 16:31
  • To pass value of current user, first of all you need to save your logged in user data into realm object which will help you to store your current username to your app. Then use that that varriable in place of "abc" to pass its value. – Vishalkumar Monpara Apr 27 '18 at 10:51