Concept Help Needed: Tables and Displaying All Rows - php

I have an upload system in my site where users can upload files and write a brief description of them. Each upload has a corresponding SQL entry.
Another page on my site will then display every file uploaded along with some traits about that file
The question is:
How can create a table with a variable set of rows and how can I set a table to automatically populate the new rows?
I am capable with PHP but still a novice, weak with HTML (I use a wysiwyg) and completely inexperienced with Javascript.
Any nudge in the correct direction would be hugely appreciated...

In order to make the rows of your HTML table "dynamic" using PHP, you should use the foreach() control structure. For example, say you have some code to grab the data from the database and it returns it as an array or some sort of result statement that implements an Iterable interface (we'll call it $results), you can then:
<table>
<thead>
<tr>
<th>File Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<?php
foreach($results as $result)
{
// Start row
echo("<tr>");
echo("<td>" . $result->filename . "</td>");
echo("<td>" . $result->description . "</td>");
// End row
echo("</tr>");
}
?>
</tbody>
</table>

You can use a loop to populate the table based on results from a query of your database. Here's the code I use for one of my pages:
$result = $db->query_read("SELECT dice.RollID AS `Roll`, dice.Limit AS `Limit`,
dice.Value AS `Value`, dice.Dateline AS `Dateline`, dice.Comment AS `Comment`
FROM dice
ORDER BY Dateline DESC LIMIT 25");
// ###### MAIN CODE ######
$str = '<table>
<tr><th>ID</th><th>Roll</th><th>Time</th><th>Comment</th></tr>';
while ($resultLoop = $db->fetch_array($result)) {
$ID = $resultLoop["Roll"];
$roll = $resultLoop["Value"] . '/' . $resultLoop["Limit"];
$when = date('m-d-Y H:i:s', $resultLoop["Dateline"]);
$comment = $resultLoop["Comment"];
$str .= '<tr>
<td>' . $ID . '</td>
<td>' . $roll . '</td>
<td>' . $when . '</td>
<td>' . $comment . '</td></tr>';
}
$str .= '</table>';
echo $str;
One thing to note is that I use $db->* functions because it is integrated with a forum software. You should be using mysqli_* functions as found here: http://php.net/manual/en/book.mysqli.php

Related

Having troubles with viewing a product in PHP & SQL

I wanted to make an automatic table display all the products from the database, where you can click on its name and view the whole details of the product. And my idea was that it wouldn't bring you to another .php file, but rather you'll still be on the same page so you wouldn't waste time on creating multiple .php files of every products.
The problem is, whenever I click on a product, it wouldn't load the product's information (the only detail is the description by the way).
Error
Fatal error: Cannot use object of type mysqli_result as array in C:\wamp\www\goldenrod\index.php on line 56
This is the database connection:
<?php
//Database Connections
$dbc = mysqli_connect('localhost', 'root', '', 'lionsierra_db') or die("Cannot find specified server");
//Product Database
$db_products = "SELECT * FROM `products`";
$products = mysqli_query($dbc, $db_products);
?>
And this is the function:
<?php
//View product
if(isset($_GET['view_product'])) {
while($product=mysqli_fetch_assoc($products)) {
$products['ID'] = $_GET['view_product'];
//Display a product
echo "<p><span>
<span style='font-weight:bold;'>" . $products['ID']['name'] . "</span><br/>
<span>$" . $products['ID']['price'] . "</span><br/>
<span>" . $products['ID']['category'] . "</span><br/>
<span>" . $products['ID']['description'] . "</span>
</p>";
}
}
//View all products
echo '<table width="600" border="1" cellpadding="1" cellspacing="1">
<tr>
<th>Name</th>
<th>Price</th>
<th>Category</th>
</tr>';
while($product=mysqli_fetch_assoc($products)) {
echo "<tr>
<td><a href='./index.php?view_product=" . $product['ID'] . "'>". $product['name'] . "</a></td>
<td>" . $product['price'] . "</td>
<td>" . $product['category'] . "</td>
</tr>";
$ID = $product['ID'];
}
?>
I'm still fairly new to PHP and SQL, and it would be grateful if you guys could help me out.
The issue resides here:
if(isset($_GET['view_product'])) {
while($product=mysqli_fetch_assoc($products)) {
Looks like you're just re-using a MySQLI query here. Instead, you should be altering the query depending on the productID. Let's see what that looks like:
if(isset($_GET['view_product'])) {
//now let's build out our query
$view_product_statement = mysqli_prepare($conn, "SELECT * FROM products WHERE ID = ?");
mysqli_stmt_bind_param($view_product_statement, 'i', $_GET['view_product']);
mysqli_stmt_execute($view_product_statement);
mysqli_stmt_bind_result($view_product_statement);
while($product=mysqli_fetch_assoc($view_product_statement)){
//now $product holds reference to the one we're trying to view.
}
mysqli_stmt_close($view_product_statement);
}
I've used prepared statements in my above to help sanitize your user input in such a way that you help avoid SQL Injection.

LIMIT x, x and foreach do not work as expected

I am using two php classes.
The first one is database connection class, which is the following:
https://github.com/rorystandley/MySQL-CRUD-PHP-OOP
and seconds one is pagination class, which is the following:
https://github.com/daveismyname/pagination/
My code:
$db = new Database();
$db->connect();
$pages = new Paginator('30','page');
$db->select('mods'); // Getting mods table
$rows = $db->numRows(); // Get number of rows
$pages->set_total($rows); // Record number of rows to pagination class
$db->select('mods', '*', null, null, null, $pages->get_limit() ); // Make request to the database
$mods = $db->getResult(); // Ger result from the database
foreach ( $mods as $key => $mod) {
$key += 1;
echo '
<tr>
<td class="text-center">' . $mod['id'] . '</td>
<td data-id="' . $key . '">' . $mod['full_name'] . '</td>
<td class="text-center">' . $mod['short_name'] . '</td>
</tr>
';
}
By the documentation of pagination class I am doing everything correctly, however, I had to change this function public function get_limit().
I have removed word LIMIT from there in order to use it in function $db->select() of database class. select() function is represented in this file - mysql_crud.php of database class from the link above on line 95.
Main problem of the loop is about breaking data from the database into part.
For example, if I break by 30 results, the first ?page=1 would give me all result from the database - so from id=1 to id=$rows, ?page=2 would result of showing all results from mods table starting from id=31 row and going up to id=$rows.
How can I fix this? Is it bug of the database class?
Thank you for help in advance!

Syntax for displaying one variable in PHP of SQL query

I was practicing making some sort of phonebook for my contacts and I ran into a problem when displaying the information in a table that is dynamically created using PHP. The table displays a row for each type of phone a person posses, for example for the house, cellphone and so on.
For that I made multiple functions that get information out of a database, but then I realized that I cannot think of a way to to return just the one variable I need (the number) because my select is also taking the id of the contact and of the type of phone to retrieve the number.
So my question is: How can I write in the PHP function that I only want to display the field for the phone number (numeroTelefono).
To further illustrate here is mySQL queries and PHP functions:
PHP function that creates the HTML and display the information the query gets:
function displaySpecificTels(){
if(isset($_POST['pIdC'])){
$idC = $_POST['pIdC'];
$casa = getSpecificCasa($idC);
$movil = getSpecificMovil($idC);
$trabajo = getSpecificTrabajo($idC);
$fax = getSpecificFax($idC);
$otro = getSpecificOtro($idC);
while($row = mysql_fetch_assoc($PLACEHOLDER)){
Perhaps remove the while and just echo? If so then what do I write where $row was?
echo
'<table class="tableFormat2 floatLeft">
<thead>
<tr>
<th>Casa</th>
<th>Móvil</th>
<th>Trabajo</th>
<th>Fax</th>
<th>Otro</th>
</tr>
</thead>
<tbody>
<tr>
<td>' . $row['casa'] . '</td>
<td>' . $row['movil'] . '</td>
<td>' . $row['trabajo'] . '</td>
<td>' . $row['fax'] . '</td>
<td>' . $row['otro'] . '</td>
</tr>
</tbody>
</table>';
}
}
}
SQL example of one of my functions:
function getSpecificCasa($idCont){
$id = 1;
$query = "SELECT bk.idTelefono , bk.idTipoTelefono, bk.numeroTelefono FROM telefono as bk WHERE bk.idTipoTelefono = $id AND bk.idTelefono = $idCont";
$result = do_query($query);
return $result;
}
EDIT:
Do_Query function does this:
function do_query($query){
global $db_server;
$result = mysql_query($query , $db_server);
if( !$result)
die("Falló la sentencia" . mysql_error());
return $result;
}
Would just returning bk.numeroTelefono and then using $result in the PHP that creates the HTML be viable?

Only one result showing after sql request and while loop

For some reason this only shows the last result, instead of showing all. The SQL works in the workbench, and $roommate is escaped, but the code has been trimmed for posting purposes:
$sql = "SELECT CONCAT(clients.studentFirstName, ' ', clients.studentLastName) AS name, appointments.location, appointments.subLocation, appointments.startTime, appointments.endTime, appointments.date
FROM appointments JOIN clients
ON appointments.clientID = clients.clientID
WHERE CONCAT(clients.studentFirstName, ' ', clients.studentLastName) = '".$roommate."';";
while ($row = mysql_fetch_array($result)) {
echo
'<table>
<tr>
<td>'
.$row["name"].
'</td>
<td>'
.$row["location"].
'</td>
<td>'
.$row["subLocation"].
'</td>
</tr>
<tr>
<td>'
.$row["startTime"].
' - </td>
<td>'
.$row["endTime"].
'</td>
<td>'
.$row["date"].
'</td>
</tr>
</table>';
}
Use mysql_num_rows() to determine the number of rows that were returned by your query. If it reports that you are only getting 1 result, then you will need to refine your query to get the number of results you intend.
If you're using one of the mysql_fetch_* functions before the while loop, that would advance the cursor and make you miss one or more results in your while loop. If that's the case, call mysql_data_seek($result, 0) before the while loop.

using php to fill in an existing table

I have a blank html table (column) on my page. I have a csv file with last years info for
that column available, but I don't want to initially write those values into the table
cells (because there might be new info which needs to be manually entered). I would like
to make a button which would populate this column. What would be the best way of going
about this? Since I want the info entered dynamically I would obviously need to use an
ajax call, and I would call a php file because that has a useful function fgetcsv(), but
can I use this function to enter info into a existing table? I was able to use php to
CREATE a table with this info, but as far as I understand, php has no knowledge of the
DOM... I would have to somehow package the entire column info and have javascript do the
job but I'm a little confused as to how...
Below is a snippet of how I used php to CREATE my table.
$file = fopen("SGS_Fall_Booklist.csv", "r");
$entry= fgetcsv($file);
echo $entry[0] . $_GET["program"] . $entry[1] . $GET["school"] .
$entry[2] . $GET["term"];
echo "<br>AutoFill (last years ISBN's)<br><input id='checkall' type='checkbox' </input>";
echo "<table><tr>
<th>Edit</th>
<th class='coursename'>" . $entry[6] . "</th>
<th class='startdate'>" . $entry[7] . "</th>
<th class='booktitle'>" . $entry[17]. "</th>
<th class='author'>" . $entry[18]. "</th>
<th class='isbn'>" . $entry[16]. "</th>
</tr>";
while(! feof($file))
{
$entry = fgetcsv($file);
echo "<tr>
<td><input type='checkbox'></input></td>
<td class='coursename'>" . $entry[6] . "</td>
<td class='startdate'>" . $entry[7] . "</td>
<td class='booktitle'>" . $entry[17]. "</td>
<td class='author'>" . $entry[18]. "</td>
<td class='isbn'></td>
</tr>";
}
echo "</table>";
fclose($file);
So here's a few things you can do:
(worst) Send the entire table back in the ajax call to PHP, and then let php add your column, and return the updated table (bad plan, lots of unchanged data transferring)
(better) Ajax call to return an entirely new table with your new column (better)
(best) Ajax call to fetch an array or object with your data and then use javascript to iterate over the table and add the data
Pseudo code:
//do your ajax request
foreach(newColumnValues AS key=>value) {
foreach(document.getElementByID("yourtable").elements) {
//If the ordering can change, check the key first, otherwise you could
//just go through every element
if(element[0] == key) {
element[1] = value;
}
}
}
Good luck!
If you have the code above print your ajax response you can then just do this on your javascript:
document.getElementById('container-id-here').innerHTML(your_ajax_response_text);

Categories