Printing out MySQL tables in HTML - php

I am currently using the code below to print out a MySQL table. However, when I am printing multiple rows the format is pretty ugly. What is a way or command I could create columns similar to the Tab key to make it more aesthetically pleasing?
$google= mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($google)){
foreach($row as $cname => $cvalue){
print "$cvalue\t <tr>";
}
print "<br>";
}
The query is printed using user input. using the
<form action="google.php" method="post">
command. I am also looking for a way to print this table on the same page as the HTML page that I accept the user input.

Your code is pretty good and only needs HTML added to it to make it look nicer. Using tables (this has not been tested but it should work):
$google = mysqli_query($query) or die(mysqli_error());
echo '<table>';
while($row = mysqli_fetch_assoc($google)) {
echo '<tr>';
foreach($row as $cvalue) {
print '<td>'.$cvalue.'</td>';
}
echo '</tr>';
}
echo '</table>';
This is a quick and dirty way to output a MySQL table, but if you also want the names of the columns to show up, things get quite a bit trickier. Also, if your results contain special characters such as ">", this can mess up the output. If that happens, just look up the documentation for htmlspecialchars().
If you want this table to show up on the same page as your form, just create a submit button and check the value in PHP like so:
if (isset($_POST['SubmitButtonNameHere']) { ... }
I'm not sure of the structure of your form so this code might need to be different to determine whether the form has been submitted. You can put the code for creating the table inside of the curly braces and place the code for your form either above or below the if statement.
<tr> is an HTML element used to add rows to a <table> element. The <td> element adds cells to those rows. Also, your code was using mysql_*. This was changed to mysqli_* as the mysql prefix is deprecated in PHP. Hope this answers your question.

Just use this code instead :)
$google= mysql_query($query) or die(mysql_error());
echo "<table><tbody>";
while($row = mysql_fetch_assoc($google)){
foreach($row as $cname => $cvalue){
echo "<tr><td>".$cname."</td><td>".$cvalue."</td></tr>";
}
echo "</tbody></table>";
Done :)

Related

php populate option box from database table

I am writing code to register a new project via a html form. I want to be able to click a dropdown box which pulls the values from a table on the database.
At the moment a dropdown box displays but with no values.
PLEASE NOTE: I am a learning the basics so apologies if this is a simple question/answer scenario.
My code is below, any help is appreciated, I connect to the database via a php include script. The table is called 'customers' and the item I want to list is 'name';-
<?php
$result = mysql_query("SELECT customers FROM name");
echo "<select name='client'>";
while($row = mysql_fetch_assoc($result))
{
echo "<option value = '".$row[name]."'>".$row[name]."</option>";
}
echo "</select>";
?>
"The table is called 'customers' and the item I want to list is 'name';" -
Do SELECT name FROM customers instead of SELECT customers FROM name
Using mysql_error() to mysql_query()
would have shown you the error that the table name does not exist.
Plus,
[name] are missing quotes inside them => ['name'] which are being treated as constants.
in
echo "<option value = '".$row[name]."'>".$row[name]."</option>";
as caught and kudos to devdesign
echo "<option value = '".$row['name']."'>".$row['name']."</option>";
However, you are using a deprecated MySQL library. If you are still not getting results, then this could mean that you need to use (and should use) mysqli_ or PDO instead.
Here are a few links on the subject:
mysqli with prepared statements
PDO with prepared statements.
Your code should be. Also note the single quotes within $row['name']. You missed that.
<?php
$result = mysql_query("SELECT name FROM customers");
echo "<select name='client'>";
while($row = mysql_fetch_assoc($result))
{
echo "<option value = '".$row['name']."'>".$row['name']."</option>";
}
echo "</select>";
?>

Echoing an Array as options inside a select box

