简体   繁体   中英

PHP script only returns first row of SELECT statement

I have a php script to run mssql queries. When I run a query like, "SELECT first_name, last_name, mi FROM users", all I get back is 'first_name'. Here's the script:

<?php

require '../../scripts/database_connection.php';

$query_text = $_REQUEST['query'];
$result = mssql_query($query_text);

 if (!result) {
   die("<p>Error: " . $query_text ."</p>");
}

$return_rows = true;
 if (preg_match("/^\s*(CREATE|INSERT|UPDATE|DELETE|DROP)/i,
   trim(strtoupper($query_text)))) {
  $return_rows = false;
}

if ($return_rows) {
 echo "<p>Results from your query:</p>";
 echo "<ul>";

while ($row = mssql_fetch_row($result)) {
 echo "<li>{$row[0]}</li>";
}

 echo "</ul>";
}

 else {

  if ($result) {
   echo "<p>Your query was processed successfully.</p>";
   echo "<p>$query_text</p>";
 }
}

?> 

Any suggestions?

A $row is an array with all columns of your select. Just iterate with foreach or implode it:

while ($row = mssql_fetch_row($result)) {
    echo "<li>".implode(" - ", $row)."</li>";
}

You might also want to use mssql_fetch_assoc to get the respective column names:

Did you try to access $row[1] and $row[2]?

    while ($row = mssql_fetch_row($result)) {
     echo "<li>{$row[0]} - {$row[1]} - {$row[2]}</li>";
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM