phpmysqliprepared-statement

Having trouble executing a SELECT query in a prepared statement


Ive followed a bunch of different examples regarding using a SELECT in a prepared statement, but nothing is returned. EDIT I have changed my code a bit to look like this:

$date1 = 2012-01-01;
$date2 = 2012-01-31;
$sql_con = new mysqli('db', 'username', 'password', 'database');

if($stmt = $sql_con->prepare("SELECT eventLogID FROM Country WHERE countryCode=? AND date BETWEEN ? AND ?")){

   $stmt->bind_param("sss", $country_code, $date1,$date2); 

    $stmt->execute();

  $i=0;
  while ($stmt->fetch()){
  $stmt->bind_result($row[$i]);
  $i++;
  }

  $stmt->close();
$sql_con->close();

Now all the desired entries, except for the first, are added to $row[]. Why isnt the first entry being added? Thanks in advance!


Solution

  • Just use get_result (instead of bind_result)

    // parameters
    $date1 = '2012-01-01';
    $date2 = '2012-01-31';
    $country_code = 'whatever';
    
    // Connect to DB
    $db = new mysqli('db', 'username', 'password', 'database');
    
    // The query we want to execute
    $sql = "SELECT eventLogID FROM Country WHERE countryCode = ? AND date BETWEEN ? AND ?";
    
    $stmt = $db->prepare($sql);
    $stmt->bind_param("sss", $country_code, $date1, $date2); 
    $stmt->execute(); 
    $result = $stmt->bind_result();
    
    // get results into array
    $logIds = $result->fetch_all(MYSQLI_ASSOC);
      
    // Do something with the results
    print_r($logIds);