Want to pass variables in foreach loop to another php file - php

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.

Related

php post value from FOREACH to another page

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;
}

Display data from database in a table

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. :)

PHP MYSQLI fetch Errors

At school my teacher told me a lot of thing about coding in PHP using a POSTGRES DATABASE.
But when I started to use MYSQLI Server i couldn't do a lot of thing.
First of all the functions.
My teacher told me to do this type of function
$rows = getBuildings();
if (count($elenco) == 0) {
print "<hr> No buildings here </hr>";
} else {
?>
<thead>
<tr>
<th>address</th>
<th>town</th>
<th>Manager</th>
</tr>
</thead>
<tbody>
<?php
foreach ($elenco as $riga) {
?>
<tr>
<td> <?= $row->address ?></td>
<td> <?= $row->town ?></td>
<td> <?= $row->name ?> <?= $riga->surname ?> </td>
</tr>
<?php
}
?>
</tbody>
</table>
</tbody>
</table>
<?php
}
?>
</body>
</html>
<?php
function getBuldings() {
global $db;
$sql = "select * from buildings, boss
where boss.codBo=buildings.codBu";
$rows = array();
if (!DB::isError($tab = $db->query($sql))) {
while ($row = $tab->fetchRow(DB_FETCHMODE_OBJECT)) {
$rows[] = $row;
}
} else {
die("ErrorSQL:" . $tab->getMessage());
}
return $rows;
}
?>
But to get it working in MYSQL i had to do a lot of changes. In fact there was an error in !BD::isError. I had to change the connection.php in from this one
<?php
Session_Start();
require_once("DB.php");
$db = DB::connect("pgsql:etc....");
if (DB::isError($db)) {
die("Error: " . $db->getMessage());
}
?>
to this one
<?php
$servername = "localhost";
$username = "test";
$password = "";
$dbname = "test";
// Create connection
$db = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
$a = mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
echo "Connected successfully " . $a . " ";
?>
In order to show the result of the query my code had become this:
<body>
<?php
$rows = getBoss();
if (count($rows) == 0) {
print "<h2>No Boss here</h2>";
} else {
foreach ($rows as $row) {
print "<p>" . $row['name'] . "</p>";
print "<p>" . $row['surname'] . "</p>";
}
}
?>
<?php
function getBoss() {
global $db;
$sql = "select *
from test_boss
order by name, surname";
$rows = array();
if ($tab = $db->query($sql)) {
while ($row = $tab->fetch_array()) {
$rows[] = $row;
}
return $elenco;
} else {
die("Errore sql: " . $tab->getMessage() . ":" . $sql);
}
}
?>
</body>
</html>
That in facts works pretty well, but I had to change FETCH_ROW to FETCH_ARRAY.
I could not use anymore the method of posting the data from the $rows value.
<?= $row->name ?>
Because there was an error
Notice: Trying to get property of non-object
but I had to use
print "<p>".$row['name']."</p>";
What can I do in order to use the method FETCH_ROW corretly?
You can type cast the array to an object by tweaking the code slight.
if you want to retrieve an object in form of $row->name then your code will be.
while ($row= $tab->fetch_array()) {
$rows[] = (object)$row;
}
OR
while ($row= $tab->fetch_object()) {
$rows[] = $row;
}

Using MySql to populate a html table using a specific column

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);

PHP MySQL undefined Index and other errors

