-1

So I am creating a shopping cart and want to display the cart based upon the user that is logged in. Currently my cart datable has a user, item_name and qty column. I am trying to output their data WHERE username = session variable. I am getting the error below the code. I believe it's the way I am typing the php variable but cannot get it right. What am I missing?

<?php
session_start();
echo "Welcome Back: <input type='text' id='user' value='" . $_SESSION["user"] . "' disabled><br>";

    $conn = new mysqli("localhost", "root", "", "assessment");
    $sql = "SELECT *
            FROM shopping_cart
            WHERE username = ' . $_SESSION["user"] . '";
    $result = $conn->query($sql);
?>

Parse error: syntax error, unexpected '"', expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in D:\xampp\htdocs\task7\cartDisplay.php on line 13

  • Your single and double quotes are unbalanced in the line which defines the sql. It should be $sql = "SELECT * FROM shopping_cart WHERE username = '" . $_SESSION["user"] . "'"; – Julian Mar 16 '21 at 10:39

1 Answers1

2

You're using periods to append your session variable, but you're not closing your strings on either side with quotation marks ".

$sql = "SELECT *
        FROM shopping_cart
        WHERE username = '" . $_SESSION["user"] . "'";

With that said, you should use prepared statements. You're so close already.

$stmt = $conn->prepare("SELECT * FROM shopping_cart WHERE username=?");
$stmt->bind_param("s", $_SESSION["user"]);
$stmt->execute();
$result = $stmt->getResult();
while($row = $result->fetchArray(MYSQLI_NUM))
{

}
Liftoff
  • 23,852
  • 11
  • 61
  • 117