0
$sql = "SELECT * FROM product WHERE product = 'Chocolate Brownie Finger'";
$result = $connect->query($sql);
while ($row = $result->fetch_assoc()){
    $field = $row["ingredients"];
    echo '<b>'.$field.'</b>';

This is fully functioning code

I have a session variable called $_SESSION["variable"]

How do I change my code so, where is searched for "Chocolate Brownie Finger", it instead searches for $_SESSION["variable"]

user3783243
  • 5,368
  • 5
  • 22
  • 41
  • 1
    You can find an example [here](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – El_Vanja Dec 21 '20 at 14:44
  • 1
    The question you've asked would be the same as how to join a variable to a string. BUT with SQL that would open you to injections. You should use a parameterized query with prepared statement. See https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php – user3783243 Dec 21 '20 at 14:51

1 Answers1

1

According PHP documentation you can use next code:

<?php
$_SESSION["variable"] = 'cake';

$sql  = "SELECT * FROM product WHERE product = ?";
$stmt = mysqli_prepare($mysqli, $sql);
    
/* bind parameters for markers */
$stmt->bind_param("s", $_SESSION["variable"]);

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

/* instead of bind_result: */
$result = $stmt->get_result();

/* now you can fetch the results into an array - NICE */
while ($row = $result->fetch_assoc()) {

    // use your $myrow array as you would with any other fetch
    printf("%s ingredients %s\n", $_SESSION["variable"], $row['ingredients']);

}

and here you can test the code

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39