简体   繁体   中英

PHP: How do I select from MySQL table by column position rather than by column name?

I have a table that has multiple columns, the column names can be changed in the future, and rather than my script select from the columns by their name (since that info can change), is there a way to select by column position?

For example, I want to select the second column in the table... can I do that easily?

I understand the reasons not to do this, but I still want to.

Easy solution? Just SELECT * FROM table , fetch with $row = mysql_fetch_row() and read from $row[1] , it will be the content of the "second column" in order (as it starts in 0).

If you want it a little bit more professional and select only whats needed, you can get the second column name from the INFORMATION_SCHEMA using a query like this:

SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'your database schema' AND TABLE_NAME = 'the wanted table name' AND ORDINAL_POSITION = 2;

But if you really want to do this the right way then know where you put your nose. If the table structure is changed and your code needs adaptations because of it, so be it. This is how it should be done. If you leave it "working" but relying in potentially wrong information it may cause much bigger problems to you later.

In PHP you can execute query using $res = mysql_fetch_row($query) . then you can fetch second column by $res[1] ;

The following three exampels shows you how to print the 3rd column using MySQL, MySQLi and PDO.

MySQL

while ($row = mysql_fetch_array($query)) {
  print $row[2];
}

MySQLi

$sth->execute();
$sth->bind_result($var1, $var2, $var3);
while ($sth->fetch()) {
  print $var3;
}

PDO

$sth->execute();
while ($row = $sth->fetchAll()) {
  print $row[2];
}

This is such a bad idea that I almost don't want to give you a solution, but it is possible. MySQL has a database named information_schema that stores DDL data that you can query. What you are after would be COLUMNS.ORDINAL_POSITION .

SELECT COLUMN_NAME FROM information_schema.COLUMNS
WHERE TABLE_NAME = ? AND ORDINAL_POSITION = ?

This will give you the name of the nth column, which you can use in the field list of a subsequent query. It would not make sense to do this in a single query.

I have had such problem many days ago. But I found the solution:

  $conn = new mysqli("localhost", "root", "", "Mybase");
  $result = $conn->query("SELECT * FROM imagesbase");
  $outp = "";
  while($rs = $result->fetch_array(MYSQLI_BOTH)) {`
     $outp .= "Picture: ".$rs[0]." ".$rs["ImgPathName"]."";`
  }
  $conn->close();
  echo "$outp";

This code may be changed by column number or column name. MYSQLI_BOTH , MYSQLI_NUM or MYSQLI_ASSOC are used for this.

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