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?
Related
I have a form where users can order multiple parts and an email alert is sent with the data. Everything works great, but when there are multiple parts ordered each item appears multiple times. I would like to have each item appear once, on its own line.
This is the PHP that is generating the table:
$requestpartnumberarraybr = implode("<br>", $requestpartnumber);
$requestpartdescriptionarraybr = implode("<br>", $requestpartdescription);
$requestpartquantityarraybr = implode("<br>", $requestpartquantity);
$requestpartpricearraybr = implode("<br>", $requestpartprice);
$warehousearraybr = implode("<br>", $warehouse);
$binarraybr = implode("<br>", $bin);
$onhandarraybr = implode("<br>", $onhand);
$availablearraybr = implode("<br>", $available);
foreach($requestpartnumber as $key=>$val) {
$message_middle.='
<tr>
<td>' . $requestpartnumberarraybr. '</td>
<td>' . $requestpartdescriptionarraybr . '</td>
<td>' . $requestpartquantityarraybr. '</td>
<td>' . $requestpartpricearraybr . '</td>
<td>' . $warehousearraybr . '</td>
<td>' . $binarraybr . '</td>
<td>' . $onhandarraybr . '</td>
<td>' . $availablearraybr . '</td>
</tr>';
}
That code produces this - note that there are multiple items in each row, and then they are repeated:
It's supposed to look like this, though, with each item just having one row to itself:
The issue you are experiencing is that you are concatenating every value in the list, and then for each element in the list you are displaying that concatenated value.
//Here you are compressing the array of part numbers into one variable with all the values in the list
$requestpartnumberarraybr = implode("<br>", $requestpartnumber);
...
//Here you loop over each item in the array
foreach($requestpartnumber as $key=>$val) {
...
//Here, in the loop, you write the variable that has all elements in the array
'<td align="center" style="border:1px solid black!important;"><font color="black">' . $requestpartnumberarraybr. '</font></td>'
So that's why it is happening.
As for what to do instead, it seems a little unclear how your information is coming in, but you should be able to simply use $val instead of $requestpartnumberarraybr when adding to your table variable, and for the other values you should be able to use $key on their arrays, like so: $requestpartdescription[$key].
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.
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!
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
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.