How to dynamically open a new page using this php code? - php

I have this php code which basically retrieves information from a MySQL database and displays it in a table.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<?php
if ( !$conn = new mysqli("localhost", "root", "", "zendesk_data") ){
$output="Connection failed: " . $conn->connect_error;
} else {
$sql = "SELECT id, subject, requester FROM escalationreview";
if ( $result = $conn->query($sql) ){
if ($result->num_rows > 0) {
$output="<table>
<tr align='left'>
<th>ID</th>
<th>Subject</th>
<th>Requester</th></tr>";
while($row = $result->fetch_assoc()) {
$output.= "<tr><td>". $row["id"]. "</td><td>" . $row["subject"]. "</td><td>" . $row["requester"]. "</td></tr>";
}
$output.="</table>";
} else {
$output= "0 results";
}
} else {
$output="Error en la consulta: ".$conn->error;
}
$conn->close();
}
echo $output;
?>
</body>
</html>
This is what my index page looks like:
Now, what I want to achieve is that, when I click in the ticket ID, it opens up that ticket page. So, for example, if I click in ticket with ID 1234 it opens 1234.php and if I click in ticket with ID 1235 it opens 1235.php and so on.
I'm new to php and honestly I have no clue how to achieve this.
Thanks to anyone willing to assist and sorry if this seems like a dumb question. Thanks again.

You can use a common page to pass the ticket ID and retrieve the details.
First, you have to wrap the ticket ID as an anchor link to the page you want to redirect. The link also should have the Ticket ID as a parameter.
$output.= "<tr><td><a href='ticketpage.php?tid=".$row["id"]."'>". $row["id"]. "</a></td><td>" . $row["subject"]. "</td><td>" . $row["requester"]. "</td></tr>";
Then, create a new page with the name ticketpage.php (You can change this if you need to) and retrieve the ID we passed via the link earlier by using the code example below:
<?php
$tid = $_GET['tid'];
// Remaning code

Related

How do I request data from mysql via a URL passed through AJAX

