I've got something like this, the function allows me to display data from the database "demo", from "products" table:
class Product
{
private $conn;
private $id;
private $name;
private $description;
private $price;
private $category_id;
private $category_name;
private $created;
public function __construct($db)
{
$this->conn = $db;
}
public function readAll()
{
$stmt = $this->conn->prepare('SELECT name, description, price, CategoryID, created FROM products');
$stmt->execute();
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
$n = $result['name'];
$d = $result['description'];
$p = $result['price'];
$ca = $result['CategoryID'];
$c = $result['created'];
echo $n . " - " . $d . " - " . $p . " - " . $ca . " - " . $c . "<br />" . "<br />";
}
}
}
Here is my database connection:
class Database {
public function getConnection() {
$result = false;
try {
$result = new PDO('mysql:host=localhost;dbname=demo', 'root', '');
} catch(PDOException $e) { }
return $result;
}
}
$db = new Database();
$conn = $db->getConnection();
if (!$conn) {
die("Error connecting to the database");
}
I can display data like this:
<div>
<h3>readAll:</h3>
<form action="" method="post">
<label>Products: <br /> (Name - Description - Price - Category ID - Creation date): </label><br />
<?php
$cat = new Product($conn);
echo $cat->readAll();
?>
</form>
</div>
But how can I display data from the database in a table?
Here's a clue, and it all depends on how your php is structured.
Just before the while loop,
echo '<table>';
// you can add table head if you please
While(...){
$a = $row['...'];
echo '
<tr><td>'.$a.'</td></tr>
';
//you can add as many columns as you wish
}
echo '</table>
I hope you picked understanding from this
Here's a simple way to achieve what you're trying. But before that, let's discuss a for a moment your approach to the application you're building.
First. It's not a good practice to construct the html in your php code. The best way you can go about it is to prepare the data for presentation and simply provide the presentation layer with this data (for a much broader explanation of this mindset, take a look at the MVC pattern).
So, let's prepare the data. In your function, where you get the products, simply return them.
public function getAll()
{
$stmt = $this->conn->prepare('SELECT name, description, price, CategoryID, created FROM products');
$stmt->execute();
$allProducts = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $allProducts;
}
I've also renamed the function, because for what we're going to build, getAll() is a more descriptive than readAll().
Now, we have a quick and easy way to get the data we need.
Let's do the presentation.
In your view php file, get the data.
<?php
// Get all products.
$products = (new Product($conn))->getAll();
?>
If you dig deeper in the MVC (or any MV*) pattern, you'll find out that a view asking for the data is not the best approach (pulling the data). The better one is to push the data to the view. But that's another story now.
So, we have our products in the products array. Let's iterate over it. Don't forget to first check if there are any users at all.
<?php if ( ! empty($products)) : ?>
<table>
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>CategoryID</th>
<th>Created</th>
</tr>
</thead>
<?php foreach ($products as $product) : ?>
<tr>
<td><?php $product['name'] ?></td>
<td><?php $product['description'] ?></td>
<td><?php $product['price'] ?></td>
<td><?php $product['CategoryID'] ?></td>
<td><?php $product['created'] ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
That's it. I hope I inspired you to broaden your perspective on best practices. :)
Related
if (!empty($_SESSION["shopping_cart"])) {
$total = 0;
foreach ($_SESSION["shopping_cart"] as $keys => $values) {
?>
<tr>
<td><?php echo $values["item_name"]; //$GLOBALS['x']= $values["item_name"] $_COOKIE["iname"] = $values["item_name"] ?></td>
<td><?php echo $values["item_quantity"];//$GLOBALS['y']= $values["item_quantity"]//$_SESSION["iquantity"] = $values["item_quantity"]?></td>
<td>₹ <?php echo $values["item_price"]; //$GLOBALS['z']= $values["item_price"]//$_SESSION["iprice"] = $values["item_price"]?></td>
<td>₹ <?php echo number_format($values["item_quantity"] * $values["item_price"], 2); ?></td>
<?php
$menus = array("name"=>$values["item_name"],
"quan"=>$values["item_quantity"],
"price"=>$values["item_price"],
"id"=>$values["item_id"]);
?>
<td><span class="text-danger">Remove</span></td>
</tr>
<?php
$total = $total + ($values["item_quantity"] * $values["item_price"]);
}
?>
<tr>
<td colspan="3" align="right">Total</td>
<td align="right">₹ <?php echo number_format($total, 2); ?></td>
<td></td>
</tr>
<tr>
<td colspan="5" align="right"> <input type="submit" value="Confirm" class="btn btn-primary">
</td>
</tr>
</form>
<?php
}
Basically I am trying to create a cafeteria management system using sql, html and php. So I want to insert the items ordered by the user into a table for that I am supposed to pass the variables from a foreach of one php file to another php file.
I want to pass the $values["item_name"], $values["item_quantity"], $values["item_price"] to the other php file to insert their values into a sql table which is below:
<?php
include_once('index.php');
$i_name = ("item_name");
$i_quantity =("item_quantity");
$i_price =("item_price");
$i_id = ("item_id");
/*$i_name = $_SESSION[$menus["name"]];;
$i_quantity =$_SESSION[$menus["quan"]];
$i_price = $_SESSION[$menus["price"]];
$i_id = $_SESSION[$menus["id"]];
*/
session_start();
$un = $_SESSION['username'];
$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "cart";
$conn = new mysqli($host, $dbusername, $dbpassword, $dbname);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
} else {
$sql = "INSERT INTO tbl_order (itemname, itemquantity, itemprice, itemid, username) values ('$i_name','$i_quantity','$i_price','$i_id','$un')";
if ($conn->query($sql)) {
header("location: lastpageFINAL.php");
} else {
echo "Error: " . $sql . "" . $conn->error;
}
$conn->close();
}
echo '<br /><a href="orderstatus1.php">';
//echo '<br /><a href="index.php">';
?>
I tried using global variables but couldn't make it.
Back in the days when I was a university student, one of my teachers told us that the code that you repeatedly need to execute is called "function". She was right in my opinion. However, you can do without functions as well, even though it's not especially advisable. You can use include/require for this purpose:
foo.php
$something = 0;
for ($i = 1; $i < 100; $i++) {
$something += $i;
require "bar.php";
}
bar.php
echo $something."<br>";
As you can see, $something is visible in bar.php because it was initialized before the file was required. This is how you can "pass" variables to files. However, again, it is advisable to define functions, require them only once and call them whenever you need them. Even better is to implement classes, but learn function programming first.
And as a sidenote I should mention: beware SQL injection and use parameterized queries instead of string interpolation.
Hi i want to show all the data of one row in a table.But i can only show 1 column of the table.
function getAllRecipes(): array {
global $connection;
$query = "SELECT * FROM recipe";
$stmt = $connection->prepare($query);
$stmt->execute();
return $stmt->fetchAll();
}
$recipe = getAllRecipes();
<?php foreach ($recipe as $recip) : ?>
<table>
<tr>
<td><?= **$recip["id"];** ?></td> <----here
</tr>
</table>
This is the result
and i want all of the line:
Do you know how to do it ?
Thanks for your help
Based on "i just want by one line show all the contain of th row" in your "answer".
$arr_values = array_values($recipe);
$html = '<table><tr><th>' . implode('</th><th>', $arr_values) . '</tr></table>';
echo $html;
If you simply only want the name of the keys(columns):
$arr_keys = array_keys($recipe);
$html = '<table><tr><th>' . implode('</th><th>', $arr_keys) . '</tr></table>';
echo $html;
I've never asked any question here before, but after spending many hours searching for a hint I decided to ask a question.
I have a project at school where I need to create a table from DB for all records for one user, and then create an expanded view for all details for a chosen record.
So far I have:
$user = 'myuser';
$pass = 'mypassword';
$db = new PDO( 'mysql:host=localhost;dbname=mydb', $user, $pass );
$sql = "
SELECT id,login
FROM quotes_taxi
WHERE login='[usr_login]'";
$query = $db->prepare( $sql );
$query->execute();
$results
where 'id' is obviously ID for each record. Then I create a table using FOREACH
<?php foreach( $results as $row ){
echo '<tr>';
echo '<td>'; echo $row['id']; echo '</td>';
echo '<td>'; echo $row['login']; echo '</td>';
echo '<td>'; echo ' View All ';
echo '</td>';
echo "</tr>";
}
?>
the problem I am having is: how can I attached that 'id' within the link (and it needs to be a separate button for each ID), so I can pass it to the view/index.php where I am using
$quote_id = $_GET["id"];
to get all other details of a chosen ID...
I know I have an error in that line, I just cannot figure it what. I also assume it is an easy problem, but I just cannot get my head around it
any help is most appreciated.
Thank you
Try to separate your PHP and HTML that way it will be easier to find errors quickly. Try the following code.
<table>
<tr>
<th>Id</th>
<th>Login</th>
<th>View</th>
</tr>
<?php foreach ($results as $row) : ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['login']; ?></td>
<td> View All </td>
</tr>
<?php endforeach; ?>
</table>
Output
I suggest this function
function AddGetParams()
{
$linkParams="";
foreach($GLOBALS["_GET"] as $key=>$value)
{
$linkParams.="$key=$value&";
}
return $linkParams;
}
I'm trying to make an simple search engine, and the results are displayed fine as it is now. The only problem I have is I want it to be a little more presentable.
This is the code as it stands (I also have a another .php where it gets the searchval, searchfunction and jQuery)
<?php
mysql_connect ("localhost","root","xxxxxxx") or die ("Connectionissues");
mysql_select_db ("xxxxxxxx") or die("Can't find database");
$output = '';
if(isset($_POST['searchVal'])) {
$searchq = $_POST['searchVal'];
$searchq = preg_replace ("#^0-9a-z#^1"," ",$searchq);
$query = mysql_query("SELECT * FROM ds_OrderItem WHERE idProduct LIKE
'%$searchq%'") or die("Search incomplete!");
$count = mysql_num_rows ($query);
if($count == 0){
$output = 'Order have never been made before';
}else{
while($row = mysql_fetch_array($query)) {
$idproduct = $row['idProduct'];
$idorder = $row['idOrder'];
$title = $row['title'];
$qty = $row['qty'];
$output .= '<div> '.$idproduct.' '.$idorder.' '.$title.' '.$qty.'
</div>';
}
if($_POST['searchVal'] == NULL) {
$output = "";
}
}
}
echo ($output);
?>
To limit the searchresults I tried to make an if statement before the when statement like this:
if($count = <100){
$output = 'Too many results!';
And for the table I have tried various methods, and I always end up making the simple HTML table, but I cant get the search results to post within the four columns.
1st of all, you should really consider using PPS : Prepared Parameterized Statements. This will help Preventing SQL injection
if you want to limit and order, use the query, therefore, MySQL : LIMIT Query Optimization is useful.
For what you ask, use something like :
<?php
-> SELECT * FROM ds_OrderItem WHERE idProduct LIKE '%$searchq%' ORDER BY title ASC, quantity DESC LIMIT 20
// THIS IS NOT SAFE as you trust user data !!!
// then you have 20 results already ordered
// here, I used title alphabetical order + the most avalaible quantity, but you adapt it...
if ($result_of_num_rows > 0) { /* we have results */
echo"<table>"; // only raw, use a nicely formatted html output :)
while($row = mysql_fetch_array($query)) {
$idproduct = $row['idProduct'];
$idorder = $row['idOrder'];
$title = $row['title'];
$qty = $row['qty'];
echo"<tr>
<td> $idorder </td>
<td> $idproduct </td>
<td> $title </td>
<td> $qty </td>
</tr>";
}
echo"</table>";
}
else { echo"nothing yet !"; }
?>
much better would be making use of 'new' standard choosing an API and you have an example below that (I hope) will help you choose a new path :)
<?php
error_reporting(E_ALL); ini_set('display_errors', 1); /* PHP will help us */
/* connexion to db */
$mysqli = mysqli_connect("$host", "$user", "$pwd", "$db");
if (mysqli_connect_errno()) { echo "Error connecting to DB : " . mysqli_connect_error($mysqli); }
$param = "%{$_POST['searchq']}%";
$query = " SELECT idProduct, idOrder, title, qty FROM ds_OrderItem WHERE idProduct LIKE ? ORDER BY title ASC, quantity DESC LIMIT 20 ";
$stmt = $mysqli->prepare($query); /* prepare query */
$stmt->bind_param("s", $param); /* bind param wil sanitize */
print_r($stmt->error_list); /* check for error -> can be removed later */
print_r($stmt->get_warnings()); /* check for error -> can be removed later */
print_r($stmt->error); /* check for error -> can be removed later */
$results = $stmt->execute(); /* execute query */
$stmt->bind_result($idProduct, $idOrder, $title, $qty); /* bounded results */
$stmt->store_result();
if ($stmt->num_rows > 0) { /* we have results */
echo"<table>"; // start table
while($stmt->fetch()){ /* loop through results */
echo"<tr>
<td> $idOrder </td>
<td> $idProduct </td>
<td> $title </td>
<td> $qty </td>
</tr>";
}
echo"</table>";
}
else
{ echo"[ no data ]"; }
?>
Your possible solution is below and you can count variable and put condition in loop before closing while
<table>
<?php while($row = mysql_fetch_array($query)) {
$idproduct = $row['idProduct'];
$idorder = $row['idOrder'];
$title = $row['title'];
$qty = $row['qty'];
?>
<tr>
<td><?php echo $idproduct; ?></td>
<td><?php echo $idorder; ?></td>
<td><?php echo $title; ?></td>
<td><?php echo $qty; ?></td>
</tr>
<?php } ?>
</table>
Essentially, I am creating a movie ordering system that has 7 movie genres, and I want each movie tab to populate according to genre. At this point I cant even get the table to show up. Can anyone help me out?
<div id="content">
<table>
<tr><th>Name</th> <th>Genre</th> <th>Year</th> <th>Rating</th></tr>
<?php
//connect to database
$dbc = mysql_connect('localhost' , 'username' , 'password');
$test = mysql_select_db('movies', $dbc);
if ($test = mysql_select_db('movies', $dbc))//test
{
$query = "SELECT * FROM 'movies' WHERE 'genre' = 'Action'";
//call query
$result = mysql_query($query, $dbc);
while ($row = mysql_fetch_array($result))
{
?>
<tr>
<td><?php print $row['name']; ?></td>
<td><?php print $row['genre']; ?></td>
<td><?php print $row['year']; ?></td>
<td><?php print $row['rating'];?></td>
</tr>
<table>
<?php
}//close the while loop
}//close the if statement
mysql_close($dbc);
?>
First of all, do not use mysql because of secure problems and it will be not suported in PHP later. Read about this http://php.net/manual/en/function.mysql-connect.php .
Try to use PDO or mysqli, for example :
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 'movies' WHERE 'genre' = 'Action'");
while($row = mysqli_fetch_array($result))
{
echo $row['name'];
echo "<br>";
}
mysqli_close($con);