phpmysqlmysqliezsql

Using a $_GET variable for id in mysqli


I would like to use a GET variable from the URL and use it in a MySQL select statement as an id, then echo the results out on the page. I was able to echo out the $_GET variable by itself, but I am not able to use it as a variable in a query.Why is the code below not working?

<?php
require_once(dirname(__FILE__) . '/core/config.php');
include_once "shared/ez_sql_core.php";
include_once "ez_sql_mysqli.php";
$db = new ezSQL_mysqli(DB_USER,DB_PASSWORD,DB_USER,'localhost');

$client = (int)mysqli_real_escape_string($_GET['client']);

$results = $db->get_results("SELECT * FROM clients WHERE id=" . $client.  ";");

foreach ( $results as $data ){ 
    echo $data->name; 
  }

?>

Solution

  • You are using that ezSQL thing wrong way.

    Here is how it have to be used:

    $client = $db->escape($_GET['client']);
    $results = $db->get_results("SELECT * FROM clients WHERE id='$client'");
    

    However, I'd strongly recommend to get rid of this ridiculously insecure solution and use PDO instead:

    $results = $pdo->prepare("SELECT * FROM clients WHERE id=?");
    $results->execute([$_GET['client']]);
    foreach ( $results as $data ){ 
        echo $data->name; 
    }