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!
Related
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 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?
I'm trying to populate a table with values extracted from a mysql table stored in a wordpress database.
I've successfully managed to populate the body of the table with the record's fields but I'm wanting to show the column name for each particular field as a header. Note, I'm wanting the headers on the left and values on the right, not above and below like a traditional table.
I've tried using "SHOW COLUMNS FROM $table_name" and also the mysqli_fetch_field_direct function but I can't work out a way of making it work in the format I'm looking for where it's part of a loop. I'm new to PHP so I'm sure it's pretty simple but I'm completely stuck.
My code is below, I've marked where I want to echo the field names.
What I basically want to acheive is a table like this:
column_1_name:field_in_column_1
column_2_name:field_in_column_2
column_3_name:field_in_column_3
...
Thanks for any help in advance!
<table class="widefat">
<tbody>
<?php
global $wpdb;
$table_name = $wpdb->prefix . "consultation";
$query = "SELECT * FROM $table_name WHERE id=$_GET[id]";
$results = $wpdb->get_results($query);
// Test if there was a query error
if (!$results) {
die ("Please select a user from the Consultation admin homepage");
} else {
foreach ($results as $record) {
foreach ($record as $field) {
echo "<tr><th>" . **THIS IS WHERE I WANT COLUMN NAME OF $field** . "</th><td> {$field}</td></tr>";
}
}}
?>
</tbody>
foreach($results as $key => $val){
echo '<tr><td>' . $key . '</td><td>' . $val . '</td></tr>';
}
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
Not sure if that was the best way to phrase what I'm trying to do. Here goes:
I want users to be able to show results form my DB based on three different tables, one at a time.
I have the queries ready, but only want to show one result on the page at a time, based on what the user clicks. The queries are based on 3 different tables. There is a Today table, a This Week table, and a This Month table.
So when a users clicks Today, I want to show the results from the Today table. When they click This Week, I want the results to switch to come from the This Week table. I'm assuming this can be done with a simple if-then logic in PHP.
Here's how I'm calling from the Today table:
<?php
global $wpdb;
$result = $wpdb->get_results('SELECT name, count FROM wp_celebcount_today');
foreach($result as $row) {
echo '<a href="http://www.celebrything.com/?s=' .
urlencode($row->name) . '&search=Search">' . $row->name .
'</a> - ' . $row->count . ' Posts<br/>';}
?>
I would call from the This Week table like so:
<?php
global $wpdb;
$result = $wpdb->get_results('SELECT name, count FROM wp_celebcount_thisweek');
foreach($result as $row) {
echo '<a href="http://www.celebrything.com/?s=' .
urlencode($row->name) . '&search=Search">' . $row->name .
'</a> - ' . $row->count . ' Posts<br/>';}
?>
This query is currently running from the page load. How do I insert logic to make it run from a click on "Today", "This Week", or "This Month"?
OK - Thanks for the help so far! I have this:
<div id="sidebar">
<div class="post">
<h2>
<font color="#333333">Most Popular Celebrities</font><br>
<font color="#333333">in last 24 hours</font>
<br>
<br>
Today
Week
Month
<?php
if (!in_array($table, array('today', 'week', 'month')) {
return false;
}
global $wpdb;
$result = $wpdb->get_results('SELECT name, count FROM wp_celebcount_' . $table);
foreach($result as $row) {
echo '<a href="http://www.celebrything.com/?s=' .
urlencode($row->name) . '&search=Search">' . $row->name .
'</a> - ' . $row->count . ' Posts<br/>';
}
}
showTable($_GET['table']);
?>
</h2>
</div>
</div>
<div class="clear"></div>
I'm getting this error:
Parse error: syntax error, unexpected '{' in /home/content/c/e/l/celebrything/html/wp-content/themes/celebrything/sidebar.php on line 16
You can make the code into a function, and choose the table via a request param. Like so below. Note I added in_array check to make sure the table is not any table.
Today
Week
PHP
function showTable ($table) {
if (!in_array($table, array('today', 'week', 'month')) {
return false;
}
global $wpdb;
$result = $wpdb->get_results('SELECT name, count FROM wp_celebcount_' . $table);
foreach($result as $row) {
echo '<a href="http://www.celebrything.com/?s=' .
urlencode($row->name) . '&search=Search">' . $row->name .
'</a> - ' . $row->count . ' Posts<br/>';
}
}
Call the function in your page.php:
if (empty($_GET['table'])) {
showTable($_GET['table']);
} else {
showTable('today');
}
You can make it based on URL parameters.
The link will look something like this: site.php?type=today.
Then, in your PHP script, you could for example do this:
if (isset($_GET['type']))
{
switch ($_GET['type'])
{
case 'today':
// Query and list for today
break;
case 'thisweek':
// Query and list for this week
break;
case 'thismonth':
default:
// Query and list for this month
break;
}
}
else
// Error handling here
EDIT: I made the example be more concrete and used a switch construct, because it allows to mess with the default case more easily.
This is now assuming that when an invalid type is given, the list for this month is displayed. I think that's what you want...
Let me ask you, though: Why exactly do you even have these three tables? Please tell me you're not using some sort of cron-like script to move items from the today table to the this week column and so on... If so, you should just do it in one table, with one date column.
EDIT 2: To fix your example code, though, you need to change the variable name from $table to $_GET['table']. You should also check whether the variable exists at all (by checking with isset($_GET['table'])).