This question already has answers here:
Creating dynamic tables in HTML using MySQL and PHP
(2 answers)
Closed last year.
my task at he moment is to show the data from a sql db in a browser.
My code is fine for that, but now i have more and bigger sql tables and i am looking for a way to read and show it more dynamic. So that i dont have to write all the names of the column (the echo statements, if i have 100 columns it would not really work like this) in the code. Is there ab better way in this case?
Thanks.
<?php
error_reporting(E_ALL);
$db_link = mysqli_connect (MYSQL_HOST,
MYSQL_BENUTZER,
MYSQL_KENNWORT,
MYSQL_DATENBANK);
if ( $db_link )
{
echo('<p> Verbindung vorhanden: </p>');
}
else
{
echo('<p style="color:red"> Keine Verbindung vorhanden: </p>');
}
$db_res = mysqli_query($db_link, "SELECT AA, B1, C3 FROM tableXYZ")
or die("Fehler: " . mysqli_error());
echo("<table>");
while($row = mysqli_fetch_array($db_res))
{
echo("<tr>");
echo("<td>" . $row["AA"] . "</td>");
echo("<td>" . $row["B1"] . "</td>");
echo("<td>" . $row["C3"] . "</td>");
echo("</tr>");
}
echo("</table>");
?>
You could use a foreach loop to show all columns. Like this:
while($row = mysqli_fetch_array($db_res))
{
echo("<tr>");
foreach ($row as $column)
{
echo("<td>" . $column . "</td>");
}
echo("</tr>");
}
If this is not what you want you have to clarify, in your question, what you really want.
Related
I'm creating a cart system and trying to find a way to have a simple button that once pressed deletes the corresponding row. However, I cannot seem to find a way to dynamically do this with while loop I currently have.
<?php
//connect to DB.
$con = mysqli_connect("localhost", "root", "", "books");
if(mysqli_connect_errno())
{
echo "Failed to connect to MySql: ". mysqli_connect_error();
}
$query = "SELECT * FROM cart WHERE customerID = '$_SESSION['id']'";
$result = mysqli_query($con, $query);
//creates a table for dumping the DB to, loops through the DB and posts the contents elegantly.
echo "<table>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" . $row['bookAuthor'] . "</td><td>" . $row['bookTitle'] . "</td><td>" . $row['bookPrice'] . "</td></tr>";
$totalprice += $row['bookPrice'];
}
echo "</table>";
echo "The total present price is: $".$totalprice;
//closes the conncection to the DB
mysqli_close($con);
?>
I've considered trying to put an echo query statement into the database and adding "$row['deletebutton']" to the while loop but I'm not sure that would necessarily work.
The easy way is to create a new page and send the message to this page to delete the item.
So, in the table you add a new column with a link
delete
And in the page you treat this value.
To expand on the comment posted to the question, you could add this to your row:
echo "<tr><td>" . $row['bookAuthor'] . "</td><td>" . $row['bookTitle'] . "</td><td>" . $row['bookPrice'] . "</td><td><input type='checkbox' name='remove[]' value='" . $row['ROW_ID'] . "' /></td></tr>";
And then with the data submitted in the form you could do something like this:
$query = "DELETE FROM cart WHERE ROW_ID IN (" . implode(',',$_POST['remove']) . ")";
Keep in mind to check the value of remove before using it in queries.
I am populating a table using php from an array (populated by an mysql query). The table code I am using is:
<thead>
<tr>
<hr>
<th>UserName</th>
<th>Nick Name</th>
<th>Role</th>
<th>Unit</th>
<th>Active</th>
<th>Admin</th>
</tr>
</thead>
<tbody>
<?php
foreach ($portfolio as $row)
{
echo("<tr>");
echo("<td>" . $row["username"] . "</td>");
echo("<td>" . $row["nickname"] . "</td>");
echo("<td>" . $row["role"] . "</td>");
echo("<td>" . $row["unit"] . "</td>");
echo("<td>" . $row["active"] . "</td>");
echo("<td>" . $row["isadmin"] . "</td>");
echo("</tr>");
}
?>
I have been trying without luck to find a way to have the first column in the table a hyperlink that allows editing of that users details (IE redirects to another page/php). The array itself is being populated using this code:
//now lets get the user's stock info
foreach ($rows as $row)
{
$stock = lookup($row["username"]);
$stock["username"] = $row["username"];
$stock["nickname"] = $row["nickname"];
$stock["role"] = $row["role"];
$stock["unit"] = $row["unit"];
$stock["active"] = $row["active"];
$portfolio[] = $stock;
}
How can I make the results of the sql query / php a link within the table?
Thanks for the help, I am new to php/mysql and trying to find my feet;
Andy
You'll need to do something like the following, then on your user edit page you can get the username with $_GET['user']
<?php
foreach ($portfolio as $row)
{
echo("<td><a href='user-edit.php?user=" . $row["username"] . "'>" . $row["username"] . "</a></td>");
}
?>
Given an unique username ofc, else you can do it with the id or any unique field.
Why do you use $portfolio variable ? It just stock the data you already have in $rows.
Then, just use this :
echo '<td>
'. $row["username"] .'
</td>';
I think you have an user ID in your table ?
Simply changing this line
echo("<td>" . $row["username"] . "</td>");
to this
echo("<td>" . $row["username"] . "</td>");
will make the first column clickable. Of course you'll need to fill in the target of the link. Making the details editable is a lot more code though.
This question already has answers here:
Looping through mysql database
(3 answers)
Closed 8 years ago.
I have a mysql database with some tables, I did a php script that will print a table like this:
[user name]
[field 1][field 2][field 3]
[value 1][value 1][value 1]
...etc, containing "n" values from each field corresponding to the user name.
but what I want is to display this table for each user, a loop printing this table for every user in my database. I know I will have to do a loop before the tag right? but I don't know which conditions this loop will have,someone could help me showing me how to do this?
You can try something like this. Note that You'll have to add database connection information and change database and table names.
$db_name = 'database';
$table_name = 'table';
mysql_connect() or die("MySQL Error: ". mysql_error());
mysql_select_db($db_name) or die("MySQL Error: ". mysql_error());
$columns_q = mysql_query("SHOW COLUMNS FROM $table_name");
if(!$columns_q){
die("Error fetching columns $table_name: " . mysql_error());
}
echo '<table><tr>';
while($column = mysql_fetch_assoc($columns_q)){
echo '<td>' . $column['Field'] . '</td>';
}
echo '</tr>';
$fields_q = mysql_query("SELECT * FROM $table_name");
if(!$fields_q){
die("Error fetching fields $table_name: " . mysql_error());
}
while($fields = mysql_fetch_assoc($fields_q)){
echo '<tr>';
foreach ($fields as $key => $value) {
echo '<td>' . $value . '</td>';
}
echo '</tr>';
}
echo '</table>';
I am using php to connect to my ms sql server. I am using php 5.3, using the microsoft database dll to connect. The problem i have is that in my database, i have tables wich there column's names have blank spaces, mean there is a table called bills whit a column named "Shipper Code" or "Shipper name"... something like that... i want to know how i can read the rows using fetch_object
while($row = sqlsrv_fetch_object($stmt))
{
echo "<li>" . $row->Code . $row->MasterId . "</li>";
echo "<li>". $row->Shipper Code . "</li>"; <== HERE HOW I MUST PUT SHIPPER CODE?
}
Do i must use () or {} or []...
thank you in advanced!
You should avoid the usage of spaces in column or object names. If you wish to separate the strings then use an underscore _ instead. This will retain the readability and ensure that the item can be accessed properly.
Other than that you can use the following:
while($row = sqlsrv_fetch_object($stmt)) {
$results[] = $row;
echo "<li>" . $results['Code'] . $results['MasterId'] . "</li>";
echo "<li>". $results['Shipper Code'] . "</li>";
}
I've got the answer. I only need to use "{" and "}". Something like this
while($row = sqlsrv_fetch_object($stmt))
{
echo "<li>" . $row->{"Num"} . $row->{"MasterId"} . "</li>";
echo "<li>". $row->{"Shipper Code"}. "</li>";
}
Thanks for all your help.
Basicaly having issues setting up a webpage which will taken in a student key entered by the user. This will then parse the student key to another file which will run it against a mysql backend to see what records this student already has. But can not get it working for the life of me please help I'm still a newb at this.
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("support_log", $con);
$result= mysql_query("SELECT student.first_name, student.surname, student.year_group, student.STKEY, student_log.issue
FROM `student` JOIN `student_log`
WHERE student.STKEY like '$_POST[stkey]'");
$result2 = mysql_query($result) or die("Error: " . mysql_error());
if(mysql_num_rows($result2) == 0){
echo("no records found");
} ELSE {
echo "<table border='1'>
<tr>
<th>First name</th>
<th>Surname</th>
<th>Year Group</th>
<th>Student Key</th>
<th>Issue</th>
</tr>";
while($row = mysql_fetch_array($result2))
{
echo "<tr>";
echo "<td>" . $row['First_Name'] . "</td>";
echo "<td>" . $row['surname'] . "</td>";
echo "<td>" . $row['year_group'] . "</td>";
echo "<td>" . $row['stkey'] . "</td>";
echo "<td>" . $row['issue'] . "</td>";
echo "</tr>";
}
echo "</table>";
}
mysql_close($con);
?>
After changing my where statement to:
WHERE student.STKEY like '$_POST[stkey]'");
I am no longer reciving errors from PHP but now recieving the error Query was empty which is part of my code to detect if there is no results. Though I have tested that query in phpmyadmin and it spits out results. From looking at the code does anyone have any solutions? I have also checked the parse by running an echo on the post command to ensure the data being entered was correct.
Edit: Got rid of the whole result2 check now throwing a:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\stkey_submit.php on line 24
Try $_POST['stkey'] instead of $_POST[stkey]
EDIT : if you use it in a query, it would be preferable to do :
$stkey = mysql_real_escape_string($_POST['stkey']);
$sql = "SELECT ....... like '$stkey'";
mysql_query($sql);
$result= mysql_query("SELECT student.first_name, student.surname, student.year_group, student.STKEY, student_log.issue
FROM `student` JOIN `student_log`
WHERE student.STKEY like " . $_POST["stkey"]);
How about storing the value of stkey on a variable before including it on the query?
$stkey = $_POST['stkey'];
$result= mysql_query("SELECT student.first_name, student.surname,
student.year_group, student.STKEY, student_log.issue
FROM `student` JOIN `student_log`
WHERE student.STKEY LIKE '%$stkey%'");
You might also want to use MySqli or PDO instead of the MySql database API. Take a look at this post from Nettuts: http://net.tutsplus.com/tutorials/php/php-database-access-are-you-doing-it-correctly/