php display all row data from mysql table without column name - php

I want to display all rows/data from a MySQL table without knowing the column names.
I have the table name but not the column names, and I want to build a grid of the data using the table HTML attribute. I was thinking of using the schema but no idea where to start, any suggestions ?

SELECT * FROM table_name;
that should give you all the data including all rows.

To get the table structure, use this SQL query:
SHOW COLUMNS FROM table_name;
From there you can then make a query that grabs all data from the table and display it as you want.

it may be helpful for you
$response = mysql_query('select * from table_name');
while($result = mysql_fetch_assoc($response))
{
foreach($result as $key => $value)
{
echo $key.'--'.$value;
}
}

This is actually an easy task to achieve with the MYSQLI_ASSOC function as it will put in the db field name as the array key. Take a look at this example:
$query = "SELECT * FROM `MyTable`";
if ($result = $mysqli->query($query)) {
echo '<table>';
foreach($result->fetch_all(MYSQLI_ASSOC) as $row) {
foreach($row as $key => $value) {
echo '<tr><td>' . $key . '</td><td>' . $value . '</td></tr>';
}
}
echo '</table>';
}
This would print all the tables key and associated values

On your select statement you could do "select * from table_name". Then, you go to your for loop() in php and can do more less like this:
$query = mysqli_query($your_connection_name, $your_sql_query);
Then, place a while loop:
<?php
while($row = mysqli_fetch_array($query)){
$item_one = $row[0];
$item_two = $row[1];
$item_three = $row[2];
? > *//end php*
your html code here (table etc)
< ? php *//start php again*
} *//end while loop*
?> *//end php*
hope it helps.

Related

cannot retrieve indexes correctly mysqli

