Pass current id in the next page in php - php

I am developing a restaurant menu system in which there is a single menu.A menu has many categories and each category has multiple items in it.Now i have created the create , show functionality of Categories and the show functionality of the Item but i am stuck on the create functionality of the item because i need the category's id to insert item in that particular id.This is my code for showing Items in a category.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<h3>Category Items</h3>
</div>
<div class="row">
<p> Create </p>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php
require 'database.php';
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
if ( null==$id ) {
header("Location: index.php");
} else {
$pdo = Database::connect();
$sql = "SELECT * FROM Items where I_C_id = '" . $id . "'";
$result = $pdo->query($sql);
foreach ($pdo->query($sql) as $row) {
echo '<tr>';
echo '<td>'. $row['I_id'] . '</td>';
echo '<td>'. $row['I_name'] . '</td>';
echo '<td>'. $row['I_desc'] . '</td>';
echo '<td>'. $row['I_price'] . '</td>';
echo '</tr>';
}
}
Database::disconnect();
?>
</tbody>
</table>
</div>
</div> <!-- /container -->
This file gets the "id" of the category and displays the items in it of that particular category.Now i want to create items of that particular id.how should i pass the id of the category in the create page?

You can use $_SESSION[] to store all informations related to the current client.
Sessions's data will be automatically destroyed once if client is disconnected, or no more active in your web site.
There are some configurations to do in php.ini : session time out, session folder, garbage collector probability... or you can let the default configurations
for more informations : http://php.net/manual/en/reserved.variables.session.php
Hope that helps :)

Either by using PHP sessions, or by appending the id to the link, so
<a href="create_items.php"
becomes
<a href="create_items.php?cat_id=<?=$_GET['id']?>"
Unrelated to the question, but you'll want to look into avoiding SQL injection attacks, e.g. How can I prevent SQL injection in PHP?

Related

Insert data into mysql table by clicking on a link using PHP and HTML

