How can I display the column names of a table using PHP? - php

I have been researching for days now. I always get something like this (this is what I think is the best answer):
SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename'
AND `TABLE_NAME`='yourtablename';
Yeah this one runs perfectly in SQL, but I still have no idea how I will create a PHP script to show it the same way as it does in SQL. Can anyone give me a code?
I'm really confused right now. Please help..

without PDO:
$sql = "SHOW FIELDS FROM users;";
$result_sql = mysql_query($sql) or die ("Error!\n");
while ($row = mysql_fetch_array($result_sql)) {
echo $row['Field']."<br>\n";
}

Apparently you need to retrieve data from a mysql table and then do stuff with it in php. There are several ways to do this, here is my favorite:
<?php
$query="SELECT `COLUMN_NAME`
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename'
AND `TABLE_NAME`='yourtablename'";
$result=mysql_query($query); //This will store the whole result table in $result
$rows=array(); //Initialize array
while($row=mysql_fetch_object($result)) $rows[]=(object) $row; //Store each row of the result table in the array $rows
//Now you can access, for example, the third row and second column by saying:
echo $rows[2]->name_of_second_column
?>
Also refer to this tutorial. on how to retrieve data from a database and manipulate it afterwards.

you can do this by in mysql mysql_field_name()
Use of mysql_* is discouraged so use either pdo or mysqli
with them you can do this by
mysqli_fetch_field_direct() //for mysqli
PDOStatement::getColumnMeta() //for pdo
for example after OP comment
$sql = "SELECT * from Person";
$result = mysql_query($sql,$con);
$name = mysql_field_name($result, 0);
explanation how to use the mysql_field_name()
Syntex
mysql_field_name(data,fieldOffset)
+------------+------------------------------------------------------------------+
| data | Required. Specifies which data pointer to use. The data |
| | pointer is the result from the mysql_query() function |
+------------+------------------------------------------------------------------+
|fieldOffset |Required. Specifies which field to start returning. 0 indicates |
| |the first field |
+------------+------------------------------------------------------------------+
good read
PDO Tutorial for MySQL Developers

Related

passing parameter to select statement from url

I have a database with a table which has two columns, lets say aa_id and bb_id - each of the the columns is a foreign key relating to another table and both columns are making a composite key for this particular table. there are several rows containing either the same aa_id and different bb_id or the same bb_id and different aa_id.
using pdo I want to extract the rows of the same - let's say - aa_id and I want to do this passing the parameter value in url. so the result of the select statement should be several rows and they should be saved as - for example - an array.
I have tried to do this with following code:
$sql = sprintf("select aa_id, bb_id from a_table where aa_id=:aa_id");
$res = $db->query($sql);
$rows = $res->fetch(PDO::FETCH_ASSOC);
foreach($rows as $key=>$value)
{
echo $key . " - " . $value . "</br>";
}
And it give no result.
I does work if I state the value of aa_id in the query like this
$sql = sprintf("select aa_id, bb_id from a_table where aa_id=191919");
, but it extracts no data if I put the value in url.
I am not really sure what to search for in the web because I don't know what's the notation called (if it is). If somebody could tell me what may be wrong with the code or give me directions to what I should look for in the web among tutorials or documentation I will be grateful. Perhaps somebody could recommend a good source of knowledge about mysql, php and pdo... Thanks in advance.
Well yeah, :indicator doesn't just automatically load in $_GET['indicator'], you need to manually bind it.
Assuming the URL ends with, ?aa_id=191919, your code might look something like this:
$sql = "select aa_id, bb_id from a_table where aa_id=:aa_id";
$res = $db->prepare($sql);
$res->bindValue(':aa_id', $_GET['aa_id'], PDO::PARAM_INT);
$res->execute();
$rows = $res->fetch(PDO::FETCH_ASSOC);
while($row=$res->fetch(PDO::FETCH_ASSOC))
{
print_r($row);
}

mysql and php - dont know how to select and echo

My question is.... i have a table with 2 columns and 24 rows.
first column is only id and it goes from 1 to 24 and second column is some text in each row and follows id.
i don't know how to SELECT text from each row separated by id in first column and echo it.
I am using xampp - mysql and working in php. TY
i tried something like this and than i used variable $row to call row 0. but i think thats not right way.
$nap_query = "SELECT napomena FROM napomena";
$nap_result = mysql_query($nap_query) or die (mysql_error());
$row = mysql_fetch_row($nap_result);
You need to look at the php mysql_fetch_array documentation: http://php.net/manual/en/function.mysql-fetch-array.php
As the comments suggest mysql_fetch_row doesn't work for multiple rows.
So you can do that
while($row = mysql_fetch_array($nap_result))
echo $row['napomena'];
Aditions
It's best not to use mysql anymore and use mysqli or prefebly PDO in order to handle database connections. Read PDO and mysqli documentation here.
If you want to get only one row result
$rownum=0; //zero or something
echo mysql_result($nap_result, $rownum, "napomena");
Multi values use mysql_fetch_array
while($row=mysql_fetch_array($nap_result)){
echo $row['napomena'];
}
$nap_query = "SELECT field FROM table";
$nap_result = mysql_query($nap_query) or die (mysql_error());
while($row = mysql_fetch_row($nap_result))
echo $row['field'].'<br/>';
This will result like this
resultA
resultB
resultC
etc
Just like #punitha said, it's better to use PDO

