Im currently making a private "list management" system in which I store SQL queries in the database. So that I can via the front-end create new "lists" (which basicly are sql queries), and view them.
I have made the front end so you can save queries into the database, and im at the point where I want PHP execute and print out the results of one of my queries. This happens when I select one of my stored "lists" on my frontend. So when I press one of the lists, it should execute the SQL query. So far, so good.
But how can I, via PHP, print a table (like the one you get out from phpMyAdmin when viewing the contents of a table) without knowing how many / what columns exists? I want the script to be dynamic, so I can view results of all kinds of SELECT queries (on different tables).
Any tips or pointers?
Rather than using deprecated libraries, use PDO instead.
$db = new PDO($dsn); //$dsn is the database connection strings. Depends on your DB.
//it can be as simple as "odbc:CONN_NAME"
$stmt = $db->prepare("SELECT * FROM $tablename");
//be sure to sanitize $tablename! use a whitelist filter, not escapes!
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); //fetch as associative array
if($rows){
//check if there are actual rows!
$first_row = reset($rows); //Resets the internal pointer, return the first elem.
$header_str = '<th>' . implode('</th><th>', array_keys($first_row)) . '</th>';
$table_body_rows = array();
foreach($rows as $row){
$table_body_rows[] = '<td>' .
implode('</td><td>', $row) .
'</td>';
}
$body_str = '<tr>' . implode('</tr><tr>', $table_body_rows) . '</tr>';
$tbl = "<table><thead><tr>$header_str</tr></thead><tbody>$body_str</tbody></table>";
} else {
//something went wrong
}
show tables is probably what you need
echo "<table><tr>";
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
while ($row = mysql_fetch_row($result)) {
echo "<td> $row[0] </td>";
}
echo "</tr></table>"
mysql_free_result($result);
If you need to print a row with header (column names), you have to do it this way:
$result=mysql_query("SELECT * FROM yourtable WHERE 1");
if (mysql_num_rows($result)<1) echo "Table is empty";
else
{
$row=mysql_fetch_assoc($result);
echo "<table>";
echo "<tr>";
echo "<th>".join("</th><th>",array_keys($row))."</th>";
echo "</tr>";
while ($row)
{
echo "<tr>";
echo "<td>".join("</td><td>",$row)."</td>";
echo "</tr>";
$row=mysql_fetch_assoc($result);
}
echo "</table>";
}
This is just the basic concept. If your table has values which may contain HTML tags and other stuff, you'll need to apply htmlspecialchars() on all values of $row. This can be done with array_walk(). Furthermore you didn't mention what PHP version are you using and what MySQL API do you prefer. Some people suggested to use mysqli or PDO, that's up to you to rewrite the code according to your preferred API.
Related
I have two MySQL tables with number of columns. The table structure is given below,
1.pictures
postedON
caption
imageName
thumbName
imageLocation
thumbLocation
2.Videos
postedOn
category
Link
I am using the folowing PHP function to fetch data from DB using a select command.
function select($table){
if($this->db_connection){
$query = 'SELECT * FROM '. $table;
$result = mysqli_query($this->db_connection,$query) or die($this->db_connection->error);
//print_r($result);
//echo "Affected rows: " . mysqli_affected_rows($this->db_connection);
//var_dump($result);
echo "<table>";
echo "<tr>";
echo "<th>Date Posted</th>";
echo "<th>Category</th>";
echo "<th>Link</th>";
echo "</tr>";
while($row = $result->fetch_assoc()){
echo "<tr>";
echo "<td>" . $row['postedOn'] . "</td>";
echo "<td>".$row['category']. "</td>";
echo "<td>" . $row['link'] . "</td>";
echo "</tr>";
}
echo "</table>";
}else{
echo "db_connection is = " . $this->db_connection;
}
}
}
The problem with this function as you can see, it can only serve only one table and not dynamic. Can someone please explain the way to dynamically fetch data from different table with different number of columns using only one PHP function? Thanks
Try using mysqli_fetch_fields()
<?php
function select($table){
if($this->db_connection){
$query = 'SELECT * FROM '. $table;
$result = mysqli_query($this->db_connection,$query) or die($this->db_connection->error);
$fieldinfo = mysqli_fetch_fields($result);
echo "<table>";
echo "<tr>";
foreach ($fieldinfo as $val)
{
echo "<th>".$val->name."</th>";
}
echo "</tr>";
while($row = $result->fetch_assoc()){
echo "<tr>";
foreach ($fieldinfo as $val)
{
echo "<td>" . $row[$val->orgname] . "</td>";
}
echo "</tr>";
}
echo "</table>";
}else{
echo "db_connection is = " . $this->db_connection;
}
}
It could be hard to explain given all the wrong premises you approach is based on, but I'll try.
First of all, you have to understand that a query like SELECT * FROM table has a very little use, next to none. Most of time you are always have some WHERE or at least LIMIT clause. So, such a function will have no use at all.
Next, you have to learn by heart that database interaction should never be intermixed with any output stuff like HTML.
Given these two premises above, your function should accept a fill qualified query as a parameter and return an array with data as a result.
For which array, in turn you can write a helper function to display its contents in the form of HTML table.
But again, such a generalized output function will be of little use as well, because, as you can see from your own example, different fields will need different formatting. So it's better to write output each time by hand.
I am trying to print the whole database in tabular format in a php file using PDO. i have this database stored in phpmyadmin. But there are a lot of rows in there like name,id, etc etc... I have this following php code. i already made a connection to the database and added require_once() in the page. But i dont know how to print all these values in a tabular method. like showing it in a way a normal database will look like.
$q="SELECT * FROM `employee`";
$sth = $odb->prepare($q);
$sth->execute();
while ($r = $sth->fetch(PDO::FETCH_ASSOC)){
// code here
}
Can someone help me to display the table properly. That is if i run it in browser, i should see a table instead of that ugly array format
Ideally each table should have his own format, but if you just want to pop all the data from the base inside a HTML table, you could do something like that :
$sql = 'SELECT * from page';
$result = $pdo->query($sql);
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
if(count($result)) {
echo '<table><tr>';
foreach ($rows[0] as $columnName => $value) {
echo '<th>' . $columnName . '</th>';
}
echo '</tr>';
foreach ($rows as $row) {
echo '<tr>';
foreach ($row as $value) {
echo '<td>' . $value . '</td>';
}
echo '<tr>';
}
echo '</table>';
}
You could use this on each table you want to show.
I am new to PHP and programming, but am attempting to print out the results from each row of one of my MySQL database tables.
Using a set of while loops I achieved this:
while($placeHolder = $query->fetch_assoc()){ // use assoc
echo "<div class='placeHolder'><img src=" . $placeHolder['photo']. " /></div>";
echo "<br />";
}
while($placeHolder2 = $query2->fetch_assoc()){
echo "<div class='placeHolder2'>" . $placeHolder2['name'] . "</div>";
echo "<br />";
}
//etc, etc...
Besides being inefficient, I'm assuming this may also be a security risk.
Is there a better way to do this, possibly using a foreach statement?
Here is my SQL code I forgot to include:
$query = mysqli_query($conx, $sql);
$query2 = mysqli_query($conx, $sql);
$sql = ('SELECT id,name,picture FROM table ORDER BY name DESC LIMIT 50');
I dont think using a foreach statement to print out the results would make it any less safe/unsafe. It really depends on your query. You should be able to print all of them using a foreach doing something like:
$result = $query->fetch_all(MYSQLI_ASSOC);
foreach($result as $row) {
echo $row['photo'];
}
Note** to use fetch_all you would need mysqlnd installed
edit: looking at your query nothing can be injected there. No outside variables being used in the query, so its safe. I would just use the while loop that you originally posted.
edit 2: link to fetch_all documentation: http://php.net/manual/en/mysqli-result.fetch-all.php
I have two PHP pages. On page1 a temporary table is created and filled with data from a mysql database. I am trying to store this table into a $_SESSION variable so that I can put the table onto page2.
Right now this has been my approach:
This is the code on page1:
//Select data from database
$result = mysqli_query($mysqli,"SELECT * FROM table");
//Set array
$array = array();
while($row = mysql_fetch_assoc($result)){
// add each row returned into an array
$array[] = $row;
}
//store array into session variable
$_SESSION['fase1result'] = $array;
This is the code on page2:
$table = $_SESSION['fase1result'];
echo "<table border='1'>
<tr>
<th>ProductID</th>
<th>ProductName</th>
<th>Fase1</th>
</tr>";
foreach ($table as $row)
{
echo "<tr>";
echo "<td>" . $row['ProductID'] . "</td>";
echo "<td>" . $row['ProductName'] . "</td>";
echo "<td>" . $row['Fase1'] . "</td>";
echo "</tr>";
}
echo "</table>";
Unfortunately, up until now these scripts return me an empty table on page2. Help would be greatly appreciated!
UPDATE:
Best thing for me would be to preserve the temporary table as is, so that I'm able to further manipulate it with MySQL queries on page 2. Do you know how to do that instead of ripping it apart by pulling the data into a php array? Sorry for mixing up this question a little bit.
You need to call session_start() before using any session-related facilities.
session_start();
$_SESSION['fase1result'] = $array;
then
session_start();
$table = $_SESSION['fase1result'];
Note that in most cases you need to call session_start() before any output, since it typically needs to send Cookie: headers to the client browser unless you have configured a different means of session persistence. Failing to do so can result in "header already sent" errors.
As tgies already pointed out, you need to have your session intialized.
Furthermore you use mysql_fetch_assoc() eventhough you're using mysqli (at least for the query), use while($row = $result->fetch_assoc()) or themysqli_fetch_assoc function (note the i).
Edit: There are several other options, but in most cases storing the data in a single, persistent table and identify it via an id in $_SESSION is a good way.
I'm trying to determine the right syntax from what I'm trying to do with MySQL. I'm basically saying that if a value in a certain column of a row of a table is equal to some session variables, I want to echo out info.
I have a table with subject, description and user. User is set by taking the current user's first name and last name and inserting it into the table under user. This is done by the following code:
$sql="INSERT INTO tbl_name (subject, description, user)
VALUES
('$_POST[subject]','$_POST[description]','$_SESSION[firstname] $_SESSION[lastname]')";
Then once I'm calling this data back out, I want to basically allow the user to delete content that they submitted themselves. The first step for me is to be able to display it in the table. I believe this is just syntax error, but I've confused myself now with how things are set up:
$sql = "SELECT * FROM tbl_name ORDER BY subject, description
LIMIT {$startpoint},{$limit}";
$result = $mysqli->query($sql);
$num_rows = mysqli_num_rows($result);
if($num_rows>0){
$field_num = $mysqli->field_count;
echo "<h1>HERE ARE SOME EXAMPLES:</h1>";
echo "<table border='0'><tr>";
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->subject}</td>";
echo "<td>{$field->description}</td>";
echo "<td>{$field->user}</td>";
if('$field->user' == '$_SESSION[firstname] $_SESSION[lastname]'){
echo '<td>You can delete this</td>';
}
}
I figured the $field->user would equal $_SESSION[firstname] $_SESSION[lastname] because that's how it was initially submitted to the table (without the '.' for concatenation).
Any help would be appreciated. Thanks!
EDIT
Here's the result of my table output code. The results are actually being display with $cell instead of from within the for loop I believe. I've added the if statement in after the but it doesn't seem to recognize echo "<td>".$field->user."</td>"; which makes me think that that is where the problem lies. What I would like to do is be able to add the if statement in a immediately after `echo {$field->user}"; to keep the code clean. I think I've confused myself thoroughly:
if($num_rows>0){
$field_num = $mysqli->field_count;
echo "<h1>HERE ARE SOME JOBS:</h1>";
echo "<table border='0'><tr>";
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->subject}</td>";
echo "<td>{$field->description}</td>";
echo "<td>{$field->user}</td>";
if($field->user == $_SESSION[firstname]." ".$_SESSION[lastname]){
echo '<td>You can delete this</td>';
}
else{
echo "<td>".$field->user."</td>";
echo "<td>".$_SESSION[firstname]." ".$_SESSION[lastname]."</td>";
}
}
echo "</tr>\n";
while($row = mysqli_fetch_row($result))
{
echo"<tr>";
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysqli_free_result($result);
}
else{
echo 'There are no jobs!';
}
I re-wrote the code in a way that was a little bit easier for me to understand (though maybe not the shortest way to do it):
while($row = mysqli_fetch_array($result))
{
echo"<tr>";
echo"<td>".$row['subject']."</td>";
echo"<td>".$row['description']."</td>";
echo"<td>".$row['user']."</td>";
if($row['user'] == $_SESSION['firstname']." ".$_SESSION['lastname']){
echo"<td>You can delete this</td>";
}
else{
echo"<td>Code didn't work</td>";
}
echo "</tr>\n";
}
It ended up working this way. If there's way to do this shorter then feel free to post it here otherwise thanks for the help!