I`m new in PHP and I'm creating a Airbnb website with recommendations for users. I have three tables in my database: users, houses and user_choice.
I display data about houses like simple html table and for testing I display Id of each house like a number of house, which include a link, which user can click and go to other page to see more info about house.
I want to write in table each house in which user was interested. So, here is my logic: every time the user wants to know more about the house, he clicks on the link, after which my code should insert a record into the table "user_choice", which will contain the id of the user and the id of the house he chose. How can I do this?
My code:
<?php
include "db.php";
session_start();
if (isset($_SESSION['Id_user']) && isset($_SESSION['Login'])) {
?>
<!DOCTYPE html>
<html lang="eu">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet">
<title>Home page</title>
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card mt-5">
<div class="card-header">
<h4>Choose your house</h4>
</div>
<div class="card-body">
<table class="table table-bordered">
<thead>
<tr>
<th>№ house</th>
<th>City</th>
<th>Location</th>
<th>Area Type</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM house_rent_dataset";
$query_run = $mysqli->query($query);
if(mysqli_num_rows($query_run) > 0)
{
foreach($query_run as $row)
{
?>
<tr>
<td><?= $row['Id_house']; ?></td>
<td><?= $row['City']; ?></td>
<td><?= $row['Locality']; ?></td>
<td><?= $row['Area Type']; ?></td>
<td><?= $row['Price']; ?></td>
</tr>
<?php
}
}
else
{
?>
<tr>
<td colspan="4">No Record Found</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
<?php
}
else {
header("Location: index.php");
exit();
}
?>
I will be grateful for your help.
you can make simple logic with count on your click detail link of house that user choose.
Every user click link of detail it will going to new page that sent data param id of house, and display detail house.
You can make logic within your function that action is to display detail house with updateOrCreate (if you use php framework likes Laravel or CodeIgniter) to database user_choice with contain user_id and house_id.
Let me give an example
// this is function for display detail of house that user //selected or click
public function detailHouse(Request $request){
//this is the code for make user_choice (recommended house //for user based on user selected)
data["user_id"] = $request->user_id;
data["house_id"] = $request->house_id;
data["count"] += 1;
user_choice::updateOrCreate(data);
//this is your code for display detail of house selected
$house = house::where('id', $request->house_id)->first()
return view('detail_house', [
'data' => $house
];
}
Then, you can display table relation that display for user that recommended house for user based on how many user click or choose detail of every house

$_GET does not work and query the property

I have a problem with $_GET method. I have retrieved some data about admins of a webpage from database & I added a hyperlink for users to get the information about that them.
Here's the code in my 1st page:
<?php if(($adminlevel)==1){
echo '
<h4 class="widgettitle">List of admins</h4>
<table class="table responsive">
<thead>
<tr>
<th>Admin Level</th>
</tr>
</thead>
'; getAdmins(); echo '
</table>
';
}else{
echo '<h4 class="widgettitle">You dont have permission to see this table</h4>';
}
?>
<div class="divider15"></div>
The function getAdmins() goes like this:
<?php
function getAdmins(){
global $con;
$get_admin = "select * from admins order by id";
$run_admin = mysqli_query($con,$get_admin);
while($row_admin = mysqli_fetch_array($run_admin)){
$id_admin = $row_admin['id'];
echo "
<tbody>
<tr>
<td>Trident</td>
<td class='center'><a href='editlevel.php?id=$id_admin' title='Clik to change admin level' target='_blank'>$adminlevel_admin</a></td>
</tr>
</tbody>
";
}
}
?>
As you see I link the users from my first page to another page which is called editlevel.php by the function getAdmins().
Therefore I made my hyperlink like this:
<a href='editlevel.php?id=$id_admin'>$adminlevel_admin</a>
And Here's the editlevel.php page:
<body>
<?php
if (isset($_GET['id_admin'])){
$result_id = $_GET['id_admin'];
$get_result = "select * from admins where id='$result_id'";
$run_result = mysqli_query($con,$get_result);
while($row_result= mysqli_fetch_array($run_result)){
$id_target = $row_result['id'];
$username_target = $row_result['username'];
$adminlevel_target = $row_result['adminlevel'];
$email_target = $row_result['email'];
echo '
<div class="mainwrapper">
<div class="header">
'; include "php/php_includes/overall/header.inc.php"; echo'
</div>
<div class="leftpanel">
';include "php/php_includes/overall/leftpanel.inc.php"; echo '
</div><!-- leftpanel -->
<div class="rightpanel">
'; include "php/php_includes/gadgets/rightpanel.editlevel.php"; echo '
</div><!--rightpanel-->
</div><!--mainwrapper-->
';
}
}
?>
</body>
So basically I used if (isset($_GET['id_admin'])){ to get the results of the item which user clicked & try to retrieve the data of that item from database via that.. But the problem is nothing appears at my screen. No error message & no result. Please if you know how can I solve it please let me know!
It appears that your link is:
<a href='editlevel.php?id=$id_admin'>$adminlevel_admin</a>
When it should be:
<a href='editlevel.php?id_admin=$id_admin'>$adminlevel_admin</a>
In order for it to work with:
if (isset($_GET['id_admin'])){
$result_id = $_GET['id_admin'];
Edit: It goes without saying, you should never trust user input (such as $_GET). These values should be validated and sanitised before being used in SQL queries.

Array gets emptied when i try to add new stuff to it (PHP)

I am trying to add stuff into an array after every click a user makes on a category but for some reason it keeps replacing everything in the array. I can't figure out where I am going wrong. I've tried 'googling' it and every example i find looks similar to what i have written. Please Help!
these functions are store in core.php
function getStoreBacktrace($cat) {
include("config.php");
$backtrace = array();
if ($cat != 0) {
array_push($backtrace, $cat);
}
if (count($backtrace != 0)) {
foreach($backtrace as $c){
echo getBackCatName($c);
}
}
print_r($backtrace); // Put this to see what output is
}
function getBackCatName($c) {
include("config.php");
$query = 'SELECT * FROM `home_store_cats` WHERE `id`="'.$c.'"';
$r_query = mysql_query($query);
$result = mysql_fetch_array($r_query);
echo ' > '.$result['name'].'';
}
this function prints out a list of links the user can click on
function getStoreCat($cat) {
include("config.php");
$query = 'SELECT * FROM `home_store_cats` WHERE `main`="'.$cat.'" ORDER BY `name` ASC';
$r_query = mysql_query($query);
echo '<ul>';
while ($result = mysql_fetch_array($r_query)) {
echo '<li>';
echo ''.$result['name'].'';
echo '</li>';
}
echo '</ul>';
}
and it gets called in store.php
<?php
include("config.php");
include("core.php");
$backtrace = array();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title><?php echo getSiteTitle().' :: '.getSiteSlogan(); ?></title>
</head>
<body>
<table width="100%">
<tr>
<td colspan="2">
<!-- Backtrace -->
Home
<?php echo getStoreBacktrace($cat, $backtrace); ?>
</td>
</tr>
<tr>
<td>
<!-- Categories -->
<table>
<tr>
<td><?php echo getStoreCat($cat); ?></td>
</tr>
</table>
</td>
<td>
<!-- Products -->
<table>
<tr>
<?php echo getStoreProducts($cat); ?>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
now everytime a user clicks on a link that is made from the function getStoreCat($cat) it refreshes the page with new links to click on and new products to show depending on what $cat they chose. i want to push the $cat to the $backtrace array.
Right here:
$backtrace = array();
You are effectively resetting the array for each call to getStoreBacktrace().
EDIT:
Thanks for fixing your question. Now it's clear that the issue is you need to make $backtrace persistent through multiple page views. Do this using sessions:
Page template
<?php
session_start(); // enable sessions
include("config.php");
include("core.php");
?>
<!DOCTYPE html>
etc...
Function definition
<?php
function getStoreBacktrace($cat) {
include_once("config.php"); // use include_once() to prevent possible errors
if (!isset($_SESSION['backtrace']))
$_SESSION['backtrace']= array();
if ($cat != 0) {
array_push($_SESSION['backtrace'], $cat);
}
...
Everytime you call getStoreBacktrace you instantiate a brand new array in $backtrace.

Can't output relevant mysql information to clicked link using SELECT *FROM table WHERE variable LIKE '$variable'

I have a mysql database named "drinks", in that database I have one table named "persons" and in "persons" I have two people, Bryan(fname) Fajardo(lname) 21(age) and Andross H Age:20.
In my index.php I have links set up from all of the people in table persons.
I am trying to get my links to work so that when I click on either name, the information relevant from that person is outputted into my other page (where the link goes to) which is: insert.php.
I have been trying for hours to run some test by clicking on the Bryan link and outputting only his last name etc. etc. My objective: is to be able to link the people from "persons" table and then upon click go to insert.php and output that person's information there.
Here is my current code from Index.php.
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<?php
//Connect to the database
$con = mysqli_connect("localhost","username","password","drinks");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
echo '<span style = "background: red ;">MSQL Connected.</span>' ;
}
$result = mysqli_query($con,"SELECT * FROM persons");
while($row = mysqli_fetch_array($result)) {
Print '<dd><a href=insert.php?
fname="'.$row['fname'].'">'.$row['fname'].'</a></dd>';
}
mysql_close();
?>
</body>
</html>
and here is my Insert .php where I want the relevant information to be printed.
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class = "full-header">
<div class = "mid-header span12 center">
</div>
</div>
<div class = "main-content-container full_w">
<div class = "span12 main-content center">
<?php
$cont = mysqli_connect("localhost","username","password","drinks");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
echo '<span style = "background: red ;">yay</span>' ;
}
$fname = $_GET['fname'];
$sel = ($cont,"SELECT * FROM persons WHERE fname ='%$fname%'");
while($rower = mysqli_fetch_array($sel)) {
Print $rower['lname'];
//why is this not printing Bryan's last name?
}
?>
</div>
</div>
</body>
</html>
Thank you in advance, I appreciate the help, I have just recently gotten into php and database building/summoning.
EDIT: I also have been reading that this is becoming deprecated and PDO is going to be used now, if you have a solution that involves PDO, I would appreciate that as well, but I am very new to PDO.
EDIT 2: Changed "table" to "persons" in insert.php query.Still did not fix.
I can understand how it is when first starting out. Once you wrap your mind around the basic parts of it the rest will flow.
Since you asked for a better way I am going to suggest a class I personally use in all my projects.
https://github.com/joshcam/PHP-MySQLi-Database-Class
Of course don't forget to download the simple MYSQLI class from the link above and include it just like I do below in your project. Otherwise none of this will work.
Here us the first page which contains the table with all the users from your persons Db table. We list them in a table with a simple edit/view button.
PAGE 1
<?php
require_once('Mysqlidb.php');
//After that, create a new instance of the class.
$db = new Mysqlidb('host', 'username', 'password', 'databaseName');
//a simple select statement to get all users in the DB table persons
$users = $db->get('persons'); //contains an Array of all users
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<table>
<th>
First Name
</th>
<th>
Last Name
</th>
<th> </th>
<?php
//loops through each user in the persons DB table
//the id in the third <td> assumes you use id as the primary field of this DB table persons
foreach ($users as $user){ ?>
<tr>
<td>
<?php echo $user['fname'];?>
</td>
<td>
<?php echo $user['lname'];?>
</td>
<td>
<a href="insert.php?id=<?php echo $user['id']; ?>"/>Edit/View</a>
</td>
</tr>
<?php } ?>
</table>
</body>
</html>
So that ends your first page. Now you need to include this code on your second page which we are assuming is called insert.php.
PAGE 2
<!--add this to your insert page-->
<?php
require_once('Mysqlidb.php');
//After that, create a new instance of the class.
$db = new Mysqlidb('host', 'username', 'password', 'databaseName');
//a simple select statement to get all the user where the GET
//variable equals their ID in the persons table
//(the GET is the ?id=xxxx in the url link clicked)
$db->where ("id", $_GET['id']);
$user = $db->getOne('persons'); //contains an Array of the user
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<table>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>user ID</th>
<tr>
<td>
<?php echo $user['fname'];?>
</td>
<td>
<?php echo $user['lname'];?>
</td>
<td>
<?php echo $user['id']; ?>
</td>
</tr>
</body>
</html>
You have two main errors. On index.php you are wrapping your query string values in quotes
Print '<dd><a href=insert.php?
fname="'.$row['fname'].'">'.$row['fname'].'</a></dd>';
This should really be
Print '<dd><a href="insert.php?
fname='.$row['fname'].'">'.$row['fname'].'</a></dd>';
Next, on your second page, you need to use LIKE on your query.
$sel = ($cont,"SELECT * FROM persons WHERE fname LIKE '%$fname%'");
That said, you really should use parameters because the current method is going to open your script up to SQL Injection, and you should consider using a primary key in your querystring instead of passing the person's name.
Print '<dd><a href="insert.php?
id='.$row['id'].'">'.$row['fname'].'</a></dd>';
And your query
$id = intval($_GET['id']);
$sel = ($cont,"SELECT * FROM persons WHERE id = $id");
One final note, on your index page, you are using mysql_close instead of mysqli_close to close your database connection.

PHP Combining search function with pagination

So I'm trying to make a page where i can display results from my database table. You should be able to search and there should be some pagination as there are thousands of results.
I've managed to make a page which just has the search, and works perfect. So now i need to know how would would integrate some pagination into that.
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="container">
<form action="" method="get">
<input type="text" name="search" id="search" placeholder="Search" />
<input type="submit" />
</form>
<?php include 'process.php'; ?>
</div> <!-- /container -->
<script src="js/jquery.js"></script>
<script src="js/script.js"></script>
</body>
</html>
process.php
<?php include 'dbconfig.php'; ?>
<?php include 'connect.php'; ?>
<?php
$search = $_GET['search'];
$result = mysql_query("SELECT * FROM oantkb WHERE Name LIKE '%$search%' ORDER BY `INDEX` DESC");
echo '<table class="table">';
echo '<thead>';
echo '<tr>';
echo '<th>#</th>';
echo '<th>Pic</th>';
echo '<th>Name</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
while($row = mysql_fetch_assoc($result)) {
$pic = $row['Pic'];
$name = $row['Name'];
echo '<tr>';
echo '<td>#</td>';
echo '<td><img src="'.$pic.'" height="50" width 50"></td>';
echo '<td>'.$name.'</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
?>
Right now it works like it should. When i search it will say index.php?search=banana, but i need some pagination added so it will say for example index.php?search=banana&?page=2. Or something along those lines. Hope it makes sense...i'm a php newb :)
Include at the end of your sql query the following:
$resultsPerPage=10;
$page = ($_GET["page"]-1)*$resultsPerPage;
$query = $query." LIMIT $page,$resultsPerPage";
mysql_query($query);
By the way the mysql_ library is deprecated in favor of mysqli.
Also the above is susceptible to sql injection attacks because $_GET["page"] isn't first sanitized, but for simplicity I did it this way.
This assumes a paging scheme that starts at 1.
i've been using Pear Pagination for a long time. you can try it.
here is a good tutorial for setting it up
Simple Pagination in PHP tutorial
a good thing to add is clean your variable before using them in your query.

Categories