mysql check columns? - php

Is there a way to check what columns are there in mysql syntax?
For example,
$dbh = $db->query("SELECT * FROM table");
while($row = $dbh->fetchAll(PDO::FETCH_ASSOC))
{
$row['somecolumn'];
}
For instance, if there is or not somecolumn, I would like to find out if there is a way that will display a list of ALL the columns in the syntax I'm looking for in table
This way in the future, I'll be able to check if there is $row['fr'] or $row['food'] that can work.
Thanks

You could simply check whether $row contains the key you need.
The PHP function array_key_exists will tell you whether $row contains the key you want. For instance, array_key_exists("fr", $row) will return true if $row contains an fr key.
If you want to see all the keys (i.e. all the columns), simply use array_keys; for example : array_keys($row) will give you all the keys in $row.
Alternatively, if you don't mind another SQL call, you can use SELECT column_name FROM information_schema.columns WHERE table_name='your_table' as xdazz's answer mentions.

You can use the INFORMATION_SCHEMA to do this, or DESCRIBE.
Take a look at the information_schema columns documentation, or see the describe syntax.

You could use the sql below to select cloumn names for one table.
SELECT
column_name
FROM
information_schema.columns
WHERE
table_name='your_table';

Related

Is there anyway to tell the datatype in a postgres array?

I am using a Postgres 9.4 database and have PHP as my front end.
A general query I may run would look like this:
PHP :
$query = "select * from some_table";
pg_prepare($connection,"some_query",$query);
$result = pg_execute($connection,"some_query",array());
while ($row = pg_fetch_array($result,null,PGSQL_ASSOC)) {
echo $row['some_field'];
echo $row['some_field_1'];
echo $row['some_field_2'];
}
I am running into a front-end that requires to know the datatype of the column that spits out - specifically I need to know when the echo'd database field is a timestamp column.
Obviously I can tell integers and string, however timestamp is a bit of a different thing.
I suppose I could see if strtotime() returns false, however that seems a little dirty to me.
So my question is:
Is there a PHP built-in function that can return a multi-dimensional array of the database row with not only $key=>$value pair but also the datatype?
Any help on this would be appreciated - thank you!
You can query from information_schema.columns and fetch just like any other query:
SELECT column_name, data_type
FROM information_schema.columns
WHERE table_name='some_table'
Or after your query use pg_field_type():
$type = pg_field_type($result, 0);
But you need to know the position of the column in the result so you should (best practice anyway) list the columns. For the above case using 0 would give the type of col1 in the query below::
SELECT col1, col2, col3 FROM some_table

Mysql PDO : get row with "dynamic" fields in query