I'm trying to create a select box full of options based on data from an array that is built from an sql query, I've tried researching where I'm going wrong but the closest I've managed to get is echoing alot of empty option boxes my code is as follows:
$result = mysqli_query($cons,"SELECT user_name FROM users");
while($row = mysqli_fetch_array($result)){
foreach($row as $key => $value){
echo '<option value="'.$value.'"</option>';}}
If anybody could point me in the right direction that would be great.
EDIT: I can't believe it was something as simple as that! Thank you very much.
On a separate note It's actually giving all of the data twice.
I'll mark as correct answer as soon as I can.
echo '<option value="'.$value.'">'.$value.'</option>';
or
echo "<option value=\"{$value}\">{$value}</option>";
You never closed the opening option tag. If you view your source you'll see it's wonky.
BTW, You don't need the value="" part if you're using the same value in the text of the option.
echo "<option>{$value}</option>";
Entire code as I would do it
$result = mysqli_query($cons,"SELECT user_id, user_name FROM users");
while($row = mysqli_fetch_assoc($result)){
echo "<option value=\"{$row['user_id']}\">{$row['user_name']}</option>";
}

PHP INSERT a variable number of records to mysql from a html form

I have a HTML form that retrieves a varying number product types that the user inputs stock figures. This data then needs to be INSERTED to a new table.
Here is the PHP query that populates the form.
require_once 'config.php';
$i = 1;
$sql = "SELECT * FROM dealer_product WHERE customer_code='$custcode' ORDER BY prod_code";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
$prodcode = $row['prod_code'];
echo "<tr><td><input type='text' name='prod".($i++)."' value='" . $prodcode . "'/></td><td><input type='number' name='openstock".($i++)."'/></td><td><input type='number' name='sold".($i++)."'/></td></tr>";
}
mysql_close($con);
?>
I know how to INSERT a set number of multiple records, but how do I INSERT a varying number of records?
Thanks in advance. Sorry for my basic knowledge, I'm a network admin not PHP MYSQL.
Name your input fields as if they were arrays, e.g.:
<input name="prods[0]" />
You can then output a variable number of inputs in your HTML, even add more with JavaScript. PHP will convert the input to an array over which you can iterate:
<?php
foreach ($_POST['prods'] as $prod) {
/* Process $prod */
}
?>
I recommend that you go in the same way but using
while ($row = mysql_fetch_assoc($result))
And now you have not numbers as index that is more complicated way to see things, better see associative way that's the column name from your table in mysql.
And you're doing a lot of increments there doing $i++ a lot of times. I don't know if you're doing that intentionally but if not just increment $i once.
Also the number of row can be reached using this:
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
Look inside the manual
http://us1.php.net/mysql_fetch_assoc

anchor tag is not working in php and html is rendered from other file

I am trying get data from a database and pasting it on a webpage in table form and in each table data there are names which have other details in database which I also have to show on other webpage if that name is clicked. I got stuck when anchor tag is not working.
NOT WORKING means that name in anchor tag is like normal text not link, though text turns blue with underline but its not acquiring its linking property.
Table in which I am getting data from database is working plus I am also trying to give anchor tag to table data which are simple names which would link to another file.
I am using 2 file one is .php and other is .html of same name.
Here are some of the LOC I am using and related to this. I have omitted other 3 columns.
file.php
<?php
...
$query="select name from table1 order by name";
$rs=mysql_query($query);
$table = '<table>';
while ($row = mysql_fetch_array($rs))
{
$cname = $row["name"];
$table .= '<tr>
<td>'.$cname.'</td> /*<a></a> not working*/
</tr>';
}
$table .= '</table>';
include_once 'file.html';
?>
file.html
<html>
<body>
<form>..</form> /*passes user input to PHP file1*/
<p><?php echo $table;?></p>
</body>
</html>
Html is rendered from html file.
file3.php is the page which I am trying to link through names.
I am using XAMPP 1.7.7 and PHP 5.3.8
Any useful suggestion?
Look at your query, you are using cname as an index for $row and your query fetches name
$query="select name from table1 order by name";
--^--
$cname = $row["cname"];
--^--
Is your error reporting turned off? You should get an error for this.. FOR SURE
Note: You should stop using mysql_() as it will be deprecated soon,
start using mysqli_() or PDO instead...
I prefer use 'mysql_fetch_assoc' to 'mysql_fetch_array.
2. Check if the table has values.
3. change '$row["cname"]' to '$row["name"]'
This is your code
$table .= '<tr>
<td>'.$cname.'</td> /*<a></a> not working*/
</tr>';
Just replace the single quote by double quotes
You just need to replace this code with following code:
$table = "";
while ($row = mysql_fetch_array($rs))
{
$cname = $row["name"];
$table .= "<tr>
<td><a href='file3.php'>$cname</a></td>
</tr>";
}
$table .= "</table>";
This code will print actual variable $cname value from your database
Please try this.

