How to can I get the names of my mysql table columns - php

RESOLVED
I have used the answer from alfasin, but as that gave me WAY too much information, i wrote a little script to just get the field names. As the field names apeared first, it was rather simple:
$here = array();
$SQL = "SHOW COLUMNS FROM User";
foreach($conn->query($SQL) as $row) {
$here[] = $row[0];
}
echo '<pre>';print_r($here);echo '<pre>';
This left me with the new array $here containing the column names, hope this helps someone in the future :)
Original question:
Let me clarify a bit, I have a mysql table and I'm trying to select * from it, and display the result in an html list <ol>. I can manage to grab the row data JUST FINE, but I cannot for the life of me figure out how to grab the table column names, in order to match them up with the row, respectively. this is my code that is grabbing the row data:
//get those results
$sql = "SELECT DISTINCT *
FROM User
WHERE Owner = '".$owner."'";
foreach($conn->query($sql) as $row) {
//split array in half
$hax = count($row);
$halfHax = $hax / 2;
//set up a for loop to give results
$u = 1;
for($i = 2; $i <= $halfHax; $i++){
echo $row[$u].'<br>';
$u++;
}
}
this is giving me all the result where Owner == $owner just like it should, but I would like the column names to list with those, I could hard-code it out, but more columns may be added/changed so I would rather not. Any ideas?

Try:
SHOW COLUMNS FROM mytable
http://dev.mysql.com/doc/refman/5.0/en/show-columns.html

Fetch rows as associative arrays in order to keep your column names as array keys.
Here's my suggestion:
$sql = "SELECT DISTINCT * FROM User WHERE Owner = :owner";
$sth = $conn->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':owner' => $owner);
while($row=$sth->fetch(PDO::fetch_assoc) as $row) {
//split array in half
$hax = count($row);
$halfHax = $hax / 2;
//set up a for loop to give results
foreach ($row as $key => $value) {
echo $key.'='.$value.'<br />';
}
}
To just list the column names:
array_keys($row);

Please refer to SHOW COLUMNS at the MySQL Reference if you want more information about the columns.
But I'd suggest using mysqli_fetch_assoc and then using foreach (array_expression as $key => $value) to get the column name and it's value, for each row.

Related

Separating mysql fetch array results

i have a mysql table the contains an index id, a data entry and 10 other columns called peso1, peso2, peso3...peso10. im trying to get the last 7 peso1 values for a specific id.
like:
$sql = mysql_query("SELECT * FROM table WHERE id='$id_a' ORDER BY data DESC LIMIT 0, 7");
when i try to fetch those values with mysql_fetch_array, i get all values together.
example:
while($line = mysql_fetch_array($sql)) {
echo $line['peso1'];
}
i get all peso1 values from all 7 days together. How can i get it separated?
They will appear all together because you are not separating them as you loop through them.
for example, insert a line break and you will see them on separate lines
while($line = mysql_fetch_array($sql)) {
echo $line['peso1'] ."<br />";
}
You could key it as an array like so
$myArray = array();
$i = 1;
while($line = mysql_fetch_array($sql)) {
$myArray['day'.$i] = $line['peso1'];
$i++;
}
Example use
$myArray['day1'] // returns day one value
$myArray['day2'] // returns day two value
It's not clear what you mean by "separated" so I'm going to assume you want the values as an array. Simply push each row field that you want within your while loop onto an array like this:
$arr = array();
while($line = mysql_fetch_array($sql)) {
$arr[]=$line['peso1'];
}
print_r($arr);//will show your peso1 values as individual array elements

PHP Nested Loop. How on the second loop print items according to the id of the first loop?

