0

I am attempting to retrieve plan information for all plans attached to a specific user. They are logged in and their username is saved in the session, and I know I need to use this, in combination with the MySQL WHERE statement. Here's the code I have:

<?php
$servername = "localhost";
$username = "root";
$password = "XXX";
$dbname = "name";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT plan_id, plan_name, plan_type, plan_active FROM plans WHERE user_name ='$_SESSION['user_name']'";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        echo "id: " . $row["plan_id"]. "<br>";
        echo "id: " . $row["plan_name"]. "<br>";
        echo "id: " . $row["plan_type"]. "<br>";
        echo "id: " . $row["plan_active"]. "<br>";
    }
} else {
    echo "0 results";
}

mysqli_close($conn);
?>

Notice I use $_SESSION['user_name'] in the WHERE statement. What did I do wrong? Nothing gets displayed at all.

6
  • Where are you setting $_SESSION? Commented Jan 22, 2016 at 19:10
  • A better approach to MySQL queries is to use prepared statements (documentation) and bind parameters to it. It is also much safer beacuse it denies any potential SQL injections. Commented Jan 22, 2016 at 19:10
  • 1. Use prepared statements instead; 2. Otherwise, if you are using an array element use ${varname[key]}; But an even better approach would be to use sprintf: $sql = sprintf("SELECT plan_id, plan_name, plan_type, plan_active FROM plans WHERE user_name ='%s'", $_SESSION['user_name']);... but again use prepared statements instead. Commented Jan 22, 2016 at 19:14
  • @prodigitalson 2. why? There is only one solution use prepared staments Commented Jan 22, 2016 at 19:17
  • 1
    @VeeeneX: becuase he needs the answer for general purpouses. He obviously doesnt know the syntax to use and array element in string. In this case its a line of SQL, that should indeed be used as a param to a statement. However, he still needs to know generally why its not working because he could just as simply be trying to ouput "My name is '$_SESSION['name']' and Im new to PHP." to screen. Had i actuall posted an answer i would have first mentioned this, then gone over string concatenation, then addressed the issue with the db sepcific stuff by giving an example using prepared statements.. Commented Jan 22, 2016 at 19:28

3 Answers 3

1

You aren't properly passing the $_SESSION['user_name'] variable in the query.

Try this :-

Replace :-

$sql = "SELECT plan_id, plan_name, plan_type, plan_active FROM plans WHERE user_name ='$_SESSION['user_name']'";

with :-

$sql = "SELECT plan_id, plan_name, plan_type, plan_active FROM plans WHERE user_name ='" . $_SESSION['user_name'] . "'";

I'd suggest you to use prepared statements. You won't make these type of errors then.

Sign up to request clarification or add additional context in comments.

7 Comments

@VeeeneX Any reasons ?
Because this bad practise because of mysql injection.
@VeeeneX the MySQL injection is an issue but that issue does not relate to Akshay's answer of properly escaping variables inside strings.
@Martin Yes, it's related we don't know how SESSION["user_name"] is set
sorry @VeeeneX but it these two points are not equal. Yes, there is a factor of possible SQL injection in the current layout, but the answer Akshay gives does not need to address that, and does not mention or address that as it is outside the core scope of this Question .Your comment of Never. Ever. Do this sounds very much like you're saying never ever close a string and concatenate a variable into the string in the form that akshay has done in his answer. If the variable is first cleaned then the answer Akshay gives is still absolutely valid.
|
1

$_SESSION['user_name'] has the same type of quotes surrounding it and within it. I would set $username = $_SESSION['user_name'] outside of the sql query and then put $username in the sql query.

Comments

0

There is problem with quotes as @kloddant mentioned. This is how a correct query should look like:

SELECT plan_id, plan_name, plan_type, plan_active FROM plans WHERE user_name = ?

And partial code looks like this:

/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT plan_id, plan_name, plan_type, plan_active FROM plans WHERE user_name = ?")) {

    /* bind parameters for markers */
    $stmt->bind_param("s", $SESSION['user_name']);

    /* execute query */
    $stmt->execute();

    /* bind result variables */
    $stmt->bind_result($result);


    /* Play with result */


    /* close statement */
    $stmt->close();
}

A few tips; If you have large database of users, index your user_name field or use id instead of user_name. This can make your query faster.

2 Comments

Is your full code supposed to replace all of what I have written in the question or just a part of it?
@MMultiLinguist No. It's only partial code :), sorry

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.