$search = htmlspecialchars($_GET["s"]);
if(isset($_GET['s'])) {
// id index exists
$wordarray = explode(" ",$search);
$stringsearch = implode('%',$wordarray);
echo $stringsearch;
echo ",";
$result = mysqli_fetch_array($conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%';"));
if (!empty($result)) {
echo sizeof($result);
echo ",";
Database has 3 rows with titles test,pest,nest with corresponding id's 1,2,3. when i request domain.com/?s=est
it echos something like this
est,2,
Now when i checked $result[0] and $result[1], $result[0] echoed 1 and $result[1] didn't echo anything. When I use foreach function, it is taking only value of $result[0]
and $result should be array of all the three indexes.
I cannot find any mistake,
when i type the same command in sql console it works, somebody help me, thanks in advance.
The problem is, if you're expecting multiple rows, then don't do this:
$result = mysqli_fetch_array($conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%';"));
This only fetches the first row, you need to loop it to advance the next pointer and get the next following row set:
$result = $conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%' ");
while($row = $result->fetch_array()) {
echo $row[0] . '<br/>';
// or $row['ID'];
}
Sidenote: Consider using prepared statements instead, since mysqli already supports this.

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

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.

PHP mySQL get table headers function

I'm trying to build a PHP function that allows me to have an array of the headers of MySQL database for finding a particular field.
function table($tablename,$id) {
$post = mysql_query("SELECT * FROM $tablename WHERE ID = '$id'");
}
How would I then output the table headers as effective miniature queries for the row in question.
eg. $post->title, $post->timestamp, $post->field4
You need MySQLi or PDO_MySQL, but in your case:
while ($row = mysql_fetch_assoc($post)) {
echo $row['title'];
}
Documentation
Remember that the use of mysql_* function is discouraged.
A simple PHP Script to fetch the field names in MySQL:
<?php
$sql = "SELECT * FROM table_name;";
$result = mysql_query($sql);
$i = 0;
while($i<mysql_num_fields($result))
{
$meta=mysql_fetch_field($result,$i);
echo $i.".".$meta->name."<br />";
$i++;
}
?>
OUTPUT:
0.id
1.todo
2.due date
3.priority
4.type
5.status
6.notes
Hope this helps! Taken from php.net documentation.
How about mysql_fetch_assoc($post)?
To get all field names int a seperate array:
$post = mysql_fetch_assoc($post);
$fields = array();
foreach($post as $title => $value){
$fields[] = $title;
}
You can use this in a while loop to go through all rows and get theri field values(as well as their names):
while($p = mysql_fetch_assoc($post)){
$title = $p['title'];
$timestamp = $p['timestamp'];
//And so on...
}
Edit: And Pierpaolo is right, you should use another mysql implementation as the old one is gonna be removed in PHP 5.5/5.6 or a bit later...
You can get just the column names by executing this:
DESCRIBE `MyTable`;
It will return a result set that contains Field, Type, Key, etc.
$query = mysql_query("DESCRIBE `MyTable`");
while($result = mysql_fetch_assoc($query)) {
echo $result['Field'] . "\n";
}

MYSQL - Select specific value from a fetched array

I have a small problem and since I am very new to all this stuff, I was not successful on googling it, because I dont know the exact definitions for what I am looking for.
I have got a very simple database and I am getting all rows by this:
while($row = mysql_fetch_array($result)){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
Now, my question is: how do I filter the 2nd result? I thought something like this could work, but it doesnt:
$name2= $row['name'][2];
Is it even possible? Or do I have to write another mysql query (something like SELECT .. WHERE id = "2") to get the name value in the second row?
What I am trying to is following:
-get all data from the database (with the "while loop"), but than individually display certain results on my page. For instance echo("name in second row") and echo("id of first row") and so on.
If you would rather work with a full set of results instead of looping through them only once, you can put the whole result set to an array:
$row = array();
while( $row[] = mysql_fetch_array( $result ) );
Now you can access individual records using the first index, for example the name field of the second row is in $row[ 2 ][ 'name' ].
$result = mysql_query("SELECT * FROM ... WHERE 1=1");
while($row = mysql_fetch_array($result)){
/*This will loop arround all the Table*/
if($row['id'] == 2){
/*You can filtere here*/
}
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
$counter = 0;
while($row = mysql_fetch_array($result)){
$counter++;
if($counter == 2){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
}
This While loop will automatically fetch all the records from the database.If you want to get any other field then you will only need to use for this.
Depends on what you want to do. mysql_fetch_array() fetches the current row to which the resource pointer is pointing right now. This means that you don't have $row['name'][2]; at all. On each iteration of the while loop you have all the columns from your query in the $row array, you don't get all rows from the query in the array at once. If you need just this one row, then yes - add a WHERE clause to the query, don't retrieve the other rows if you don't need them. If you need all rows, but you wanna do something special when you get the second row, then you have to add a counter that checks which row you are currently working with. I.e.:
$count = 0;
while($row = mysql_fetch_array($result)){
if(++$count == 2)
{
//do stuff
}
}
Yes, ideally you have to write another sql query to filter your results. If you had :
SELECT * FROM Employes
then you can filter it with :
SELECT * FROM Employes WHERE Name="Paul";
if you want every names that start with a P, you can achieve this with :
SELECT * FROM Employes WHERE Name LIKE "P%";
The main reason to use a sql query to filter your data is that the database manager systems like MySQL/MSSQL/Oracle/etc are highly optimized and they're way faster than a server-side condition block in PHP.
If you want to be able to use 2 consecutive results in one loop, you can store the results of the first loop, and then loop through.
$initial = true;
$storedId = '';
while($row = mysql_fetch_array($result)) {
$storedId = $row['id'];
if($initial) {
$initial = false;
continue;
}
echo $storedId . $row['name'];
}
This only works for consecutive things though.Please excuse the syntax errors, i haven't programmed in PHP for a very long time...
If you always want the second row, no matter how many rows you have in the database you should modify your query thus:
SELECT * FROM theTable LIMIT 1, 1;
See: http://dev.mysql.com/doc/refman/5.5/en/select.html
I used the code from the answer and slightly modified it. Thought I would share.
$result = mysql_query( "SELECT name FROM category;", db_connect() );
$myrow = array();
while ($myrow[] = mysql_fetch_array( $result, MYSQLI_ASSOC )) {}
$num = mysql_num_rows($result);
Example usage
echo "You're viewing " . $myrow[$view_cat]['name'] . "from a total of " . $num;

How do I loop through a PHP array containing data returned from MySQL?

Ok I have a table with a few fields. One of the fields is username. There are many times where the username is the same, for example:
username: bob
password: bob
report: 1
username: bob
password: bob
report: 2
I did a SQL statement to select * where username='bob'; but when I do the following PHP function, it will only return the last result:
$thisrow = mysql_fetch_row($result);
I need to get every field from every row. How should I go about doing this?
$mainsection="auth"; //The name of the table
$query1="select * from auth where username='$user'";
$result = mysql_db_query($dbname, $query1) or die("Failed Query of " . $query1); //do the query
$thisrow=mysql_fetch_row($result);
echo "Study: " . $thisrow[1] . " - " . $thisrow[5];
Sorry for such a dumb question. I can't seem to get the while loops of more than one field working for the life of me.
mysql_fetch_row fetches each row one at a time. In order to retrieve multiple rows, you would use a while loop like this:
while ($row = mysql_fetch_row($result))
{
// code
}
Use a loop, and use mysql_fetch_array() instead of row:
while($row = mysql_fetch_array($result)) {
echo "Study: " . $row[1] . " - " . $row[5];
// but now with mysql_fetch_array() you can do this instead of the above
// line (substitute userID and username with actual database column names)...
echo "Study: " . $row["userID"] . " - " . $row["username"];
}
I suggest you to read this:
http://www.w3schools.com/php/php_mysql_select.asp
It will give you an overview idea of how to properly connect to mysql, gather data etc
For your question, you should use a loop:
while ($row = mysql_fetch_row($result)){//code}
As said by htw
You can also obtain a count of all rows in a table like this:
$count = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS count FROM table"));
$count = $count["count"];
You can also append a normal WHERE clause to the select above and only count rows which match a certain condition (if needed). Then you can use your count for loops:
$data = mysql_query("SELECT * WHERE username='bob'");
for ($i = 0; $i
Also, mysql_fetch_array() is usually a lot easier to use as it stores data in an associative array, so you can access data with the name of the row, rather than it's numeric index.
Edit:
There's some kind of bug or something going on where my second code block isn't showing everything once it's posted. It shows fine on the preview.
I like to separate the DB logic from the display. I generally put my results into an array that I can call within the HTML code. Purely personal preference; but here's how'd I'd approach the problem: (I'd take the $sql out of the error message in production)
<?php
$sql="
SELECT *
FROM auth
WHERE username='$user';
";
$result = mysql_query($sql)
or die("Failed Query : ".mysql_error() . $sql); //do the query
while ($ROW = mysql_fetch_array($result,MYSQL_ASSOC)) {
$USERS[] = $ROW;
}
?>
HTML CODE
<? foreach ($USERS as $USER) { ?>
Study: <?=$USER['dbFieldName'];?> - <?=$USER['dbFieldName2'];?>
<? } //foreach $USER ?>
$qry=mysql_query(select * where username='bob');
if(mysql_num_rows($qry))
{
while($row=mysql_fetch_array($qry,MSQL_NUM))
{
echo $row[0]." ".$row[1]." ".$row[2]."<br>";
}
}

Categories