skip to Main Content

I’ve set a local server using PHPMyAdmin, and I’m presenting some dynamic data that is stored in that server using some PHP, HTML and SQL. The problem is that whenever I pass a variable that is stored using $variable = mysqli_real_escape_string($conn, $_GET["variable"]); and then I use that variable in a SQL query similar to this one $sql = 'SELECT * FROM assets WHERE variable="$variable";. The array that is generated is empty.

When I do a print_r($variable);, I get the variable that the code is expecting, so I’m not sure why the query sends an empty array. Then, when I hardcode the SQL query with the value of print_r($variable), the correct array is obtained from the query.

Code in PHP that is not working

$variable = mysqli_real_escape_string($conn, $_GET["variable"]);

  print_r($_GET["location"]);

  // make SQL
  $sql = 'SELECT * FROM assets WHERE variable="$variable"';

Where $conn = mysql_connect('localhost', 'user', 'password', 'table');
The connection is correct though

then for example when I hardcode it using the result I get from

print_r($_GET["variable"]); prints N1 on the screen

This PHP is working, but it won’t be dynamic

 $sql = 'SELECT * FROM assets WHERE variable="N1';

I’m expecting to see all the results were the field variable = to a $_GET["variable"], where $_GET["variable"] is stored in $variable, but all I’m getting is an empty string.

2

Answers


  1. You could use a prepared statement and binding param (for this you don’t need the real string escape id done by the msqli prepared and binding)

    $conn= new mysqli('localhost', 'user', 'password', 'your_db');
    $myVar =  $_GET["location"]; 
    $sql = 'SELECT * FROM assets WHERE variable=?';
    
    $query = $conn->prepare( $sql);
    $query->bind_param('s',$myVar);
    $result = $query->execute();
    
    Login or Signup to reply.
  2. Try this code may be solve issues.

       $conn= new mysqli("localhost","my_user", "my_password", "world");
       $sql = 'SELECT * FROM assets WHERE variable='.$_POST["variable"];
       mysqli_query($conn,$sql);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search