在SQL查询中使用表名时如何访问PDO结果?

问题描述:

I recently had to change an SQL query to query multiple tables and started specifying the table names with the column names.

$results = $db->query('SELECT categories.name, channels.description, channels.name FROM categories JOIN channels ON categories.id = channels.category ORDER BY RANDOM() LIMIT 4');

However now I have a problem that the rest of the code doesn't work even though I updated it to use the table names with the column names.

<h3><?php echo $row['channels.name']; ?></h3>

How do I specify table name with column names in this way? The SQL query itself is fine but I don't understand how to echo the results?

我最近不得不更改SQL查询以查询多个表,并开始使用列名指定表名。 / p>

  $ results = $ db-&gt; query('SELECT categories.name,channels.description,channels.name FROM categories JOIN channels ON categories.id = channels.category ORDER BY  RANDOM()LIMIT 4'); 
  code>  pre> 
 
 

但是现在我有一个问题,即使我更新它以使用表格,其余代码也不起作用 具有列名的名称。 p>

 &lt; h3&gt;&lt;?php echo $ row ['channels.name'];  ?&gt;&lt; / h3&gt; 
  code>  pre> 
 
 

如何以这种方式指定包含列名的表名? SQL查询本身很好,但我不明白如何 echo code>结果? p> div>

The table name is unlikely to carry through to the output. Instead, alter the name of one of the columns with an alias, such as:

$results = $db->query('SELECT categories.name as cat_name, channels.description, channels.name FROM categories JOIN channels ON categories.id = channels.category ORDER BY RANDOM() LIMIT 4');

Then when referencing the columns, you refer to

<h3><?php echo $row['name']; ?></h3>
<h3><?php echo $row['cat_name']; ?></h3>

Etcetera.

The documentation says:

The name of a result column is the value of the "AS" clause for that column, if there is an AS clause. If there is no AS clause then the name of the column is unspecified and may change from one release of SQLite to the next.

So if you want to access result columns by name, you have to use AS.