0

I have to run mysql query in a for loop like this

$date_start = '2017-01-01';
$date_end = '2017-01-10';
while ($date_start < $date_end){
   $sql ("SELECT id FROM mytable WHERE mydate = '$data_start'"); [<--edit]
   $result = $db->query($sql);
   $f = $result->fetch();
   echo 'result is : '.$f['id'];
   $date_start = date('Y-m-d', strtotime($date_start. ' + 1 days'));
}

ID result was always related to first $date_start, then first sql query...

How to wait php for mysql to finish query?

EDIT.:

Ok, there was a mistake when I create the loop here, but is a distraction! It's not a copy/paste

After this I wrote

ID result was always related to first $date_start, then first sql query...

This means that is not a code problem, the loop works, else I have a php error!

I will try with MYSQL error reporting

2
  • Simply look at the highlighting colour. There is an obvious string literal issue in this code Commented Feb 9, 2017 at 21:52
  • 3
    PHP will always "wait" for a query to finish before it continues executing the script. That is how PHP works, nothing you have to take care of. Commented Feb 9, 2017 at 21:55

1 Answer 1

3

You have a string literal that is not closed properly, and the assignment of the query to the variable $sql is incorrect. Therefore the script is crashing

// while testing specially if you are developing on a live server
// that will have error reporting to the screen turned off
// add these 4 lines so you see your errors on the browser page
ini_set('display_errors', 1); 
ini_set('log_errors',1); 
error_reporting(E_ALL); 
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$date_start = '2017-01-01';
$date_end = '2017-01-10';
while ($date_start < $date_end){
    $sql = "SELECT id FROM mytable WHERE mydate = '$data_start'";
    // --new character added to close the literal------------->^
    // () removed
    $result = $db->query($sql);
    // check for errors
    if ( !$result) {
        echo $result->error;
        exit;
    }
    $f = $result->fetch();
    echo 'result is : '.$f['id'];
    $date_start = date('Y-m-d', strtotime($date_start. ' + 1 days'));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.