I have a query with a dynamic field, how do I access this field without knowing its name?
define('FIELD_NAME',"name");
$stmt = $connexion->query('SELECT '.FIELD_NAME.' from mytable);
while ($rs=$stmt->fetch(PDO::FETCH_OBJ)){
echo $rs->FIELD_NAME; // DOESN'T WORK
echo $rs->name; // WORK
}
Wrap the constant in {} to create dynamic variables.
echo $rs->{FIELD_NAME};
You can see some example from the documentation.
Curly braces may also be used, to clearly delimit the property name.
Demo: http://3v4l.org/sgvV4
There are lot of approaches to this. If it's not important that the variable name match the column_name, you could assign an alias to the expression in the SELECT statement
For example:
SELECT whateverexpression AS mycol FROM mytable LIMIT 1;
Then, you'd "know" the name of the variable in the object is $mycol
echo $rs->mycol;
I'm thinking this approach might be good in the more general case, when you're dealing with tables that have column names that were assigned by syphilitic idiot developers who had a good reason to
CREATE TABLE t (`Hey!$I (can)^name.\my->column Wh#tever` INT);
INSERT INTO t VALUES (42);
SELECT `Hey!$I (can)^name.\my->column Wh#tever` FROM t;
Obviously, there are lots of other approaches, like avoiding PDO::FETCH_OBJ and using PDO::FETCH_NUM instead. If you want to stick with PDO::FETCH_OBJ, I'm thinking assigning an alias would be workable.
Retrieving the metadata from the resultset is an approach I would consider, if getColumnMeta wasn't still experimental.
define('FIELD_NAME',"name");
$stmt = $connexion->query('SELECT '.FIELD_NAME.' from mytable');
while ($rs=$stmt->fetch(PDO::FETCH_NUM)){
echo $rs[0];
}
Using this approach, if FIELD_NAME is defined to something like *, you will still be able to get the first column.
If you're only trying to get a single value from each row, you can use PDOStatement::fetchColumn()
define('FIELD_NAME',"name");
$stmt = $connexion->query('SELECT '.FIELD_NAME.' from mytable');
while ($col = $stmt->fetchColumn()) {
echo $col;
}
Also note, you were missing a '.

PHP MySQL While loop for SELECT from two tables?

Hi there i am working on PHP code that is selecting columns from two tables.
Here is my code:
$result2 = mysql_query("SELECT *
FROM `videos`, `m_subedvids`
WHERE `videos.approved`='yes' AND
`videos.user_id`='$subedFOR'
ORDER BY `videos.indexer`
DESC LIMIT $newVID");
while($row2 = mysql_fetch_array($result2))
{
$indexer = addslashes($row2['videos.indexer']);
$title_seo = addslashes($row2['videos.title_seo']);
$video_id = addslashes($row2['videos.video_id']);
$title = addslashes($row2['videos.title']);
$number_of_views = addslashes($row2['videos.number_of_views']);
$video_length = addslashes($row2['videos.video_length']);
}
When i try to print $indexer with echo $indexer; it's not giving me any results.
Where is my mistake in this code?
It seems to me like the key 'indexer' isn't in your results. It's hard to tell, since you haven't listed a definition for your table and you're using SELECT * so we can't see the names.
It makes the program easier to read later, if instead of SELECT *..., you use SELECT col1, col2, .... Yes, SELECT * will save you some typing right now, but you'll lose that time later when you or anyone else who works on your code has to check the table definition every time they work with that line of code.
So, try changing your query to explicitly select the columns you use. If it's an invalid column you'll get an error right away rather than this silent failure you're getting now, and you'll thank yourself later as well.
So long as videos.indexer is a unique field name among all tables used in the query you can change
$indexer = addslashes($row2['videos.indexer']);
to
$indexer = addslashes($row2['indexer']);
You don't need to (or can not) use the table name when referring to the result.

MYSQL Select rows in PHP by name

I have the following code and it only works when I specify the column number!
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
echo($row[0]);
}
Not when I use the name though
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
echo($row['name']);
}
Is there something that needs setting on the MYSQL box?
You might want to try print_r( $row ) for debugging so you see which column names are actually set in the resultset. Getting the associative names doesn't need to be configured in some way, but the index names need to exactly represent the column names in the database result.
mysql_fetch_array, according to the documentation, fetches the result row as an numeric array or as an associative array, depending on the second parameter. By default, this is MYSQL_BOTH, so you can access via both means.
It seems like the problem may like with your query, specifically the actual name of the column in your SELECT statement. Without seeing more of your query, I can suggest adding AS name to the first column to ensure it is the actual retrieved column name. print_r will print the array for further debugging.

PHP: MySQL Query with fieldname in a var

Little question: With the following code...
<?php
$statement = "SELECT * FROM TABLE";
$query_unfetched = mysql_query($statement);
$query_num = mysql_num_rows($query_unfetched);
if ($query_num !== 1) {
exit;
}
$query_fetched = mysql_fetch_object($query_unfetched);
$fielname = "ID";
echo $query_fetched->$fiedname;
?>
With this code, there is no output, because PHP somehow does not check that in $fieldname is an existing name of a field in the selected Table.
Why doesn't it work, have I made a mistake? Or are there any other ways to select a field whose name is saved in a var?
Thanks for the help!
Instead of using mysql_fetch_object, you could use mysql_fetch_assoc. It will return the result as an array, after which you can simply use your variable as a key.
I'd suggest using var_dump on the $query_fetched. Some OS's and DB's will return different capitalizations. Oracle, for one, will always return the column names as capital. I've seen MySQL only return lower in one circumstance.
You can also use the fetch_assoc as suggested by Cpt. eMco and that will give you warnings if the array key is not set. (Remember to turn warnings off in production though).
(I do need to put in an obligatory plug for the PDO classes. I find them far more intuitive and clearer.)

Categories