FOR in php and sqlsrv

Asked

Viewed 187 times

0

I have to do a FOR in PHP, using SQLSRV. I’m using the penultimate version of PHP and not the last, because I can’t update PHP.

  • 2

    Please try to explain better the problem you have and want to solve, and if possible show the code where you have this problem and possible errors.

1 answer

3


One thing you can use is sqlsrv_fetch_array

$sql = "SELECT FirstName, LastName FROM SomeTable";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
    die( print_r( sqlsrv_errors(), true) );
}

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
          echo $row['LastName'].", ".$row['FirstName']."<br />";
}
  • Not Raphael. I need it to be via for so I can get the data individually. With while I can’t do that, you know? Ex: I need to get 5 email accounts.

  • @Gustavosevero how Raphael did picks up the data individually. Try.

  • With while you can individually have the data within your $Row variable. That will be an associative array of a row of your sql output. then you will be able inside while to do something like $Row[email]. If you want to take 5 email accounts from a table with 100 record. Use a limit in your sql. Or use a conditional break to exit the loop.

  • And how do I get $Row[email][0], $Row[email][1], $Row[email][2]...? Because I’m using a php class, phpmailer.

  • Your sql will return a table with several rows.

  • Hi Raphael, but how do I put these lines in the email? Look how I did: $mail->Addaddress($Row['email'], $Row['name']) But in each of them there must be more than one email... Will it work? .

  • Your sql will return a table with multiple rows. When you do the while, in each iteration, the $Row variable will contain one of these rows. The $Row['email'] variable will, in each Wile iteration, point to the value of the email. Until there are no more rows to run. In the example, let’s say you have 20 lines with Lastname and Firstname. while will traverse these 20 rows of sql and echo 20 times. You can put inside the loop while sending the email with phpmailer, so for each row of your sql result it will send an email.

  • It would be something like while( $Row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) { $mail->Addaddress($Row['email'], $Row['name']); }

  • That’s what I did... It looks like part of the code: 'while( $Row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) { echo htmlentities($Row['name'])." , ". $Row['email']." <br />"; $mail->Addaddress($Row['email'], $Row['name']);'

  • And what was the result?

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.