I am creating a page display a list of products and want to be able to filter by category, have pages, a item per page limit and a sort order
on the store page I do a database call to generate all categories and put them in a sidebar.
Then on click/change serialize all the date on the form using $('#form').serialize() then pass it to request_handler.php which will return the correct data.
The problem is, is that because it is all POST data there is no URL reference so people will not be able to link to the results from their choice similar to -
http://www.asos.com/Men/Shirts/Cat/pgecategory.aspx?cid=3602#state=Rf989%3D6200%2C4885&parentID=Rf989&pge=0&pgeSize=36&sort=-1
Also you will not be able to go back and forth because it is all AJAX. I may be able to solve this with history JS but im not sure how to use a url to get the desired results.
<?php
// Database config file, db login settings
require_once '../inc/dbconfig.php';
try {
// connect to database;
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt_all_results = $conn->prepare('SELECT * FROM films ORDER BY category ASC');
$stmt_all_results->execute();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<form id="store">
<ul>
<?php
$category = null;
while($r = $stmt_all_results->fetch()){
if ($category != $r['category']) {
$category = $r['category'];
echo '<li>
<label for="cat-' . $category . '">
<input type="checkbox" name="cat[]" id="cat-'. $category .'" value="' . $category . '">'
. $category .
'</label>
</li>';
}
}
?>
</ul>
</form>
<div class="result"></div>
<?php
// close try
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
<!-- LOAD JQUERY -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function get_data(dat){
$.post( "request_handler.php", dat)
.done(function( data ) {
$( ".result" ).html( data );
});
}
$('li').change(function(){
var dat = $('#store').serialize();
get_data(dat);
})
</script>
Request Handler Script
<?php
// Database config file
require_once '../inc/dbconfig.php';
$category =$_POST['cat'];
foreach ($category as $i){
$options[] = "category='" . $i ."'";
}
$sql = "SELECT * FROM databse";
if (count($options)){
$sql .= " WHERE " . implode(' OR ', $options);
}
try {
// connect to database;
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt_all_results = $conn->prepare($sql);
$stmt_all_results->execute();
# default
$get_pages = isset($_GET['page']) ? $_GET['page'] : 1;
while($row = $stmt_all_results->fetch()) {
$product_title = $row['title'];
$product_image = $row['image_src'];
$product_category = $row['category'];
$product_id = $row['id'];
?>
<ul>
<li>
<img src="<?php echo $product_image; ?>">
<h4><?php echo $product_title; ?></h4>
<p><?php echo $product_category; ?></h4>
More Info
</li>
</ul>
<?php
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
-if this post is confusing don't attack it just suggest rewording as i have been searching all day to solve this issue - thanks
Mixing php with html/js/css nowadays is suggested bad practice. Some sort of framework and templating (separation of logic and data representation) is must have.
Interactive clientside applications for data manipulation should be built using proper instruments, like angular.js, ember.js, whatever. If you try to do that in raw JavaScript, or even using jQuery, you will surely suffer a lot in both development and support of that application.
If you don't want to confuse yourself with clientside frameworks and prefer oldschool way, I'd recommend you take a look at jQuery plugin called jqGrid. It has sorting, filtering, pagination, etc. built in, but you will have to do much work on the serverside anyway.
Also if you want sorting/filtering/page number parameters to be passed in the URL, you'll have to initialize grid properly, set those parameters using grid API, and reload it.
And I'd strongly recommend you try some sort of templating engine anyway. That will make your code much more clear and consistent.

How to make link of the database in PHP

Hi I want to show URL as a link in PHP the URL is shown by query from database but it is not a link so I want to make it link like using but I don't know what I am doing wrong
My data show like this in browser
ID Name URL
2 This localhost/p_uploads/00.jpg
3 Nissan localhost/p_uploads/7a.jpg
I want these URL's to be link so anyone can click on the url to open the image
Here is my PHP Code:
<?php
if(!isset($_COOKIE['loggedin'])){
header("location:index.php");
}
session_start();
if(!isset($_SESSION['user'])){
header("location: index.php");
}
else {
?>
<?php
$con=mysqli_connect("localhost","root","123","user");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"Select * from private_uploads where username = '".$_SESSION['user']."'")
or die(mysql_error());
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>URL</th>
</tr>";
while($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>",'<a href=' . $row['Link'] . '></a>',"</td>";
echo "</tr>";
}
echo "</table>";
//Views Counter
mysqli_close($con);}
?>
<?php
$url = htmlspecialchars($_SERVER['HTTP_REFERER']);
echo "<a href='$url'>back</a>";
?>
replace
echo "<td>",'<a href=' . $row['Link'] . '></a>',"</td>";
for this
echo '<td>[a name here would be nice]</td>';
you are missing the "" in the generated href
You're producing links that look like this:
That's both an invalid URL (unless you really do have a localhost/p_uplaods folder) and a link with no body, so you'll never see it.
If you want to access localhost the host, and not the folder, you should use use an absolute path on the current host, /p_uploads/00.jpg, or a fully qualified URL: http://localhost/p_uploads/00.jpg.
Your link looks like this:
It doesn't have a HTTP protocol. The link should look like this:
You might have a problem on this line:
echo "<td>",'<a href=' . $row['Link'] . '></a>',"</td>";
As you are referring to Link whereas in your database the column is called URL. Also add a text to the tag:
echo '<td>View</td>';

Refresh one variable every second

I want to refresh two variables named profittext and sumtext which will be refreshed and echoed in the following places every few seconds. I know AJAX is needed to do this but how do i actually make it work ? The only way i found out was to refresh the content of the whole file. is there any way to refresh specific variables? Any answers will be greatly appreciated . Thank you very very much.
<table>
if($profitandloss<$zero) {
$profitText = "<div style=\"color: red;\">$profitandloss</div>";
} elseif ($profitandloss>$zero) {
$profitText = "<div style=\"color: green;\">$profitandloss</div>";
}
// for profit and loss counting
$sum+= $profitandloss;
//
echo "<tr><td>" . $row['trade_id'] .
"</td><td>" . $row['selection'] .
"</td><td>" . $row['date'] .
"</td><td>" . $row['type'] .
"</td><td>" . $row['size'] .
"</td><td>" . $row['bidprice'] .
"</td><td>" . $row['offerprice'] .
"</td><td>" . $row['stoploss'] .
"</td><td>" . $row['takeprofit'] .
"</td><td>" . $profitText .
"</td><td><a href ='delete.php?id=".
$row['trade_id']."'>X</a>
</td></tr>";
$profitandloss=0;
if($sum<$zero) {
$sumText = "<div style=\"color: red;\">$sum</div>";
} elseif ($sum>$zero) {
$sumText = "<div style=\"color: green;\">$sum</div>";
}
}
echo "</table><br>";
?>
<!DOCTYPE html>
<html>
<table style="border:1px solid black;">
<tr>
<th style="border:1px solid black;">Profit/Loss</th>
</tr>
<tr>
<td style="border:1px solid black;"><?php echo $sumText ;?></td>
</tr>
</table>
</html>
I struggled with the concept of how to structure such code when I first started too. Although it's not specific to your particular variables, here's a quick example for how to update a var through AJAX with jQuery/PHP.
Prologue: If this is something you're going to be doing often, you'll want to learn jQuery, rather than using normal javascript alone. There are lots of great, free, resources on how to learn jQuery. Alternatively, if you're not satisfied with the free tutorials online, this is an excellent book. I'll write the example in jQuery.
Design: Okay, so the way it works is this:
Set a timer in javascript to execute a particular function every X seconds (you DO NOT want to do it every second).
That function makes an AJAX call (with jQuery) to a .PHP file on the server, sending it the data necessary so that the .PHP code knows what to send back.
The .PHP code grabs the data required (e.g., with MySQL) encodes it in a JSON format, and exits.
A promise on the AJAX call is fired and the data sent from PHP is received. Process it as you will.
Repeat from step 2.
If you have any questions about what the code is doing, please ask.
AJAX.PHP
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$return_obj = array();
$request_obj = NULL;
// our AJAX call used "POST" as it's 'type', so we look in that
// variable.
if ( array_key_exists("func",$_POST) ) {
if ( $_POST['func'] === "get_update" ) {
if ( array_key_exists("which_var",$_POST) ) {
$which_var = $_POST['which_var'];
$which_var = $mysqli->real_escape_string($which_var); // should use prepared statements
// we sent 'num_people_logged_in' as our value here, so we'll be looking for a column/field
// with that value. this assumes that some other code, somewhere else,
// is regularly updating the table. it also assumes that there will only
// be a single row returned, which will hold the value.
$query = "SELECT '$which_var' FROM site_stats ";
if ( $result = $mysqli->query($query) ) {
if ( $row = $result->fetch_assoc() ) {
$request_obj[$which_var] = $row[$which_var];
}
}
}
}
}
$return_obj['request'] = $request_obj;
echo json_encode($return_obj);
die();
?>
MYCODE.JS
// this actually sends the AJAX request to the server.
function getUpdate() {
var jqXHR = $.ajax({
url : "ajax.php",
data : {
'func' : 'get_update',
'which_var' : 'num_people_logged_in'
},
dataType : 'json',
type : 'POST',
timeout : 10000
});
// attach 'promises' to the jqXHR object, which represents
// the AJAX call itself. 'promises' are, in this context,
// just events.
jqXHR.done(function(data,textStatus,jqXHR) {
// this executes if the AJAX call succeeded.
// the variable 'data' holds what the server
// sent us.
if ( ( data ) && ( data.request ) ) {
receiveUpdate(data.request);
}
});
jqXHR.fail(function(jqXHR,textStatus,errorThrown) {
// this executes if it failed
console.log("Fail: " + textStatus + " (" + errorThrown + ")");
});
jqXHR.always(function(a,textStatus,c){
// this executes either way, after .done or .fail
});
}
// this is called from jqXHR.done, on success
function receiveUpdate(request_obj) {
if ( request_obj.num_people_logged_in ) {
updateDOM(request_obj.num_people_logged_in);
}
}
function updateDOM(num_people_logged_in) {
if ( num_people_logged_in ) {
$("#mydiv > p.update").html("The updated value is: " + num_people_logged_in);
}
}
var timeoutID = null;
// setup our timer, to periodically make an
// AJAX call
function init() {
timeOutID = setInterval(function(){
getUpdate();
},5000);
}
// stop the timer
function cleanup() {
clearTimeout(timeoutID);
}
INDEX.HTML
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>AJAX practice</title>
<!-- <link href="mycss.css" rel='stylesheet'> if needed -->
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="mycode.js"></script>
<script>
$(document).ready(function() {
init();
$("#cleanup").on("click",function(){
cleanup();
});
}); // end ready
</script>
</head>
<body>
<div id='mydiv'>
<p>
How many people are online?
</p>
<p class='update'>
</p>
</div>
<button id='cleanup'>Stop updating!</button>
</div>
</body>
</html>
You will needd two PHP pages:
- one with HTML and JS, which periodicly makes ajax calls and puts the result to the HTML
- second with json (or even plain text) output of your dynamic data piece
Unfortunately, writing the full code in the answer is not someting that people do at stackoverflow, so just look at small example below, and try to figure out the missing parts.
http://jsfiddle.net/AMEqz/
var xhr = new XMLHttpRequest();
xhr.onload = function(r) {
// your render logic HERE
setTimeout(send, 1000);
}
function send() {
xhr.open("GET", "/", true);
xhr.send();
}
send();
p.s.: keep in mind that each ajax request will mean extra connection to your server, so make sure it can deal with the load ;)
Use a timer : https://developer.mozilla.org/en/docs/DOM/window.setInterval
setInterval(function(){
//update your var here
},1000);