I need to print a wine list from a database.
I need to print at first a categorie and after all the items that are inside. Thats the order. And i have multiple categorie. So at the end the result will be categorie1, many items, categorie2 many items...
This is the code that i write from now: I think that my problem is to print items according to the id of the alcool_categorie !!
$q_vine = "SELECT * FROM alcool_categorie ";
$r_vine = mysql_query($q_vine,$connection);
$n_vine = mysql_num_rows($r_vine);
$q_bouteille = "SELECT * FROM alcool_item where ALCNID = '$alid'";
$r_bouteille = mysql_query($q_bouteille,$connection);
$n_bouteille = mysql_num_rows($r_bouteille);
for($i = 0; $i < $n_vine; $i++){
echo mysql_result($r_vine,$i,'named').'<br/><br/>';
for($z = 0; $k < $n_bouteille; $k++){
echo mysql_result($r_bouteille,$k,'name').'<br/>';
}
}
I think it's best to use a "JOIN" in your query and then order the rows in the way you want them to be ordered, then you'll only need one loop. While running the loop you compare the category name with the previous category name and if it changes display the category name.
Example
$sql = "SELECT categoryName, bottleName FROM category INNER JOIN bottle ON category.categoryId = bottle.categoryId ORDER BY category.categoryId";
$result = mysql_query($sql,$connection);
$categoryName = ''; //just to make sure the first time the Category is named
while ($row = mysql_fetch_assoc($result)) {
if($categoryName != row['categoryName']){
$categoryName = row['categoryName'];
echo '<h1>'.$categoryName.'</h1>';
}
echo row['bottleName'].'<br/>';
}
Try this after correctly giving the category id field name in the query and inside the first while loop.
$q_vine = "SELECT id, named FROM alcool_categorie ";
$r_vine = mysql_query($q_vine,$connection);
$n_vine = mysql_num_rows($r_vine);
while ($row = mysql_fetch_assoc($r_vine)) {
$categories[$row['id']] = $row;
}
$q_bouteille = "SELECT name, ALCNID FROM alcool_item ";
$r_bouteille = mysql_query($q_bouteille,$connection);
$n_bouteille = mysql_num_rows($r_bouteille);
while ($row = mysql_fetch_assoc($r_bouteille)) {
$items[$row['ALCNID']] = $row;
}
foreach ($categories as $category_id=>$category) {
echo "<ul><li>{$category['named']}<ul>";
foreach ($items[$category_id] as $item) {
echo "<li>{$item['name']}</li>";
}
echo "</ul></li></ul>";
}
You will want to look into PHP's foreach construct. Foreach loops through an entire array of results, for each element inside the array, it extracts its value and optionally also its key. This will not require the use of mysql_num_rows.
Instead of calling mysql_result, you could use mysql_fetch_assoc to get a row's value from your mysql_query. The row's To get all values, you can incorporate this into a loop even. If you do the latter, you can create your own array of key/value pairs and use this inside a foreach construct.
Also note that the use of mysql is outdated, you will want to use mysqli now, which is very similar to mysql.

PHP, SQL, in_array with csv and while loop only retrieving integer

I have searched for similar questions but cannot find the right answer to my specific one. I have a column (data) in my table (table) which contains comma separated values which are id's e.g.
Row 1= 4,5,45
Row 2= 5,8,9
Row 3= 5
I use an in_array function to retrieve the number of occurances for the $data value within the while loop. So I use an sql function to retrieve the number of times a certain value such as '5' occurs in all rows within the while loop.
The issue is that I can only retrieve the $data value if it is by itself (i.e. no commas just the integer by itself) so based on my example in the list, I can only retrieve 5 once (row 3). I would like to retrieve the value '5' three times as it appears in all the rows. Here is my code below and any help would be appreciated. The $selectiontext variable is what the user enters from the form.
$sql_frnd_arry_mem1 = mysql_query("SELECT data, id FROM table WHERE data='$selectiontext'");
while($row=mysql_fetch_array($sql_frnd_arry_mem1)) {
$datacheck = $row["data"];
$id = $row["id"];
}
$frndArryMem1 = explode(",", $frnd_arry_mem1);
if (($frnd_arry_mem1 !=="") && (!in_array($id, $frndArryMem1))) {echo $id;}
Thank you.
you keep overwriting the variables $datacheck and $id, leaving you with only the last version of them. move that curly brace down two lines, like this:
$sql_frnd_arry_mem1 = mysql_query("SELECT data, id FROM table WHERE data='$selectiontext'");
while($row=mysql_fetch_array($sql_frnd_arry_mem1)) {
$datacheck = $row["data"];
$id = $row["id"];
$frndArryMem1 = explode(",", $frnd_arry_mem1);
if (($frnd_arry_mem1 !=="") && (!in_array($id, $frndArryMem1))) {echo $id;}
}
I am not totally sure of your requirements, is not very clear what you intend to do as part of the code is missing.
I assume you want to check each row of a comma separated of a CSV file ($frnd_arry_mem1 being the row) against your data in column data, if any of those comma separated data (not) occurs.
Assuming you are already looping through your CSV, this would be the code (non tested):
NOTE: might be inefficient retrieving data within a loop, if you can do otherwise - but I cant tell as I dont kow the full specs of your script.
If I got the specs wrong please clarify, I will try to help further.
$sql = "SELECT data, id
FROM table
WHERE data='$selectiontext'";
$sql_frnd_arry_mem1 = mysql_query($sql);
$results = array();
// get values to check
while ($row = mysql_fetch_array($sql_frnd_arry_mem1))
{
$results[] = array(
'datacheck' => $row["data"],
'id' => $row["id"],
);
}
foreach ($results as $result)
{
$frndArryMem1 = explode(",", $frnd_arry_mem1);
$data = explode(',', $result['datacheck']);
foreach ($data as $d)
{
if (($frnd_arry_mem1 !=="") && (!in_array($d, $frndArryMem1)))
{
echo 'DEBUG: Record #' . $id . ' not found, value:' . $d . '</br>';
}
}
}

