Get row values as column names using Codeigniter and mysql - php

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 ?>

Related

CodeIgniter MySQL count different rows

i want to count the different rows in CodeIgniter...
I have a table like this
NAME | ZIPCODE
Mike | 12345
Marc | 51233
TEST | 12345
Now i want a Result of "2" cause there 2 different Zipcodes.
I tried so much, but dont get this :(
$this->db->select('zipcode, count(*)');
$getAll = $this->db->get('ads');
echo $getAll->num_rows();
but dont get result of or anything... idk how i can make this.
Please help
//EDIT:
Okay i found it. Sorry for Question. Here is the Answer
$this->db->distinct();
$this->db->select('zipcode');
$getAll = $this->db->get('ads');
echo $getAll->num_rows();
you can use this:
$query = $this->db->query('select count(1) as x from your_table_name group by zipcode');
$row= $query->row();
$x = $row->x;
You could use group_by() in your query as follows.
$this->db->select('zipcode', 'count(*) as totalcount');
$this->db->group_by('zipcode');
$this->db->get('ads');

How can I display the column names of a table using 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

PHP MYSQL looking for a way to group rows that have same value in certain column

I have a table named records with the columns: recordid, artist, album, description and coverimg. Some of the albums in the table have the same artist.
On my site I would like to display it like this:
-artist1
album1
album2
- artist2
album3
-artist3
album4
album5
If I use GROUP BY it just shows one row per artist. Is there any other way to group them without resorting to relational tables?
Because now I have a form to insert and update the table through my site, and I have no idea how I would have to code the forms to make this work with relational tables.
try this
select artist,group_concat(album) from albums group by artist
gives you
artist1 | album1,album2,album3
artist2 | albumx,albumy
You can split the second column in PHP e.g. using explode(row[1])
That should help you a bit
You can do it without a group by:
<?php
$query = 'Select artist, album
FROM records
ORDER BY artist'
$result = mysql_query($query);
$artist = '';
while ($line = mysql_fetch_assoc($result)){
// only show artist when it's an other artist then the previous one
if ($line['artist'] != $artist){
echo $line['artist'].'<br/>';
$artist = $line['artist'];
}
echo $line['album'].'<br/>';
}
?>
I know I should not be using mysql_* functions anymore, please choose mysqli_* or PDO....

Remove mySQL row if 1 field is found

I have a mySQL table called "clients" with this structure:
Name | Phone | ID
Now I am using $_GET to extract an ID from a URL, then I would like to delete the entire row (name, phone and ID) from the database that has that ID.
How woudl I do this last part (selecting the row and removing it)? I've tried some stuff but I am starting with php and mysql and it's kind of confusing.
Thank you for your help.
I hope this could help you out to understand better :)
<?php
$Action=$_REQUEST['a'];
$ID=$_REQUEST['id'];//i assume your ID's are numeric so to avoid injections check for numeric
if(is_numeric($ID)){
if($Action=="del" and $ID){
mysql_query("DELETE FROM clients WHERE id=".$ID);
}
$q=mysql_query("SELECT * FROM clients WHERE id=".$ID);
while($qd = mysql_fetch_array($q)){
echo "Name: ".$qd['name']."<br>Phone: ".$qd['phone']."<br><a href='?a=del&id=".$qd['id']."'>Delete</a><br><br>";
}
}
?>

How to I pull information from MySQL with PHP?

I am asking if it is not only possible to pull data from a MySQL table, but also display each row in either a table or a DIV, preferably a DIV. How would I do so?
Table:
ID |BodyText |Title |
1 |Hello World1 |Title1 |
2 |Hello World2 |Title2 |
etc..
I'd like to put each row into a DIV that has a title and also bodytext, but I want php to generate these tables and put the info into each DIV.
Possible to do?
We will use this table as an example data set:
Database Name: friends
-----------------------------
| firstname || lastname |
----------------------------
|Chris || Geizz |
|Steve || Michalson |
|Ken || Bohlin |
|Doug || Renard |
-----------------------------
First you must connect to your database as so:
http://www.w3schools.com/PHP/php_mysql_connect.asp
You would run a MYSQL query to get the data from the MySQL Database:
$query = mysql_query("SELECT * FROM friends");
Then you would use the following to put them into a table:
echo "<table><tr><td>First Name</td><td>Last Name</td></tr>";
while($row = mysql_fetch_array($query))
{
echo "<tr><td>";
echo $row['firstname'];
echo "</td><td>";
echo $row['lastname'];
echo "</td></tr>";
}
echo "</table>";
What this basically does is pulls the information that is returned with my mysql_query and puts it into an array that you can call with the $row variable we set. We do this in the while loop so that it repeats for all records in your database.
The code before the while loop and after the while loop are there so that way it is all in one table and we are just making rows instead of separate tables for each row in your database.
This will accomplish what you want. When you are doing the while loop you can use the variables ($row['firstname'] and $row['lastname']) as you wish. You could place them in seperate DIV's if you wish as well.
Hope this helps you! If you have any questions leave a comment and I will respond.
Basically you can do whatever you want, once you have the rowset. The general structure of such code (if layers not devided / MVC) looks like this:
connect to db
write query
retrieve results
loop for each row in resultset
{
echo html and column content as you wish
}
so for example you could use
foreach ($rowset as $row)
{
echo '<div>'.$row['column1'].' is a friend of '.$row['column2'].'</div>';
}
Here's the manual pages for how to access/query MySQL databases:
MySQL: http://www.php.net/manual/en/book.mysql.php
MySQLi: http://www.php.net/manual/en/book.mysqli.php
Using the functions there you can easily query and display the data as you see fit. If you are wanting to access column info (field names) you either need to use the access the information_schema tables or use queries like describe table.
Update: based on the comments, the question relates more to Tharkun's answer than this.
<?php
$result = mysql_query("SELECT * from table");
if($result && mysql_num_rows($result))
{
$numrows = mysql_num_rows($result);
$rowcount = 1;
while($row = mysql_fetch_assoc($result))
{
print "<div><b>$rowcount</b>";
foreach($row as $var => $val)
{
print"|$var: $val|";
}
print "</div>";
++$rowcount;
}
}
?>

Categories