PHP - How can I print out my database table? - php

I have a php code to print out my table including its column name. The printing has to be dynamic because it has to print different size/length tables based on a user input. :
<table>
<?php
while ($row = mysqli_fetch_array($results)) {
while ($fieldInfo = mysqli_fetch_field($results)) { ?>
<th> <?php echo $fieldInfo->name; ?> </th>
<td> <?php echo $row[$fieldInfo->name] ?> </td>
<?php }
} ?>
</table>
this is the query for $results:
$tName = $_POST["tableNames"]; //this data is recieved from another page
require_once("conn.php");
$sql = "SELECT * FROM $tName";
$results = mysqli_query($conn, $sql)
or die ('Problem with query' . mysqli_error($conn));
my code correctly prints out the table name as well as the first row data but it is not formatted correctly here is how it looks:
additionally. for some reason it only prints out the first row even though im using a while loop.

My advice to you is to prepare two arrays:
First one: containing column names and second: containing data.
When use two foreach to generate first row with header and second one to display data. You have forgot to add <tr> tags to divide rows.

Use
The mysqli_fetch_field() function returns the next column in the result set as an object. It will only returns all column names not the records of table.
You need to use mysqli_fetch_array() for getting all records:
while ($info = mysqli_fetch_array($results,MYSQLI_ASSOC)) {
{
echo $info['rid'];
echo $info['level'];
....
}

I ended up with using a taras' suggestion of storing the column names in an array:
<table>
<?php
while ($fieldInfo = mysqli_fetch_field($results)) { ?>
<th> <?php echo $fieldInfo->name; ?> </th>
<?php
$colNames[] = $fieldInfo->name;
?>
<?php }
while ($row = mysqli_fetch_array($results)) { ?>
<tr>
<?php for ($i=0; $i<sizeof($colNames); $i++) { ?>
<td><?php echo $row[$colNames[$i]] ?>
<?php } ?>
</tr>
<?php } ?>
</table>

As of my understand, do you want to display all table and their columns?
So you can format like below
$sql = "SHOW TABLES FROM dbname";
$result_tables = mysqli_query($link, $sql);
echo "<table border=1>";
echo "<tr><td>Table name</td><td>Fields name</td></tr>";
while($row = mysqli_fetch_array($result_tables)) {
echo "<tr>";
echo "<td>".$row[0]."</td>";
$sql2 = "SHOW COLUMNS FROM ".$row[0];\\row[0] is used to get table name
$result_fields = mysqli_query($link, $sql2);
echo "<td>";
while($row2 = mysqli_fetch_array($result_fields)) {
echo $row2['Field'].',';
}
echo "</td>";
echo "</tr>";
}

Related

How could you use PHP and a SQL database to change HTML <h> content?

I have a webpage that displays cars from the first car in the table to the last car with a while loop.
I have the following columns: Make, Model, Price. In my syntax I have an anchor tag around the Make rows that links to the description page of the Make you click on.
I want my <h> tags to change to the Model of the corresponding Make.
I've spent over an hour trying to achieve this but all I could come up with is this:
<?php
$query = "SELECT Model FROM inventory;";
$Vtitle = $conn->query($query);
$Vtitle_ar = mysqli_fetch_assoc($Vtitle);
echo "<h1>".$Vtitle_ar['Model']."</h1>";
?>
This works to an extent.
Every anchor I click replaces the <h> tags with only the first result under the Model column in my database.
Here is my code for the the entire car inventory page
<?php
$query = "SELECT * FROM inventory;";
/* Try to query the database */
if ($result = $conn->query($query)) {
// Don't do anything if successful.
}
else {
echo "Error getting cars from database:" .$conn->error()."<br>";
}
// Create the table headers
echo "<table id='Grid' style='width: 80%'><tr>";
echo "<th style='width: 50px'>Make</th>";
echo "<th style='width: 50px'>Model</th>";
echo "<th style='width: 50px'>Asking Price</th>";
echo "</tr>\n";
$class = "odd"; // keep track of whether a row was even or odd, so we can style it later
// Loop through all the rows returned by the query, creating a table for each row
while ($result_ar = mysqli_fetch_assoc($result)) {
echo "<tr class=\"$class\">";
echo "<td><a href='viewcar.php?VIN=".$result_ar['VIN']."'>".$result_ar['Make']."<a></td>";
echo "<td>".$result_ar['Model']."</td>";
echo "<td>".$result_ar['ASKING_PRICE']."</td>";
echo "</td></tr>\n";
// if the last row was even, make the next one odd and vice-versa
if ($class=="odd") {
$class = "even";
}
else {
$class = "odd";
}
}
echo "</table>";
$conn->close();
?>
Does anyone how I can do this?
I'm new to programming and I'm trying to use this for an actual project I'm working on for a hair salon's website
Add a WHERE clause to the query.
$vin = $_GET['VIN'];
$stmt = $conn->prepare("SELECT Model FROM inventory WHERE VIN = ?");
$stmt->bind_param("s", $vin);
$stmt->execute();
$stmt->bind_result($model);
$stmt->fetch();
echo "<h1>$model</h1>";
Though not a solution resolved with the use of a where clause as given by #Barmar whilst formatting the code I did find an error within the HTML which was not immediately obvious
The line echo "</td></tr>\n"; has an extra </td> which would break the flow of the html and can have detrimental effects. Also, // Don't do anything if successful. makes no sense - if there are results then process the recordset otherwise show the error ;-)
<?php
$query = "SELECT * FROM inventory;";
if ( $result = $conn->query( $query ) ) {
echo "
<table id='Grid' style='width: 80%'>
<tr>
<th style='width: 50px'>Make</th>
<th style='width: 50px'>Model</th>
<th style='width: 50px'>Asking Price</th>
</tr>";
$i=0;
while( $result_ar = mysqli_fetch_assoc( $result ) ) {
$class = $i %2 == 0 ? 'even' : 'odd';
echo "
<tr class='$class'>
<td><a href='viewcar.php?VIN={$result_ar['VIN']}'>{$result_ar['Make']}<a></td>
<td>{$result_ar['Model']}</td>
<td>{$result_ar['ASKING_PRICE']}</td>
</tr>";
$i++;
}
echo "</table>";
} else {
echo "Error getting cars from database:" .$conn->error()."<br>";
}
$conn->close();
?>
For styling alternate table rows ( the above uses a modulus function to calculate odd/even ) you can do it with some simple CSS - such as
tr:nth-child( odd ){/* rules */}

do while in do while in php

That loop using do while, and it is working fine but when I add another do while in to this the second do while work but first do while only show one row not all 10 row. My code is below
<?php do { ?>
<tr>
<td><?php echo $row_Recordset1['date']; ?></td>
<?php do { ?>
<td><?php echo $row_Recordset1['nav']; ?></td>
<?php } while ($row_Recordset1= mysql_fetch_assoc($Recordset1)); ?>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
My date should be displayed once in a row but all the other td will be took from nav;
This is what I want:
------------------------
|2014-02-26|5.5|3.2|3.5|
------------------------
|2014-02-25|3.1|1.2|1.5|
But I'm currently getting:
------------------------
|2014-02-26|5.5|3.2|3.5|
------------------------
You should look at http://php.net/mysql_fetch_assoc
It moves the internal pointer one step ahead, so each time you do mysql_fetch_assoc() you get the next value, hence only your enternal do while is executed. That is, only date from the first row is output, and all other values are output in second do while;
Try this for exercise:
$q = mysql_query("SOME MYSQL QUERY WITH MINIMUM THREE ROWS");
$f = mysql_fetch_assoc($q);
$f = mysql_fetch_assoc($q);
$f = mysql_fetch_assoc($q);
print_r($f);
First of all, please don't bounce in and out of PHP like that...
<?php
do {
echo '<tr>
<td>';
echo $row_Recordset1['date'];
echo '</td>';
do {
echo '<td>';
echo $row_Recordset1['nav'];
echo '</td>';
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
echo '</tr>';
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
?>
Where do you fetch your first $row_Recordset1? Somewhere earlier than this code? You're going to output table cells (<td>) until you run out of rows. I don't think you want that.
Like so:
<?php do { ?>
<tr>
<td><?php echo $row_Recordset1['date']; ?></td>
<td><?php echo $row_Recordset1['nav']; ?></td>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
Because each time you use mysql_fetch_assoc it does the following
Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead.
Part of the reason this doesn't work is because you are re-assigning the value of the same variable. If you don't want to lose it then you cannot do it this way. At the very least it is a bad idea if you ever intend to do anything new with the code.
Next, I really recommend you populate an array with the data first before you ever do anything with outputting it. It is a very good idea to separate logic from output.
Your code should look more like this:
<?php
//Assumes you have already connected to a mysqli resource
$conditional_data_filtered = $mysqli->real_escape_string($conditional_data);
$sql = "SELECT date, nav FROM some_table WHERE some_column = '" . $conditional_data_filtered . "'";
if ($result = $mysqli->query($sql)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$data = array(); //Make sure we start with a fresh array each time.
$data['date'] = $row['date'];
//Now I think you have a bunch of data in the nav you need to loop through
$nav_filtered = $mysqli->real_escape_string($row['nav']);
$subSql = "SELECT some_data FROM navigation WHERE some_identifier = '" . $nav_filtered . "'";
if ($subResult = $mysqli->query($subSql)) {
while ($subRow = $subResult->fetch_assoc()) {
$data['nav'][] = $subRow;
}
}
$rowList[] = $data;
}
/* free result set */
$result->free();
}
foreach ($rowList as $rowData) {
echo "<tr>";
echo "<td>" . $rowData['date'] . "</td>";
foreach ($rowData['nav'] as $navData) {
echo "<td>" . $navData['some_info'] . "</td>";
}
echo "</tr>";
}
?>
Just a note: If you really don't have sub-data and just want to output the next column then you don't need a sub-loop. You just need to echo the contents of the column like you did with the first one. Then you can get rid of the sub-loops I have shown above and just put it within the first loop.

Get line breaks in the my-sql_fetch_array table results

I have a simple project that I am working on and I'm having a hard time finding the code I need to get line breaks in the following table:
<?php
// connect to the database
$host = '###';
$username = '###';
$pass = '####';
mysql_connect($host,$username,$pass) or die(mysql_error());
mysql_select_db("####") or die(mysql_error());
// select everything from the table
$query = "SELECT * FROM Employees";
$result = mysql_query($query) or die(mysql_error());
echo "<table>";
echo "<tr>";
while( ($row = mysql_fetch_array($result)))
{
echo "<td>".$row['employeeid']."</td>";
echo "<td>".$row['firstname']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['department']."</td>";
}
echo "</tr>";
echo "</table>";
// disconnect from the database
mysql_close();
?>
Everything works correctly and it grabs data from the correct database and table. But when it displays results it is all on the same line ("record1record2record3") and I'd like a line break between employee records.
I've searched this question and it seems like my results all show me an entirely different way of doing this. I've already got the code written and fussed with it a lot to get it working. Can I just make a simple alteration to the above code to get the breaks I want?
The <tr> tags must also be inside the while loop so that they are outputted for each row. They make the rows in the HTML table.
while( ($row = mysql_fetch_array($result)))
{
echo "<tr>";
echo "<td>".$row['employeeid']."</td>";
echo "<td>".$row['firstname']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['department']."</td>";
echo "</tr>";
}

Deleting database values Using PHP, not working

I am trying to delete multiple values from my form (its a car rental system, where I want to give the staff the ability to delete a car from the record). I am new to PHP but this is what I have right now.
<?php
$link = mysql_connect ("xxxx", "xxxx", "xxxx");
mysql_select_db ("xxxx");
$query = "SELECT * from car";
$result = mysql_query ($query);
echo ("<form action=\"deleting2.php\" method=\"GET\">");
echo "<table id = 'table-3'>";
echo "<thead>";
echo "<th>Car ID</th>
<th>Car Name</th>
<th>Fuel Type</th>
<th>Transmission</th>
<th>Engine Size</th>
<th>Doors</th>
<th>Total</th>
<th>Available</th>
<th>Date Added</th>
<th>Delete</th> ";
echo "</thead>";
for ($i = 0; $i < mysql_num_rows ($result); $i ++)
{
$row = mysql_fetch_object ($result);
echo "<tbody>";
echo "<tr>";
echo "<td>$row->ID</td>";
echo "<td>$row->CARNAME</td>";
echo "<td>$row->FUELTYPE</td>";
echo "<td>$row->TRANSMISSION</td>";
echo "<td>$row->ENGINE_SIZE</td>";
echo "<td>$row->DOORS</td>";
echo "<td>$row->TOTAL</td>";
echo "<td>$row->AVAILABLE</td>";
echo "<td>$row->DATEADDED</td>";
echo "<td><input type='checkbox' name='delete[]' value='$row->ID' /></td>";
echo "</tr>";
echo "</tbody>";
}
echo ("<tr><td colspan='6' align='center'><input type=\"submit\" value=\"Delete \"></td> </tr></table></form>");
echo "</table>";
mysql_close ($link);
?>
Now,when I do press the delete button, it goes to my php page called 'deleting2.php' as mentioned in the form action, which has the following code:
<?php
$link = mysql_connect ("xxxx", "xxxx", "xxxx");
mysql_select_db ("xxxx");
$ID='$_GET[ID]';
// DELETE ANY RECORDS IN DATABASE
for ($i = 0; $i < #mysql_num_rows ($result); $i ++)
{
if(isset($_GET['delete[]']) && $_GET['delete[]']=='$row->ID');
{
$query=("DELETE FROM car WHERE ID='$_POST[ID]'");
$result1 = mysql_query($query);
}
}
mysql_close ($link);
?>
The problem is, it is NOT deleting anything from the my database. The URL in the address bar when the deleting2.php is being processed, is:
http://www.computing.northampton.ac.uk/~11430900/a1/webpages/deleting2.php?delete[]=6
Which according to my knowledge, selects the values that were ticket. Here, I had checked the box, which had a corresponding ID value of 6. So, check-box DOES work, it just does not do anything to the database, does not delete the value. I have tried many tutorials but I can't delete it using check-boxes. Any help would be much appreciated.
You don't need to itrate through following loop as mentioned in your question
for ($i = 0; $i < #mysql_num_rows ($result); $i ++)
{
if(isset($_GET['delete[]']) && $_GET['delete[]']=='$row->ID');
{
$query=("DELETE FROM car WHERE ID='$_POST[ID]'");
$result1 = mysql_query($query);
}
}
mysql_close ($link);
just to the following.
change your form method to POST.
use the following code. implode is necessary as $_POST['delete'] will be an array
if(isset($_POST['delete']) && count($_POST['delete']) > 0) {
$query=("DELETE FROM car WHERE ID in ('".implode(',',$_POST['delete'])."')");
$result1 = mysql_query($query);
}
Your data needs sanitizing but this should be Ok if you expect the ID to be a number:
$id = (int)$_GET['ID'];
$query=("DELETE FROM car WHERE ID=$id");
You really need to look at the rest of your code for SQL injection attacks.
First of all, be very carefull when implementing a database entries deletion as You could end up with empty database.
Secondly, always sanitize Your input to prevent SQL Injection.
Thirdly, learn PDO or at least mysqli_* functions instead of mysql_ as they are deprecated now and could be removed with any next PHP release.
Now, to Your problem, You are setting the ID values into a delete[] array value, that means You should do this:
// DELETE THE DESIRED RECORDS IN DATABASE
foreach($_GET['delete'] as $id) {
$result = mysql_query("DELETE FROM car WHERE ID = '" . mysql_real_escape_string($id) . "'");
// do something with the $result here ...
}
Other option could be to expect only integers:
// DELETE THE DESIRED RECORDS IN DATABASE
foreach($_GET['delete'] as $id) {
$result = mysql_query("DELETE FROM car WHERE ID = '" . (int)$id . "'");
// do something with the $result here ...
}

loop through database and show in table

I am trying to loop though my users database to show each username in the table in their own row. I can only get it to show one user but loops through this the number of rows there are. Code is below
<?php
require_once ('../login/connection.php');
include ('functions.php');
$query = "SELECT * FROM users";
$results=mysql_query($query);
$row_count=mysql_num_rows($results);
$row_users = mysql_fetch_array($results);
echo "<table>";
for ($i=0; $i<$row_count; $i++)
{
echo "<table><tr><td>".($row_users['email'])."</td></tr>";
}
echo "</table>";
?>
Thanks
mysql_fetch_array fetches a single row - you typically use it in a while loop to eat all the rows in the result set, e.g.
echo "<table>";
while ($row_users = mysql_fetch_array($results)) {
//output a row here
echo "<tr><td>".($row_users['email'])."</td></tr>";
}
echo "</table>";
You're only fetching one row:
$row_users = mysql_fetch_array($results);
You're never calling a fetch again so you're not really looping through anything.
I'd suggest changing your loop to the following:
echo "<table>";
while ($row = mysql_fetch_array($results)) {
echo "<tr><td>".($row['email'])."</td></tr>";
}
echo "</table>";
The while loop will loop through the results and assign a row to $row, until you run out of rows. Plus no need to deal with getting the count of results at that point. This is the "usual" way to loop through results from a DB in php.
In the new MYSQLI, I use this coding
$query = "SELECT * FROM users";
$results=mysqli_query($con,$query);
$row_count=mysqli_num_rows($results);
echo "<table>";
while ($row = mysqli_fetch_array($results)) {
echo "<tr><td>".($row['id'])."</td></tr>";
}
echo "</table>";
mysqli_query($con,$query);
mysqli_close($con);
Your problem is in this line:
echo "<table><tr><td>".($row_users['email'])."</td></tr>";
You're echoing out a <table> tag again. Remove that so your code looks like this:
echo "<table>";
for ($i=0; $i<$row_count; $i++)
{
echo "<tr><td>".($row_users['email'])."</td></tr>";
}
echo "</table>";
You don't need to output a table within a table the way you're doing it.
$result = mysql_query("SELECT `email` FROM `users`");
$num_emails = mysql_num_rows($result);
echo "<table><caption>There are/is $num_emails email(s)</caption>";
while ($row = mysql_fetch_assoc($result)) {
echo "<tr><td>{$row['email']}</td></tr>";
}
echo '</table>';
Something like that should work.

Categories