Get row values as column names using Codeigniter and mysql

im using codeigniter and mysql as db. i know might can be solved with mysql query, but if anyone can solve with codeigniter query it will be awesome, otherwise normal PHP mysql query can work also.
I have Table with 3 columns, Well it have many feilds but i have shown here 4 enteries, i didnt wanted to make a table with many columns but only 1 row of data. so instead i went for this style of table as someone suggested me on this website.
Problem is i never worked with this kind of table.
SettingsID SettingsKey SettingsValue
----------------------------------------------------------------------
1 | facebookLink | facebook.com
2 | twitterLink | twitter.com
3 | youtubeLink | youtube.com
4 | googlePlusLink | googleplus.com
Now i want to run a query that should return me rows in to columns. i searched over net and found some solutions but i am not good with this new queries.
I suppose this guy had same kind of problem like i have but in his case he has same value repeated in column, where my SettingsKey has all the values unique.
Here is the link to similar kind of question :
mysql select dynamic row values as column names, another column as value
i cant understand his query and that query i am not sure if is any use of me.
Please can anyone help me build a query to return row values of SettingsKey as columns.
This should work:
<?php
$db = new PDO('mysql:host=localhost;dbname=DBNAME;charset=utf8', USERNAME, PASSWORD);
$stmt = $db->query("SELECT SettingsKey, SettingsValue FROM Settings");
$links = array();
while($row = $stmt->fetch()) {
$links[$row['SettingsKey']] = $row['SettingsValue'];
}
$db = null;
This code queries this table and for each row the SettingsKey and the SettingsValue will be shown.
Now you can get the facebookLink like this:
echo $links['facebookLink'];
Hope this helps.
$sql = "
SELECT SettingsKey, SettingsValue
FROM Settings
";
$q = $this->db->query($sql);
return $q->result_array();
Go to your controller
$data['settings'] = $this->model_selection->your_function();
$this->load->view('example', $data);
And lasty on your view
<?php if(!empty($settings)): ?>
<?php foreach($settings as $k => $v): ?>
//print your staff in here mix with html and go crazy
<?php endforeach; ?>
<?php endif ?>

How to retrieve data from a single field in mysql?

I'm trying to retrieve an email address from a table in MySql using $keyword (keyword can be anything in the question field) to identify the row. I am successful in finding the row I need with the query below but it returns the entire row, how does one pull just the email out of the row and store it as $email?
Query:
$result = mysql_query("SELECT * FROM ask WHERE date = '$keyword' order by ask_id")
or die(mysql_error());
Table:
| ask_id | store | fname | lname | email | phone | city| state | zip_code |question | sku | date |
Just select only the column you need email instead of them all *
$result = mysql_query("SELECT email FROM ask WHERE date = '$keyword' order by ask_id")
Note that mysql_* function are deprecated, better to switch to either mysqli or PDO. So you will be able to use prepared statements and you will avoid any risk of mysql injection, learn more here How can I prevent SQL injection in PHP?
SELECT `email` FROM ask WHERE date = '$keyword' order by ask_id
Use code above instead. SELECT * FROM... in your mysql statement means select everything.
$result = mysql_query("SELECT columnName AS email FROM ask WHERE date = '" . $keyword . "' ORDER BY ask_id");
while($row = mysql_fetch_assoc($result)){
$row['email']; // Here Do Anything With Email...
}
First off, the obligatory mysql_* commands are deprecated, don't use them, kittens will die and your dog will get shot etc. For more on that, please see this question.
If you only want to retrieve one column from your MySQL database you can do so by specifying the column after your SELECT, instead of an asterisk. So you would have a query as follows:
SELECT email FROM ask WHERE date = '$keyword' order by ask_id
You can use this as follows in PHP code:
$result = mysql_query("SELECT email FROM ask WHERE date = '$keyword' order by ask_id")
or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
var_dump($row);
}
To reiterate, you should not be using the mysql_* functions. There are superior replacements available, as detailed in the question referenced above.

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.
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.
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];
}
In PHP you can execute query using $res = mysql_fetch_row($query). then you can fetch second column by $res[1];
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.

Categories