1

I'm trying to get the first 3 occurrences (rows) in a MySQL table (column specified) that start with a user-provided string:

$con = mysqli_connect($db_host, $db_user, $db_password, $db_name);
$user_input = $_POST['user_input'];

$result = mysqli_query($con, "SELECT * FROM airports WHERE airport_name LIKE '$user_input%' LIMIT 3") or die();  
$row = mysqli_fetch_array($result);

$airport_suggestion1 = $row[1];
$airport_suggestion2 = $row[2];
$airport_suggestion3 = $row[3];

For some reason this will only return the first row found, $airport_suggestion2 and $airport_suggestion3 are always empty even when they shouldn't be. What am I doing wrong here?

  • Maybe only one row matches. – Gordon Linoff Nov 14 '18 at 04:40
  • 2
    Loop `mysqli_fetch_array`, it only returns one row without a loop....You also should not be putting user input directly into SQL. Parameterizing your query is best practice. – user3783243 Nov 14 '18 at 04:42
  • Right, I wouldn't run this in a live code without a mysqli_real_escape() on all user inputs before running SQL, I just didn't include it in the code for brevity. – gonna_take_sometime Nov 14 '18 at 08:43
  • @gonna_take_sometime Even [`real_escape_string`](https://stackoverflow.com/a/12118602/2469308) cannot secure it completely. For more robustness, please use [Prepared Statements](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Madhur Bhaiya Nov 14 '18 at 11:52

0 Answers0