I want to select all columns from a table except one column using MySQL. I know we can select all columns using this
<?php
$query = SELECT * FROM posts;
?>
But how can I leave one specific column from the table?
I want to select all columns from a table except one column using MySQL. I know we can select all columns using this
<?php
$query = SELECT * FROM posts;
?>
But how can I leave one specific column from the table?
Instead of using *
you list all the columns on the table, leaving out the one you don't want
MySQL has an information scheme that will list all the columns in the table; you can query it and use the returned results to paste into your code so you don't have to type it out. For example, write this:
SELECT CONCAT(column_name, ',') FROM information_schema.columns WHERE table_name = 'posts' AND column_name NOT IN ('column name to exclude')
Then copy the result and paste into your code , removing the last comma
Many query tools will also help you formulate queries in this way, or show you the queries they are running and you can copy it/paste it into your code
You might find it easier to do you database access via a library that lets you treat tables like objects; I'm not a php programmer but over in C# we have things like entity framework, a library where we can make our code side Person object have 4 properties (Name, Age, Job, SSN) and tell it that it is backed by the tblPerson table (with 5 columns) and it won't download the 5th column when doing its queries. Pretty sure php will have something like that that means you don't have to spend your life writing endless SELECT blah, blah2, blah3 ...
There is a benefit in not using * sometimes, as your queries and code carry on working if someone adds a column to a table with the same name as another column. If you had:
SELECT * FROM person JOIN address ON ...
And person had a Status column that was used in the front end app, if someone later adds another Status column to address, you'll start getting two Status columns back and your front end might not treat the second correctly; it might overwrite the first or cause a crash. If you avoided using * and picked the columns you wanted by name, the system would carry on working even with the new column