Is it possible to Query a Mysql database from a field selected from dropdown menu populated from a Query in php

Hello i am new to php and i have tried to find a piece of code that i can use to complete the task i need, i currently have a page with a form set out to view the criteria of a course. also i have a dropdown menu which currently holds all the course codes for the modules i have stored in a database. my problem is when i select a course code i wish to populate the fields in my form to show all the information about the course selected. The code i am trying to get to work is as follows:
<?php
session_start();
?>
<? include ("dbcon.php") ?>
<?php
if(!isset($_GET['coursecode'])){
$Var ='%';
}
else
{
if($_GET['coursecode'] == "ALL"){
$Var = '%';
} else {
$Var = $_GET['coursecode'];
}
}
echo "<form action=\"newq4.php\" method=\"GET\">
<table border=0 cellpadding=5 align=left><tr><td><b>Coursecode</b><br>";
$res=mysql_query("SELECT * FROM module GROUP BY mId");
if(mysql_num_rows($res)==0){
echo "there is no data in table..";
} else
{
echo "<select name=\"coursecode\" id=\"coursecode\"><option value=\"ALL\"> ALL </option>";
for($i=0;$i<mysql_num_rows($res);$i++)
{
$row=mysql_fetch_assoc($res);
echo"<option value=$row[coursecode]";
if($Var==$row[coursecode])
echo " selected";
echo ">$row[coursecode]</option>";
}
echo "</select>";
}
echo "</td><td align=\"left\"><input type=\"submit\" value=\"SELECT\" />
</td></tr></table></form><br>";
$query = "SELECT * FROM module WHERE coursecode LIKE '$Var' ";
$result = mysql_query($query) or die("Error: " . mysql_error());
if(mysql_num_rows($result) == 0){
echo("No modules match your currently selected coursecode. Please try another coursecode!");
} ELSE {
Coursecode: echo $row['coursecode'];
Module: echo $row['mName'];
echo $row['mCredits'];
echo $row['TotalContactHours'];
echo $row['mdescription'];
echo $row['Syllabus'];
}
?>
however i can only seem to get the last entry from my database any help to fix this problem or a better way of coding this so it works would be grateful
Thanks
The main error is in your final query, you're not actually fetching anything from the query, so you're just displaying the LAST row you fetched in the first query.
Some tips:
1) Don't use a for() loop to fetch results from a query result. While loops are far more concise:
$result = mysql_query(...) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
...
}
2) Add another one of these while loops to your final query, since it's just being executed, but not fetched.
For me i would use some javascript(NOTE: i prefer jQuery)
An easy technique would be to do this(going on the assumption that when creating the drop downs, your record also contains the description):
Apart from creating your dropdown options like this <option value="...">data</option>, you could add some additional attributes like so:
echo '<option value="'.$row['coursecode'].'" data-desc="'.$row['description'].'">.....</option>
Now you have all your drop down options, next is the javascript part
Let's assume you have included jQuery onto your page; and let's also assume that the description of any selected course is to be displayed in a <div> called description like so:
<div id="course-description"> </div>
<!--style it how you wish -->
With your javascript you could then do this:
$(function(){
$("#id-of-course-drop-down").change(function(){
var desc = $(this).children("option").filter("selected").attr("data-des");
//now you have your description text
$("#course-description").html(desc);
//display the description of the course
}
});
Hope this helps you, even a little
Have fun!
NOTE: At least this is more optimal than having to use AJAX to fecch the description on selection of the option :)

Categories