1

I have a PHP file that will run a SQL select statement and echo out the results. I am trying to be able to set individual columns to specific variables. Is this possible?

IE: based on the code below, how could I create a variable called $FirstName and set it equal to the value of the single record in the column firstname that is returned?

Thank you

   $sql = "SELECT * FROM Employees where Employee_ID = 1";
  $stmt = sqlsrv_query( $trpConn, $sql );
  if( $stmt === false) {
    die( print_r( sqlsrv_errors(), true) );
  }

  while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
    echo $row['FirstName'].", ".$row['LastName']."<br />";
  } 
4
  • What's wrong with the array? You could use extract() but that will only lead to problems as you can overwrite existing variables, etc. Even the php manual recommends against using it. Commented Apr 18, 2016 at 14:29
  • 1
    If you want to store the value in a variable just make $FirstName = $row['FirstName']; before your echo statement. Commented Apr 18, 2016 at 14:31
  • Thank you @Error404 - too simple but that is exactly what I was trying to do but I was putting it in the wrong location before. I appreciate the help! Commented Apr 18, 2016 at 14:34
  • @AAA You are welcome :). Do not doubt to ask if you have more questions and your question it is well-defined and you can provide some code to check it. Happy coding :) Commented Apr 18, 2016 at 14:36

1 Answer 1

2

I put it as a comment but I provide it as an answer to help if someone has the same error as @AAA. If you want to store your value you just have to put it as follows:

$FirstName = $row['FirstName'];

but you have to aware that you have access to that $row (or that you are accessing in the right way to that content) before trying to assign it to a variable, in this case, inside the loop.

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.