php & mysql - loop through columns of a single row and passing values into array

I have a mysql table with columns id, f1, f2, f3, ..., f20 where id is productID and f1,...f20 are product features. Depending on each product, some might have all, none or only some columns filled.
Each column holds a delimited string like a#b#c#d where a,b,c,d are values in different languages (a=english, b=french etc)
I need to select a row by it's id, explode each column's value (f1,f2...) with '#' in order to get the language part I need and then pass the values to an array in order to use in my product spec page.
How do I loop through the fetched row (i'm using $row = my_fetch_array) and put the exploded value into a one dimension array like $specs=('green', 'M', '100', 'kids'...) etc?
PS:I know, is complicated but I cant come up with a better idea right now.
Try this:
$result = mysql_query("...");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$arr = array();
foreach ($row as $k=>$v)
{
$features = explode("#", $v);
$value = $features[1]; // get the specific language feature
$arr[] = $value;
}
$specs = join(", " , $arr);
}
Not sure this is the best way togo but you could define an array with your langs, then access the result by lang
<?php
$langs=array('eng'=>0,'fr'=>1,'ger'=>2,'geek'=>3);
while ($row=mysql_fetch_assoc($result)) {
$specs=explode('#',$row['f1']);
$other=explode('#',$row['f2']);
...
}
//Get lang from cookie that you could set elsewhere
$lang=(isset($_COOKIE['lang']))?$_COOKIE['lang']:'eng';
echo $specs[$langs[$lang]];
?>
My solution for how I understand you question:
// Make a MySQL Connection
$sQuery = "SELECT f1,f2,... FROM table WHERE id = ...";
$oResult = mysql_query($sQuery) or die(mysql_error());
//Fetch assoc to use the column names.
$aRow = mysql_fetch_assoc($oResult);
//Prepare the product properties array
$aProductProperties = array("English"=>array(),"French"=>array(),"Dutch"=>array());
//Loop over all the columns in the row
foreach($aRow as $sColName=>$sColVal){
//Explde the column value
$aExplodedCol = explode("#",$sColVal);
//The code below could be nicer when turned into a looped that looped over every language,
//But that would make the code less readable
$aProductProperties['English'][$sColName] = $aExplodedCol[0];
$aProductProperties['French'][$sColName] = $aExplodedCol[1];
$aProductProperties['Dutch'][$sColName] = $aExplodedCol[2];
}
//Done, you should now have an array with all the product properties in every language

Print mysql results column by column

I feel incredibly stupid for not being able to figure this out, but I guess that's what Stackoverflow is for. If someone could point me to helpful resources or explain to me how to solve this, I would be very appreciative.
Basically I'm fetching a couple of rows from a table, and now I need to be able to print them out the value of each row's field, followed by the values of each row from a different field, and so on. It's hard to explain, but let me give you an example.
Let's say we have a table with three fields: id - name - url. Now I want to be able to output the result in this order:
1
2
3
John
Steven
Patrick
http://google.com/
http://stackoverflow.com/
http://php.net/
How do I loop through the results of my query in order to achieve this?
Well you should make an array and then spew it out:
$ids = array();
$names = array();
$urls = array();
while($row = ...){
$ids[] = $row['id'];
$names[] = $row['name'];
$urls[] = $row['url'];
}
foreach($ids as $id) {
echo $id . PHP_EOL;
}
//do the same for the other 2
You can do this via union. The only tricky part is making sure to cast all of the fields to a common data type (in this case, text). Also, each subquery is ordered by id to make sure that the ordering is consistent.
select id::text
from table
order by id
union
select name::text
from table
order by id
union
select url::text
from table
order by id
$result = mysql_query("SELECT id, name, url FROM yourtable") or die(mysql_error());
$data = array()
while($row = mysql_fetch_asssoc($result)) {
$data[] = $row;
}
foreach(array('id', 'name', 'url') as $key) {
foreach($data as $idx => $val) {
echo $val[$key], "\n";
}
}
The simplest way is
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$ids[] = $row['id'];
$names[] = $row['names'];
$wwws[] = $row['website'];
}
Then you iterate over the three arrays. There are surely better methods for doing this!

Categories