$_GET does not work and query the property - php

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.

Related

how to print a specific data that is stored in mysql database using php

Hi I have added a function to my website where the user can cancel a booked ticket using the code: cancel.php
<?php
session_start();
include('config.php');
mysqli_query($con,"delete from tbl_bookings where book_id='".$_GET['id']."'");
$_SESSION['success']="Booking Cancelled Successfully";
header('location:profile.php');
?>
and I tried to add a function to the same ticket that the user can cancel to print ticket, so the user can print this ticket, the code i used is: print.php
<?php
session_start();
include('config.php');
window.print(mysqli_query($con,"select from tbl_bookings where book_id='".$_GET['id']."'"));
header('location:profile.php');
?>
the link to these two classes in a class called profile.php, and this bit is in the line where it says:
Cancel /Print Ticket
I would be happy if you can tell me how to print this data.. thanks
the use of $bkg
$bk=mysqli_query($con,"select * from tbl_bookings where user_id='".$_SESSION['user']."'");
if(mysqli_num_rows($bk))
{
?>
<table class="table table-bordered">
<thead>
<th>Booking Id</th>
<th>Movie</th>
<th>Theatre</th>
<th>Screen</th>
<th>Show</th>
<th>Seats</th>
<th>Price</th>
<th></th>
</thead>
<tbody>
<?php
while($bkg=mysqli_fetch_array($bk))
{
$m=mysqli_query($con,"select * from tbl_movie where movie_id=(select movie_id from tbl_shows where s_id='".$bkg['show_id']."')");
$mov=mysqli_fetch_array($m);
$s=mysqli_query($con,"select * from tbl_screens where screen_id='".$bkg['screen_id']."'");
$srn=mysqli_fetch_array($s);
$tt=mysqli_query($con,"select * from tbl_theatre where id='".$bkg['t_id']."'");
$thr=mysqli_fetch_array($tt);
$st=mysqli_query($con,"select * from tbl_show_time where st_id=(select st_id from tbl_shows where s_id='".$bkg['show_id']."')");
$stm=mysqli_fetch_array($st);
?>
<tr>
<td>
<?php echo $bkg['ticket_id'];?>
</td>
<td>
<?php echo $mov['movie_name'];?>
</td>
<td>
<?php echo $thr['name'];?>
</td>
<td>
<?php echo $srn['screen_name'];?>
</td>
<td>
<?php echo $stm['start_time'];?>
<?php echo $stm['name'];?>
</td>
<td>
<?php echo $bkg['no_seats'];?>
</td>
<td>
£ <?php echo $bkg['amount'];?>
</td>
<td>
<?php if($bkg['ticket_date']<date('Y-m-d'))
{
?>
<i class="glyphicon glyphicon-ok"></i>
<?php
}
else
{?>
Cancel /Print Ticket
<?php
}
?>
</td>
</tr>
<?php
}
?></tbody>
enter image description here
You can't call window.print() within PHP code since it's a javascript function
header('location:profile.php'); will redirect the page before the javascript have the chance to execute the code. Replace that code with a javascript code which executes after you print the page.
Your print.php:
<?php
session_start();
include('config.php');
$result = mysqli_query($con, "select * from tbl_bookings where book_id='{$_GET['id']}'"); // You should replace this with prepare statement
$row = $result->fetch_array();
// assume that your booking table has columns: id, movie_name, time
echo "<table>
<tr><td>Booking ID</td><td>{$row['id']}</td></tr>
<tr><td>Movie Name</td><td>{$row['movie_name']}</td></tr>
<tr><td>Time</td><td>{$row['time']}</td></tr>
</table>";
?>
<script>
window.print();
window.location.href = "profile.php"
</script>
Stop coding now!
You need to learn the very basic of how PHP + MySQL + HTML + JS work together.
At the moment, you don't need to know what's wrong with your code. You need to learn some basic tutorials, then re-write your code from scratch. Many tutorials all over the intermet. Read this.
Extra Explanation
Server = where your code lives.
Client = the browser.
PHP & MySQL live in the server ONLY, work on the server, handled by the server.
HTML + CSS + JS prepared by the server, server then send it to client, then handled by client (the browser). So they start working when in the client (the browser). As long as they're on the server, they are just strings.
So it's always like:
Browser request file from server (http://www.mywebsite.com/something.php). This is known as the request.
Server runs the php file (something.php), which may generate output (HTML+CSS+JS), server then send the output to the client (browser). This is known as response.
Client (browser) then receives the output (as plain strings), then browser runs the code (JS).
Conclusion:
Don't tell server to run JS, don't tell client (browser) to run PHP or MYSQL.
I've modified your code to work and to much more secured way using prepare statement.
<table>
<tr><th> id </th> <th> time </th> </tr>
<?php
if (!$bk = $con->prepare("select * from tbl_bookings where user_id = ? ")) {
echo $con->error; // show error message when SQL query is wrong or goes kaboom!
} else{
$bk->bind_param("s",$_SESSION['user']); //bind the blind parameters, "s" stands for string
$bk->execute ();// execute the query
$bk_result = $bk->get_result(); // get results
}
while ($bk_row = $bk_result->fetch_assoc()){ ?>
<tr><td> <?php echo $bk_row['id']; ?> </td> <td> <?php echo $bk_row['id'] ?> </td> </tr>
<?php } //end while loop ?>
</table>

HTML PHP database - edit/delete button - passing value

im rather amateur with php and even more so with js. I have created a database table with an edit & delete button, as shown in the screenshot. (if anyone is also able to see why there is a gap between my header and body of table that would be great, i have no clue why this is cropping up, doesnt seem to be css).
The idea is to just click the delete button, pass the 'AwbNo' over to the delete.php page in order to delete the entire row from the database, and then automatically return to the page to see the updated table, if redirection can be avoided, even better just to make the operation smoother. Any help would be greatly appreciated, hope my code below is enough for aid
so select a row to delete>click delete>confirmation>row deleted from db. That is the process i am aiming to achieve
example database screenshot
<table class="table">
<thead>
<tr>
<th>Awb Number</th>
<th>Vessel</th>
<th>Client</th>
<th>Pieces</th>
<th>Total Weight</th>
<th>Carrier</th>
<th>Sender</th>
<th>Status</th>
<th>Arrival Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php //BEGINNING OF PHP
include("login/dbinfo.inc.php");
$comm=#mysql_connect(localhost,$username,$password);
$rs=#mysql_select_db($database) or die( "Unable to select database");
$sql="SELECT AwbNo, VesselName, ClientCode, Pieces, Weight, Carrier, Sender, Status, DATE_FORMAT(ArrivalDate, '%d-%m-%yyyy') FROM tbl_import";
$result = mysql_query($sql) or die("SELECT Error: ".mysql_error());
$num_rows = mysql_num_rows($result);
echo "<p>There are $num_rows records in the Customer table.</p>";
echo "<table class=\"table\">\n";
while ($get_info = mysql_fetch_array($result))
{
echo ("<tr>\n");
echo ("<td>".$get_info["AwbNo"]."</td>");
echo ("<td>".$get_info["VesselName"]."</td>");
echo ("<td>".$get_info["ClientCode"]."</td>");
echo ("<td>".$get_info["Pieces"]."</td>");
echo ("<td>".$get_info["Weight"]."</td>");
echo ("<td>".$get_info["Carrier"]."</td>");
echo ("<td>".$get_info["Sender"]."</td>");
echo ("<td>".$get_info["Status"]."</td>");
echo ("<td>".$get_info["ArrivalDate"]."</td>");
?>
<td>
<div id="outer">
<div class="inner"><button type="submit" class="msgBtn" onClick="goToURL()" > Edit </button></div>
<div class="inner"><button type="submit" class="msgBtn2" onClick="goToURL1()"> Delete </button></div>
</div>
</td>
<?php
echo ("</tr>\n");
}
echo "</table>\n";
mysql_close();
?> <!--END OF PHP-->
</tbody>
</table>
Below is the js script to redirect user page when clicking on the 'edit' or 'delete' button.
<script>
function goToURL() {
window.open('php/edit.php');
}
function goToURL1() {
window.open('php/delete.php');
}
</script>
And below is the supposing 'delete.php' page to delete the record from the db on a live server, this is only an example, im not exactly sure if it is correct.
<?php
include("dbinfo.inc.php");
$comm=#mysql_connect(localhost,$username,$password);
$rs=#mysql_select_db($database) or die( "Unable to select database");
$AwbNo=$_POST['AwbNo'];
$sql="DELETE FROM tbl_import where AwbNo=$AwbNo";
mysql_query($sql)or die("Delete Error: ".mysql_error());
mysql_close();
echo "Record was successfully deleted.\n";
?>
The issue your having is because you need to pass the primary key that AwbNo in you case, along with the Edit /Delete link, so that the correct record is selected from DB. This is not happening in your case.
The code for the table needs to look something like mentioned below for the edit & delete links.
echo '<td>&nbspEdit&nbsp</td>';
echo '<td>&nbspDelete&nbsp</td>'
Also add this script in same page.
<script>
function delete_user(uid)
{
if (confirm('Are You Sure to Delete this Record?'))
{
window.location.href = 'delete.php?id=' + uid;
}
}
</script>
delete.php can have just this code:
<?php
include("dbinfo.inc.php");
$comm=#mysql_connect(localhost,$username,$password);
$rs=#mysql_select_db($database) or die( "Unable to select database");
$id = $_GET['id']; // $id is now defined
mysqli_query($conn,"DELETE FROM tbl_import where AwbNo='".$id."'");
mysqli_close($conn);
header("Location: index.php"); //redirect to relevant page
?>

Pass current id in the next page in 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?

Linking to search results directly

I got myself into a project at work that is going beyond my (very modest) coding skills.
So i have a database with 6 fields. I'm able to make searchs on it using php (i followed a youtube tutorial), add records, delete records and update records. All of that is working just fine.
What i need now is this:
I need to link search results (only a few, the most popular) on a image.
Per example, i have a company logo on my main page (let's say company name is..i dunno.. "Google". When i click on it, i wanted it to redirect to the search results of "google", like if i had inserted that in the search field. Is that possible?
(notice that i don't have companies in my database, i'm just trying to give an example so that people can understand what i intend. In my database i would need to link to reflect search results of the field "unidade")
Here is my code so far. The add / update .php i don't think are needed.
<?php
// include the connection file
include "connection.php";
$sql = "SELECT * FROM usuariotb";
if (isset($_POST['search'])) {
$search_term = mysql_real_escape_string($_POST['search_box']);
$sql .=" WHERE nome LIKE '%".$search_term."%'";
$sql .=" OR posto = '{$search_term}' ";
$sql .=" OR nim = '{$search_term}' ";
$sql .=" OR unidade LIKE '%".$search_term."%'";
$sql .=" OR codigoueo LIKE '%".$search_term."%'";
}
$query = mysql_query($sql) or die (mysql_error());
if (isset($_GET['recordId'])) {
$id = mysql_real_escape_string($_GET['recordId']);
$sql_delete = "DELETE FROM usuariotb WHERE id = {$id}";
mysql_query($sql_delete) or die(mysql_error());
header("location:display_data.php");
exit();
}
?>
<html>
<head>
<meta charset="iso-8859-1">
<title></title>
<link rel="stylesheet" type="text/css" href="format.css" />
</head>
<body>
<div class="container">
<form name="search_form" method="POST" action="display_data.php">
Search: <input type="text" name="search_box" value=""/>
<input type="submit" name="search" value="Procurar">
</form>
<div class="container">
<div class="content">
<div class="toolbar">Adicionar Novo Militar</div>
</div>
<div class="toolbar">Voltar à página de pesquisa</div>
</div>
</div>
<div class="container">
<div class="content">
<table width="90%" cellpadding="5" cellspacing="5">
<tr>
<td><strong>Nome</strong></td>
<td><strong>Nim</strong></td>
<td><strong>Posto</strong></td>
<td><strong>Unidade</strong></td>
<td><strong>Sigla Unidade</strong></td>
<td><strong>Observações</strong></td>
<td><strong>Acções</strong></td>
</tr>
<?php if (mysql_num_rows($query)) { ?>
<?php while ($row=mysql_fetch_array($query)) {?>
<tr>
<td><?php echo $row['nome'];?></td>
<td><?php echo $row['nim'];?></td>
<td><?php echo $row['posto'];?></td>
<td><?php echo $row['unidade'];?></td>
<td><?php echo $row['codigoueo'];?></td>
<td><?php echo $row['observacoes'];?></td>
<td>Delete</td>
<td>Edit</td>
</tr>
<?php } /* end loop */ ?>
<?php } else { ?>
<h2> Nothing to display!</h2>
<?php } /* end rows checking */ ?>
</table>
</div>
</div>
</body>
</html>
First of all, I empathize with you regarding being tasked with a more complex task than your current ability. Been there, done that. Many companies do this.
Regarding your task, for search every website usually uses GET to do the search e.g. https://www.google.co.in/search?q=stackoverflow. Notice the q=stackoverflow part. For this you do not need to submit any form, just use the URL directly.
So, I suggest you visit the websites where you want to link directly for search. Search for some sample text, say TEST and observe the URL of the page that opens.
Then using JavaScript/jQuery/etc, on click of the logo, read whatever text you want to search, create a URL in JavaScript and redirect there.
This is the general idea, feel free to comment and ask if you face any issues in implementation.

passing a php array item into a javascript popup window to be edited and updated in mysql db

I am creating a diabetes management system for a university project. One of the features of this system is for the patient to be able to send latest glucose readings and for the nurse to be able to login and comment on those readings.
I have been able to code the patient feature, however I wish to add a comment button in the comments column, which when clicked, brings up a popup window or a textbox for the nurse to be able to comment on that specific record. If a comment has not already been entered, an empty box should come up, however if there has been a previously entered comment, it should be displayed in the box to be updated and sent back to the mysql database. I would like to ask if someone could give me a way to include this comment box and code for the existing value to be displayed in the box and if there is no existing comment, then a new comment can be entered and stored in the database.
Below is my php code.
<?php//run query
$result = mysql_query($GetReadings);
?>
<table>
<tr>
<th>Date</th>
<th>Time</th>
<th>Glucose Level</th>
<th>SBP</th>
<th>DBP</th>
<th>Comments</th>
</tr>
<?php
//display results
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<tr>
<td><?php echo $row["Date"]; ?> </td>
<td><?php echo $row["Time"]; ?> </td>
<td><?php echo $row["GlucoseLevel"]; ?> </td>
<td><?php echo $row["SBP"]; ?> </td>
<td><?php echo $row["DBP"]; ?> </td>
<td><?php echo $row["Comments"];
<?php
//if statement to add comment link if user is a nurse
if ($_SESSION['User_level'] == 2)
{
//code for comments
}
?> </td>
</tr>
<?php
//end of while loop
}
?>
Hope I haven't missed out any crucial information.
Use the javascript function :
window.open(URL, windowName[, windowFeatures])
Where, URL - desired URL to display a page containing Textbox, use any window name you want.
Echo <a> or button with a onclick event eg:
Add Comment
Edit
The most basic way to achieve is, echo a <div></div> containing the past comments, the text box for new comments and Send/Cancel buttons. The trick is to set the display:none style property of that div. You the following code a guideline :
Echo the following code if the User has right user level.
Show Comments
<div id="comment-<?php echo $row['id']?>" style="display:none">
//display previous comments
<form method="post" action="addComment.php?id=<?php echo $row['id']?>">
<textarea name="comment"></textarea>
<input type="submit" value="Add Comment" /><input type="button" onclick="hideComment('<?php echo $row['id']?>')">
</form>
</div>
<script type="text/javascript">
function hideComment(id) {
document.getElementById('comment-' + id).style.display = 'none';
}
function showComment(id) {
document.getElementById('comment-' + id).style.display = 'block';
}
</script>

Categories