Many people will think this is a duplicate question and answers to such question is already given.But I have a different problem, here I don't know the number of columns and name of columns!
I have a text input type in html in which a user can directly manipulate database. User can query any table in database. All tables have different column names and number of columns. And i can't use 'describe' and 'show column' sql statement since name of the column is unknown.
All the answers to this question considers programmer already know column name
and number of columns in table.
So the question is:
how to get number of columns in table?
how to get column names of table to display it in table heading tag?
You can use DESC TABLE_NAME.
Itere the return to know the amount of fields.
Use SHOW COLUMNS FROM your_table_name_here and when you fetch the results the count of the number of rows will tell you how many columns there are.
Part of the data that is returned includes in the name of the columns which you may use for your table headings.
$ColsQ = $yourdb->prepare('SHOW COLUMNS FROM ' . $your_table_name_here);
$ColsQ->execute();
$ColsD = $ColsQ->fetchAll(PDO::FETCH_ASSOC);
echo 'There are ' . count($ColsD) . ' columns in the table';
foreach ($ColsD as $Column) {
echo 'Column name is ' . $Column['Field'];
}
So i got the answer of my question from php documentation! Here i will post snippet of my code which executes 'select' SQL statement written run-time which shows header plus records of table from result i got from executing query.
if(strcmp($words[0], "select")==0) //for making sure its select statement
{
$result= mysqli_query($conn, $sql);
if($result)
{
echo '<table border=1 style="border-collaspe=collaspe" class="table table-striped table-bordered table-hover dataTable no-footer">';
echo '<tr>';
for($i=0;$i<mysqli_num_fields($result);$i++)
{
$column_info=mysqli_fetch_field_direct($result, $i);
/*this function returns all the information about table metioned in the query.
variable i over here refers to field no*/
echo "<th>".$column_info->name."</th>"; //here fetching only name from whole information
}
echo '</tr>';
while ($row = mysqli_fetch_array($result))
{
echo '<tr>';
for($i=0;$i<mysqli_num_fields($result);$i++)
{
echo '<td>'.$row[$i].'</td>';
}
echo '</tr>';
}
echo '</table>';
}
else
{
echo "<script>alert('Error occured, Please check your syntax or internet connection')</script>";
}
}
For detailed information:
PHP Documention page for mysqli_fetch_field_direct ( mysqli_result $result , int $fieldnr ) function
Related
I'm still a novice with PHP and MySQL but willing to learn and now I'm in need of help after three days of tinkering.
First, to help you understand my db structure, I have a MySQL db table named "o70vm_invoices_items" and I'm trying to loop through the results that are for each invoice_ID. Each item in the items table has a PK (o70vm_invoices_items.id) and the invoice_ID column is a link to another table (invoices).
In the items table, for example, some invoices would have one item, others could have two or three items. I'm feeling quite challenged with how to loop through to display all of the items (o70vm_invoices_items.name) associated with each invoice.
Here is my MySQL query statement:
$queryItems = "SELECT
o70vm_invoices_items.id AS 'Item_ID',
o70vm_invoices_items.invoice_id AS 'Invoice_ID_on_Items',
o70vm_invoices_items.name AS 'Program',
o70vm_invoices_items.value AS 'Fee',
o70vm_invoices_items.amount AS 'Qty',
o70vm_invoices_items.desc AS 'forWeek',
GROUP_CONCAT(o70vm_invoices_items.desc SEPARATOR ' & ') As 'forWeekGroup',
ROUND(SUM((o70vm_invoices_items.value)*(o70vm_invoices_items.amount)),2) AS 'INV-TOTAL'
FROM o70vm_invoices_items
WHERE o70vm_invoices_items.invoice_id = $invoiceID
GROUP BY o70vm_invoices_items.invoice_id";
As you can see, I'm searching the results from INVOICE_ID. This part works great. I get these results to display easy. The problem is I'm looking to display each value in the "o70vm_invoices_items.name" column for the selected Invoice ID AND I can only display one item.
Here is my attempt to loop through the results and display the info:
// storing the result of this MySQL query
$resultItems = mysql_query($queryItems) or die(mysql_error());
echo "<table><tr>";
while($rowItems = mysql_fetch_array($resultItems))
{
echo "<td>";
echo "<input type='text' title='' name='name' id='name' value='". $rowItems['Program']. "' /><br>";
echo "</td>";
}
echo "</tr></table>";
Again, I can only get the result of one item, not all the items. Any help, very much appreciated. I think I may need a different way to write an Array perhaps. Also, as you can see, I'm displaying it in a input tag that I am hoping I will later be able to EDIT the content.
PLEASE NOTE: Once I have this figured out, I will also need to do the same for Fee and Qty columns as well.
Firstly I would rewrite the sql so that it appears easier to read, to do that assign an alias to the table and use that when referencing the fields. This is especially useful when you are joining multiple tables - each alias must be unique. In the case of your original sql because you are only drawing data from one table there is no need really for an alias nor to use the full table name as a prefix to the individual fields (ie: table.field ) - just the fieldname would have sufficed.
<?php
$queryitems = "select
o.`id` as 'item_id',
o.`invoice_id` as 'invoice_id_on_items',
o.`name` as 'program',
o.`value` as 'fee',
o.`amount` as 'qty',
o.`desc` as 'forweek',
group_concat( o.`desc` separator ' & ' ) as 'forweekgroup',
round( sum( ( o.`value` ) * ( o.`amount` ) ),2 ) as 'inv-total'
from `o70vm_invoices_items` o
where o.`invoice_id` = '$invoiceid';";
// storing the result of this MySQL query
$resultItems = mysql_query( $queryItems );
if( $resultItems ){
echo '
<table>
<tr>
<th scope="col">ID</th>
<th scope="col">Program</th>
<th scope="col">fee</th>
</tr>';
$id=0; /* Each field / element that has an id must have a unique id ~ use a counter to achieve this */
while( $row = mysql_fetch_object( $resultItems ) ){
$id++;/* Increment the id counter */
echo '
<tr>
<td>'.$row->item_id.'</td>
<td>
<input type="text" title="'.$row->program.'" name="name" id="name'.$id.'" value="' . $row->program. '" />
</td>
<td>'.$row->fee.'</td>
</tr>';
}
echo '
</table>';
} else {/* Do not give away too much information and degrade gracefully */
echo 'Sorry, there was an error retrieving relevant information from the database';
}
?>
Your query contains these two lines. Together they guarantee you'll get only one row in your resultset.
WHERE o70vm_invoices_items.invoice_id = $invoiceID
GROUP BY o70vm_invoices_items.invoice_id
Your WHERE line filters your table so the resultset only contains rows for a particular invoice_id value. Then, GROUP BY summarizes the information for that particular value in one result-set row.
From your question it sounds like you have multiple items per invoice, and you wish to show detail rows for the items. In that case you're going to need to group by the items, not the invoice_id.
Try this GROUP BY.
GROUP BY o70vm_invoices_items.id
And, you are using a very confusing nonstandard MySQL extension to the GROUP BY functionality. If you start working with more than one table, this will bite you hard. Read about it. https://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html
I am using PHP to display a row from MySQL table based on the user input.
Since the table has many columns, I retrieve a lot of columns, for which the user has to scroll right to see all the data.
I am using the following code to display the content to the page.
$sql2="select * from student_information where student_id='$id'";
$result2=mysqli_query($conn,$sql2);
if($result2->num_rows > 0){
echo '<table width="100%" bgcolor="#FFFFFF" cellpadding="0" cellspacing="0" border="1" class="db-table">';
echo '<tr><th>STUDENT__FIRST_NAME</th><th>STUDENT__LAST_NAME</th><th>STUDENT_ID</th><th>ADDRESS</th><th>CITY</th><th>STATE</th><th>ZIP</th><th>COUNTRY</th><th>PHONE</th><th>DEPARTMENT</th><th>MAJOR</th>
<th>EMAIL</th><th>MAILING_ADDRESS</th><th>HEALTH_INSURANCE</th><th>CREDIT_HOURS</th><th>GROUP</th><th>GENDER</th><th>DOB</th><th>STATUS</th><th>NOTES</th><th>JOINED_ON</th></tr>';
while($rowz2 = mysqli_fetch_assoc($result2)){
echo "<tr>";
foreach($rowz2 as $key=>$value){
echo '<td>',$value,'</td>';
}
echo '</tr>';
}
echo "</table><br/>";
}
else {
echo "<h2>No data based on the entered values</h2>";
}
How can I break out of the output row and into two rows, so that the output row will be displayed in two parts, so that it fits the screen, without the need to scroll right.
You can't assume the user screen has any defined width. it can range from a cell phone to an ultra wide monitor... better your table stays one record per line.
You can use some css responsive table tricks though
Check this out https://css-tricks.com/examples/ResponsiveTables/responsive.php
How to display all the results from a table from MySQL via static PHP code when the table fields are not always the same?
Viable example:
I am working on a site that gives the user the option to create custom tables in the MySQL database via PHP code. There is also a page (with static PHP code) that should display the custom database tables in a HTML table using PHP code.
I use mysqli and not PDO.
Example code of what I know:
<?php
$db_table = mysqli_query($db_link,"SELECT * FROM custom_table");
while ($row = mysqli_fetch_field($db_table)) {
$column_name = $row->name;
?>
<th><?php echo $column_name; ?></th>
<?php
}
?>
The above will display all the column names, but how do I do to display all the column names and all the values from the table below this column names ?
I do not know all the row names, so I can't define them using $row1 = $row['table_field']; and then echo it into the HTML table.
$header=true;
$header_row=''; $row_data='';
while ($row = mysqli_fetch_assoc($db_table)) {
$row_data.='<tr>';
foreach($row as $key=>$value){
if($header){
$header_row.='<th>'.$key.'</th>';
}
$row_data.'<td>'.$value.'</td>';
}
$header=false; # stop after first run through as we have all header fields
$row_data.='</tr>';
}
echo '<table><tr>'.$header_row.'</tr>'.$row_data.'</table>';
didn't validate this but you should get the idea
I got this list of checkboxes that print out from database. I am able to retrieve data from database if user makes multiple checkbox and display it in table, but i cannot retrieved other information from database and display it in the same table.
This is my code:
<table border='1'>
<tr>
<th>TITLE</th>
<th>PERCENTAGE RESULT</th>
</tr>
<?php
if(isset ($_POST["submit1"]))
{
$selectedcheckbox = $_POST["selectedcheck"];
$query = "SELECT * FROM compareresult where subject=$selectedcheckbox";
$sql_query = mysql_query($query) or die('Error 3 :'.mysql_error());
while($data = mysql_fetch_array($sql_query,MYSQL_ASSOC)){
$result=$data['result'];
}
foreach($selectedcheckbox as $title)
{
echo "<tr>";
echo "<td>".$title."</td>";
echo "<td>".$result."</td>";
}
echo "</tr>";
}
?>
I want to display result after user select multiple checkbox, so I wrote:
echo $result in table
so that the result can be displayed in table beside the selected title, but I am getting an error:
Array to string conversion in C:\xampp\htdocs\sam\c.php on line 31 Error 3 :Unknown column 'Array' in 'where clause'
I am not at the moment in the environment to test your problem, and I do this out of my head, but try something like the following.
if(isset($_POST['submit1'])){
$checkbox = isset($_POST['selectedcheck']) ? $_POST['selectedcheck'] : array();
foreach($checkbox as $title){
$query = "SELECT * FROM compareresult where subject='".$title."'";
$result=mysql_query($query); // <-- to avoid SQL injections, please change your method from mysql_query to mysqli_query (use the mysqli functions instead of mysql)
while($data = mysql_fetch_array($result)){
$result=$data['result'];
echo "<tr>";
echo "<td>".$title."</td>";
echo "<td>".$result."</td>";
echo "</tr>
}
}
}
It checks first if your checkboxes are checked and if they are they put it in an array.
Then it runs the foreach statement, where it sets the checkbox value as title. It runs there if the query if it the title is in the database, if so, spit it out through the while loop. Rinse and repeat until done.
edit
I see you put your open tablerow statement in the foreach but close it outside. So either you want it all printed on one line or is it an error? If its on one line, make sure you open the table row BEFORE the while loop and end it AFTER, else it's like how i spit it out.
I have a table in Oracle with this columns: IMGPOSX, IMGPOSY and IDIMG. Each row of the table has a different X Y value positions and an ID to identify witch of this values correspond to an specified ID.
For example: IDIMG = image1 > IMGPOSX = 20 IMGPOSY = 50
With this value then I build a html map image and load the image with an specified ID and put the results of the IMGPOSX and IMGPOSY on the margin-top and margin-left css properties.
I have found several example of how to get the values of the first line of the row but i don't know how to get the another ones (the table has 12 rows)
With the next code I get the first row of each column (IMGPOSX, IMGPOSY and IDIMG) but i don't know how to get the rest of the rows of the table. If I put row1[1] the parser get an error.
<?php
$conn = oci_connect('TEST', 'TEST', 'ORCL');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, 'SELECT IMGPOSX, IMGPOSY, IDIMG FROM TESTTABLE ');
if(oci_execute($stid))
{
$row=oci_fetch_row($stid) ;
"<table border='2'>";
print"<tr><td><p>posx: </td><td>$row[0] </td></tr>";
print"<tr><td>posy: </td><td>$row[1] </td></tr>";
print"<tr><td>idimg: </td><td>$row[2] </td></tr>";
print"</table></br>";
}
oci_free_statement($stid);
oci_close($conn);
?>
Also I like to filter the results of the fetch by the idimg, for example, some code that says "showme only the IMGPOSX and IMGPOSY from the IDIMG='image2'.
A rough example could be appending a WHERE clause to your query:
$id = 'image2';
$stid = oci_parse($conn, "SELECT IMGPOSX, IMGPOSY, IDIMG FROM TESTTABLE WHERE IMDIMG = $id;");
or, with the same query, you can filter with IF:
if ($row[2] == $id) {
//show
}
The sentence before your code states that you could need more than one row, so if you are not filtering, you will recieve more, to get them you need a proper fetch. Your current one if fetch_row, maybe you need fetch_array in order to recieve array with all values.
I would suggest oci_fetch_assoc http://php.net/manual/en/function.oci-fetch-assoc.php so you can access the column via their names. Also the filtering will use a named column.
if ($row['IDIMG'] == $id) {
//show
}
Have in mind the following sentence of the function description:
This function is typically called in a loop until it returns FALSE
You'd need something like:
<?php
//all the code here
// ...
// ...
?>
<table border="2">
<?php while ($row = oci_fetch_assoc($stid)): ?>
<tr><td><p>posx:</p></td><td><?=$row['IMGPOSX'];?></td></tr>
<tr><td><p>posy:</p></td><td><?=$row['IMGPOSY'];?></td></tr>
<tr><td><p>idimg:</p></td><td><?=$row['IDIMG'];?></td></tr>
<?php endwhile; ?>
</table><br />
<?php
oci_free_statement($stid);
oci_close($conn);
?>