Calling a random record on pageload via PHP, dynamically displaying result via AJAX

this is something I've been stuck on for around 7 hours total over the last 3 days, and it is driving me absolutely insane. Any assistance you could lend me with be greatly appreciated.
Basically I want to:
Call a PHP function on pageload which randomly selects a record from
my MySQL database
Dynamically display that record in a HTML page
(Once I've got that down, I also want to be able to trigger that this process on the click of a button.)
Before tackling this task, I put together a prototype which dynamically displays a specific record via a HTML dropdown menu: http://lrdondmt.com/week13/ajaxprototype1.html
I've been trying to modifications to this code to achieve the above.
My PHP looks like this:
<?php
// connect to database
$username= "**withheld**"'
$password="**withheld**";
$database="**withheld**";
$table="banddb";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
// the query itself, selects random record from database
$sql="SELECT * FROM banddb WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM quotes ) ORDER BY id LIMIT 1";
$result = mysql_query($sql);
// echo result
while($row = mysql_fetch_array($result))
{
echo '<b>Band name:</b> ' . $row['bandname'] . '</br></br>';
echo '<b>Location:</b> ' . $row['city'] . ', ' . $row['state'] . '</br></br>';
echo '<b>Image:</b> </br></br>' . '<img src="http://lrdondmt.com/discovermusic/images/' . $row['imgpath'] . '" />' . '</br></br>';
echo '<b>About the band: </b>' . $row['abouttheband'] . '</br></br>';
echo '<img src="http://www.lrdondmt.com/discovermusic/images/bandcamp-icon.png" alt="Find on the band on Bandcamp" />' . '</br></br>';
echo '<img src="http://www.lrdondmt.com/discovermusic/images/facebook-icon.png" alt="Find on the band on Facebook" />' . '</br></br>';
echo '<b>Bandcamp player:</b> </br></br>' . '<iframe width="300" height="100" id=bandcampplayer src="http://bandcamp.com/EmbeddedPlayer/v=2/album=' . $row['bandcampid'] . '/size=grande/bgcol=e9e9e9/linkcol=890101/" allowtransparency="true" frameborder="0" >' . '</br></br>';
}
echo "</table>";
// close connection
mysql_close();
?>
My HTML document looks like this:
<!DOCTYPE html>
<html>
<head>
<title>AJAX prototype 2</title>
<script type="text/javascript" >
function showRecord()
{
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
xmlhttp.open("GET","getmusic2.php",true);
xmlhttp.send();
}
</script>
<script type="text/javascript" >
$(document).ready(function(showRecord))
</script>
</head>
<body>
<div id="txtHint">
<em>Your content should appear here.</em>
</div>
</body>
</html>
If you need any further info, please just ask.
Since you are already using jQuery, you could replace your whole showRecord() function with this more simple jQuery function :
$.ajax({
url: 'getmusic2.php',
success: function(data) {
$('#txtHint').html(data);
}
});
Also, your on load call should look like that :
$(document).ready(function() {
showRecord();
});
Your closure looks wrong when calling your ajax function, fix this line
$(document).ready(function(showRecord))
to look like this
$(document).ready(function(){showRecord()})

Trying to make an function call to an external file with PhP, MySQL using WAMP

I'm sure there is a simple answer to this, but I have been fumbling with everything for almost a week now and surrender. I am trying to build a shopping cart app and every coding solution I build will work when I include the code on the same page, but when I try to use an external page to run the function it does not seem to return the data. I have tried various monitoring techniques to determine what it is happening.
Here is the code for the main page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Cart Connection</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<p>Will this display?</p>
<p><a href='<?php echo "showCart.php?PHPSESSID=" . session_id() ?>'>View Cart</a></p>
<?php
$Database = "L3TtL2B5DdY";
$Table = "tblProds";
if (isset($_SESSION['curCart']))
$Cart = unserialize($_SESSION['curCart']);
else
{
if (class_exists("shoppingCart"))
{
$Cart = new shoppingCart();
$Cart->setDatabase($Database);
echo ("<p>If statement ran successfully</p>");
}
else
exit("<p>The shoppingCart class is not available!");
}
$Cart->setTable($Table);
$Cart->getProductList();
$_SESSION['curCart'] = serialize($Cart);
?>
<p><a href='<?php echo "showCart.php?PHPSESSID=" . session_id() ?>'>View Cart</a></p>
</body>
</html>
Here is the relevant code on the "shoppingCart.php" page:
<?php
class shoppingCart
{
private $dbConn = "";
private $dbName = "";
private $tableName = "";
private $orders = array();
private $orderTable = array();
function _construct()
{
$this->dbConn = #new mysqli("localhost", "root", "");
if (mysqli_connect_errno())
die("<p>Unable to connect to the database server.</p>" . "<p>Error Code " .
mysqli_connect_errno() . ": " . mysqli_connect_error() . "</p>");
}
public function setDatabase($Database)
{
$this->dbName = $Database;
#$this->dbConn->select_db($this->dbName)
Or die("<p>Unable to select the database.</p>" . "<p>Error code " . mysqli_errno($this->dbConn) .
": " . mysqli_error($this->dbConn) . "</p>");
}
public function setTable($Table)
{
$this->tableName = $Table;
}
public function getProductList()
{
$sqlString = "SELECT prodID, prodName, prodPrice FROM $this->tableName";
#$qryResult = $this->dbConn->query($sqlString)
Or die("<p>Unable to perform the query.</p>" . "<p>Error code " . mysqli_errno($this->dbConn) .
": " . mysqli_error($this->dbConn) . "</p>");
echo "<table width='100%' border='1'>";
echo "<tr><th>Product ID</th><th>Product Name</th><th>Product Price</th><th>Select Item</th></tr>";
$row = $qryResult->fetch_row();
do
{
echo "<tr><td>{$row[0]}</td>";
echo "<td>{$row[1]}</td>";
echo "<td>{$row[2]}</td>";
echo "<td><a href='showCart.php?PHPSESSID=" . session_id() . "&operation=addItem&productID=" . $row[0] .
"'>Add</a></td></tr>";
$row = $qryResult->fetch_row();
} while ($row);
echo "</table>";
}
......
?>
When I try to load the main page it will display the two lines and that is all. I debugged all the errors when I first created the code and thought it would work. When I wrote the original version of this page I put the "connection" code on the same page and the table displayed fine, so I don't know what else it could be.
I installed WAMP on my Windows XP box and it seems to work fine. I haven't touched the configuration files for any of the programs and all my other test code seems to work fine. It is just when I try to contact an external file.
Any help would be greatly appreciated as I think my brain is turning to mush.
Thanks
You probably need to include the ShoppingCart.php file in your main page, so it has the definition of the ShoppingCart class. Try putting at the top of your main page:
<?php require('ShoppingCart.php'); ?>
What I think might be happening is that the cart object is getting unserialised from the Session, but there is no class definition, so it becomes an instance of an incomplete class. When you then call a method on it you are getting a fatal error. What probably doesn't help is that you may not be displaying errors, so the script will just end. You could also try putting at the top of the main page:
<?php ini_set('display_errors', true); ?>
This should make PHP errors get shown.
Edit
It might be worth pointing out that you can't store a database connection in the session. You need to connect to the server / select the database etc. on every request. I don't think your script is currently doing that.
Also, you can store objects in the session without worrying about the serialisation yourself, here is a quick example:
<?php
//include class definition before starting session.
require('ShoppingCart.php');
session_start();
if (!isset($session['cart'])) {
$session['cart'] = new ShoppingCart();
}
$cart = $session['cart'];
//do stuff to cart
$cart->doSomething();
//changes are now saved back to the session when the script is terminated, without you having to do anything.
You need to
include_once("ShoppingCart.php");
Read up on the different ways to include files
http://www.w3schools.com/PHP/php_includes.asp

Categories