having trouble getting a script of mine to run correctly, I have 2 undefined index errors and an invalid argument supplied error that for the life of me I can't figure out why I'm getting. the 2 undefined index errors come from these lines.
if(!is_null($_GET['order']) && $_GET['order'] != 'courseTitle')
and
if (!is_null($_GET['page']))
and my invalid argument error is this
Warning: Invalid argument supplied for foreach() in
generated from this
<?php foreach ($books as $book) : ?>
my full code between the two classes is this.. any ideas of what I've done wrong? tearing my hair out over this.
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Catalog</title>
</head>
<body bgcolor="white">
<?php
/////////////////////////////////////////////////
//connect to db
/////////////////////////////////////////////////
$dsn = 'mysql:host=localhost;dbname=book_catalog';
$username = "php";
$password = "php";
$db = new PDO($dsn, $username, $password);
//get data
if(!is_null($_GET['order']) && $_GET['order'] != 'courseTitle')
{
$thesort = $_GET['order'];
$query = "Select * FROM book
INNER JOIN course
ON book.course = course.courseID
ORDER BY ".$_GET['order'];
}
else
{
$thesort = "courseTitle";
$query = "Select * FROM book
INNER JOIN course
ON book.course = course.courseID
ORDER BY $thesort";
}
//if page is null go to first page otherwise query for correct page
if (!is_null($_GET['page']))
{
$query = $query." LIMIT ".($_GET['page']*8-8).", 8";
}
else
{
$query = $query." LIMIT 0, 8";
}
//query result
$books = $db->query($query);
//get number of overall rows
$query2 = $db->query("SELECT * FROM book");
$count = $db->query("SELECT Count(*) As 'totalRecords' FROM book");
$count = $count->fetch();
$count = $count['totalRecords'];
?>
<table border =" 1">
<tr>
<th bgcolor="#6495ed"><a href="?order=course">Course #</th>
<th bgcolor="#6495ed"><a href="?order=courseTitle">Course Title</th>
<th bgcolor="#6495ed"><a href="?order=bookTitle">Book Title</th>
<th bgcolor="#6495ed"></th>
<th bgcolor="#6495ed"><a href="?order=price">Price</th>
</tr>
<?php foreach ($books as $book) : ?>
<tr>
<td><?php echo $book['course']; ?></td>
<td><?php echo $book['courseTitle']; ?></td>
<td><?php echo $book['bookTitle']; ?></td>
<td><?php
$bookcourse = $book['course'];
$isbn = $book['isbn13'];
$booklink = "<a href=\"course.php?course=$bookcourse&isbn=$isbn\">";
echo $booklink ;?><img src='images/<?php echo $book['isbn13'].'.jpg'; ?>'></a></td>
<td><?php echo $book['price']; ?></td>
</tr>
<?php endforeach; ?>
</tr>
</table>
<?php
//paging function... not sure if it works correctly?
for ($j=1; $j <= ceil($count/8); $j++)
{ ?>
<a href=<?php echo "?page=".$j."&order=".$thesort; ?>><?php echo $j; ?></a>
<?php
}?>
</body>
</html>
**course.php**
<?php
//get data from index.php
$course = $_GET['course'];
$isbn = $_GET['isbn'];
//connect to db
$dsn = 'mysql:host=localhost;dbname=book_catalog';
$username = "php";
$password = "php";
$db = new PDO($dsn, $username, $password);
//get data
$query = "Select * FROM book, course, author, publisher
WHERE book.isbn13 = $isbn AND book.course = '$course' AND book.course = course.courseID AND book.bookID = author.bookID AND book.publisher = publisher.publisherID
ORDER BY book.bookID";
//query results
$books = $db->query($query);
//error troubleshooting
if (!$books) {
echo "Could not successfully run query ($query) from DB: " . mysql_error();
exit;
}
//count the number of rows in the result
$results = $books->fetchAll();
$rowCount = count($book);
//get data from results
foreach($results as $book){
$bookID = $book['bookID'];
$bookTitle = $book['bookTitle'];
$isbn = $book['isbn13'];
$price = $book['price'];
$desc = $book['description'];
$publisher = $book['publisher'];
$courseTitle = $book['courseTitle'];
$courseID = $book['courseID'];
$credits = $book['credit'];
$edition = $book['edition'];
$publishDate = $book['publishDate'];
$length = $book['length'];
$firstName = $book['firstName'];
$lastName = $book['lastName'];
}
if($numrows > 1)
{
foreach ($books as $book)
{
$authorArray[] = $book['firstName'] + ' ' + $book['lastName'];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>CIS Department Book Catalog</title>
</head>
<body bgcolor=white">
<table border="0">
<tr>
<td>
<img src='images/<?php echo $isbn.'.jpg'; ?>'>
</td>
<td>
<?php
echo "For Course: $courseID $courseTitle ($credits)";
echo "</br>";
echo "Book Title: $bookTitle";
echo "</br>";
echo "Price: $price";
echo "</br>";
echo "Author";
if ($numResults > 1)
{
echo "s:";
for ($i = 0; $i < $numResults; $i++)
{
if ($i!=0)
echo ", $authorArray[i]";
else
echo $authorArrat[i];
}
}
else
echo ": $firstName, $lastName";
echo "</br>";
echo "Publisher: $publisher";
echo "</br>";
echo "Edition: $edition ($publishDate)";
echo "</br>";
echo "Length: $length pages";
echo "</br>";
echo "ISBN-13: $isbn";
?>
</td>
</tr>
<tr>
<td colspan="2">
<?php echo "Description: $desc"; ?>
</td>
</tr>
</table>
</body>
</html>
You should be using isset not is_null to keep it from warning about undefined variables.
$books is never defined It was defined, just incorrectly ... foreach needs it to be an array. You really don't need it anyway, fetch each row into the array with a while loop. (see my example below). You're also redefining $count several times in your query.
And like #Brad said. Use prepared statements and placeholders. Your database will end up hacked with your current code.
EDIT
Answer to your question. query() returns a statement handle. (I've defined it as $sth). fetch() returns a result which you need to pass one of the fetch mode constants (or define it by default earlier with $db->setFetchMode())
To get the books you need to have
$books = array();
$sth = $db->query($query);
while( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
$books[] = $row; // appends each row to the array
}
Here's how your code should look to get a count.
// you're not using the $query2 you defined ... just remove it
$sth = $db->query("SELECT Count(*) As 'totalRecords' FROM book");
$result = $sth->fetch(PDO::FETCH_ASSOC);
$count = $result['totalRecords'];
Take a look at:
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers Looks like a good guide to give you an in-depth understanding of how to use PDO. Pay special attention to error handling and to prepared statements!

Categories