Hi I have a search function in my index.php page. When a user types in a field and enters 'search' it goes to jobsearch.php and prints out the job summary from a mysqli database.
I've created links that go on the end of the results. So when the user sees the job summary the user clicks on the link (click here) then it directs the user to a pop up view which shows more information (job _description) about the job. Is there a way of doing this? I don't want to have to create a html page for every job as there could be 100s of jobs in the database.
I would like the click-here link to take the ID of the desired job and print out the job description on a pop up page.
It looks like this:
this is jobs.php which prints out a list of jobs..
<?php
$servername = "*****";
$username = "root";
$password = "*****";
$dbname = "jobslist";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, job_title, job_description, job_location, job_category FROM jobs_list";
$result = $conn->query($sql);
//display table
echo "<table border='1'>
<!--<tr>
<th>ID</th>
<th>Title</th>
<th>Description</th>
<th>Location</th>
<th>Category</th>
</tr>-->";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td min-height:'200' ><h2>". $row["id"] ."</h2></td>";
echo "<td>". $row["job_title"] . "</td>";
echo "<td min-width:'700' >". $row["job_description"] . "</td> " ;
echo "<td>". $row["job_location"] . "</td>";
echo "<td>". $row["job_category"] . "</td> " ;
//this prints out a clickable link for every job
echo "<td><a href='" . $row['id'] . "'>Click Here</a></td>";
echo "</tr>";
}
}
else {
echo "0 results";
}
echo "</table>";
$conn->close();
?>
Change
//this prints out a clickable link for every job
echo "<td><a href='" . $row['id'] . "'>Click Here</a></td>";
To
echo "<td><a target='jobdescriptionwindow' href='jobdescription.php?id=" . $row['id'] . "'>Click Here</a></td>";
This will open a new window (called 'jobdescriptionwindow') when you click on the link passing the ID of the job clicked through to jobdescription.php. You will also have to make sure that your browser isn't stopping this window from opening.
Create a new PHP document called jobdescription.php with these contents:
<?php
if (isset($_GET['id'])) { // Check ID is is present in parameters
$servername = "*****"; // <-- Enter your details
$username = "root";
$password = "*****"; // <-- Enter your details
$dbname = "jobslist";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// I do: (int)$_GET['id'] to type cast the value of $_GET['id'] to protect against injection. http://php.net/manual/en/language.types.type-juggling.php
$sql = "SELECT id, job_title, job_description, job_location, job_category FROM jobs_list WHERE id = ".(int)$_GET['id'];
$result = $conn->query($sql); // <-- Added new line
$row = $result->fetch_assoc();
echo $row['job_title'] . '<br />';
echo $row['job_description']; //<-- Does now show your description?
var_dump($result); // Lay out this data as required
// Outputs object(mysqli_result)#2 (5) { ["current_field"]=> int(0) ["field_count"]=> int(5) ["lengths"]=> array(5) { [0]=> int(1) [1]=> int(23) [2]=> int(102) [3]=> int(4) [4]=> int(2) } ["num_rows"]=> int(1) ["type"]=> int(0) }
} else {
echo "No ID provided";
}
This will get the details for the job ID sent in the GET parameters.
You do not need to generate a page for every job. You could generate one php that gets a job id as a GET parameter (getJob.php?id=5), fetches the data from data base on that id and returns the data as HTML page.
In addition to beingalex's code, you could also use fancybox to load content in the popup via ajax instead of a new window.
See this page:
http://fancyapps.com/fancybox/
Take a look at examples specifically ajax.
Search for 'ajax' on this page.This is what you need exactly.
jobs.php href-->
echo "<td><a href='something.php?id=".$row['id']. "'>Click Here</a></td>";
Something.php:
if(isset($GET_['id'])){
$getid = $_GET['id'];
$sql = "SELECT job_title, job_description, job_location, job_category FROM jobs_list WHERE id = '".$getid."'";
$result = $conn->query(sql);
while($row = $result->fetch_assoc()){
echo $row['job_title'].'<br />';
echo $row['job_description'].'<br />;
echo $row['job_location'].'<br />;
echo $row['job_category'];
}
}
But this code is attackable with SQL Injection! You need to escape the $_GET param, or you need to learn / use PDO.
Include jQuery,Bootstrap and show information on modal popup. The modal windows opens on job title link click.
<?php
$servername = "*****";
$username = "root";
$password = "*****";
$dbname = "jobslist";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, job_title, job_description, job_location, job_category FROM jobs_list";
$result = $conn->query($sql);
$tbdata = "";
$modals = "";
if ($result->num_rows > 0) {
// display table if results exist
echo "<table class=\"table table-striped\"><tr><th>Job Title</th><th>Location</th><th>Category</th></tr>";
while($row = $result->fetch_assoc()) {
$tbdata.="<tr><td>". $row["job_title"] . "</td><td>". $row["job_location"] . "</td><td>". $row["job_category"] . "</td></tr>";
$modals.="<div class=\"modal fade\" id=\"#jbinfo_". $row["id"] . "\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"jbLabel". $row["id"] . "\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h4 class=\"modal-title\" id=\"jbLabel". $row["id"] . "\">". $row["job_title"] . "</h4></div><div class=\"modal-body\">". $row["job_description"] . "</div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button></div></div></div></div>";
}
echo $tbdata;
echo "</table>";
echo $modals;
} else {
echo "No results";
}
$conn->close();
?>
Before your closing body tag place the following:
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
Related
I use simple AJAX to display data from database. But, when i run it, only 1 data show on my table, the rest of data show outside from my table. Am i missing something ?
I use same code from my standar Bootstrap table and it show data into my table correctly, but not this one.
My PHP file
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tata_kota1";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * from laporan_gini";
$result = $conn->query($sql);
echo "<table border='1'>
<thead>
<tr>
<th>Nomor</th>
<th><b>tipe variabel</b></th>
<th><b>variabel turunan</b></th>
<th><b>nama atahun</b></td></th>
<th><b>turunan tahun</b></td></th>
<th><b>data_content</b></td></th>
<th><b>vertical variabel</b></th>
</tr>
</thead>";
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
{
echo "<tbody><tr>";
echo "<th>".$row['id']."</th>";
echo "<td>".$row['nama_variabel']."</td>";
echo "<td>".$row['nama_variabel_turunan']."</td>";
echo "<td>".$row['nama_tahun']."</td>";
echo "<td>".$row['nama_turunan_tahun']."</td>";
echo "<td>".$row['data_content']."</td>";
echo "<td>".$row['nama_item_vertical_variabel']."</td>";
echo "</tr>";
}
echo "</tbody></table></table>";
}
} else {
echo "0 results";
}
?>
You need to write tbody before the while loop.
Your problem is you have an extra set of {} inside your while and so the echo "</tbody></table></table>"; is inside the while, not outside it. Try this:
if ($result->num_rows > 0) {
echo "<tbody>";
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<th>".$row['id']."</th>";
echo "<td>".$row['nama_variabel']."</td>";
echo "<td>".$row['nama_variabel_turunan']."</td>";
echo "<td>".$row['nama_tahun']."</td>";
echo "<td>".$row['nama_turunan_tahun']."</td>";
echo "<td>".$row['data_content']."</td>";
echo "<td>".$row['nama_item_vertical_variabel']."</td>";
echo "</tr>";
}
echo "</tbody></table></table>";
} else {
echo "0 results";
}
I am trying to get data from a dropdown and post it to a textbox. But by some reason I dont get any response also the Error message that needs to be shown in the textbox.
First of all, this is my dropdown:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM products";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<select class='form-control' id='product1' name='product1' onChange='getProduct1(this.value)' style='width: 100%;'>";
echo "<option selected disabled hidden value=''></option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["id"]. "'>" . $row["article_id"]. " | " . $row["name"]. "</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$conn->close();
?>
After selecting a item in the dropdown the scripts needs to paste . $row["name"]. into the following textbox:
<input type="text" class="form-control" id="product11" name="product11">
The jquery script that I am using to paste the name is the following script:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getProduct1(selectedItem) { // Do an Ajax request to retrieve the information
console.log("getProduct1 before ajax", jQuery('#product1').val());
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: {'product1' : jQuery('#product1').val()},
success: function(response){
// and put the price in text field
console.log("getProduct1 after ajax", jQuery('#product1').val());
jQuery('#product11').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
The script uses the following PHP script that connects with the database and retrieves the relevant information:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) ;
// Check connection
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error) ;
}else {
$product1 = isset($_POST['produc1t'])?$_POST['product1']:'';
$product11 = isset($_POST['product11'])?$_POST['product11']:'';
$query = 'SELECT * FROM products WHERE id="' . mysqli_real_escape_string($conn, $product1) . '"';
$res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0) {
$result = mysqli_fetch_assoc($res) ;
echo $result['product11'];
}else{
$result = mysqli_fetch_assoc($res) ;
echo "Error";
}
}
?>
When I run the script by selecting an option in the dropdown, nothing is happening. Does anyone know what is wrong with my script?
I am not sure you should query the database again for a value you already retrieved. Something like this should work:
jQuery( document ).ready(function() {
jQuery( "#product1" ).change(function(){
var name = jQuery( "#product1 option:selected" ).text().split('|')[1];
jQuery("#product11").val(name);
});
});
You don't need the javascript/jQuery command in the HTML
So I have a user page in which I include several tables, one of which uses a pagination script that is handled by javascript (so that I dont have to refresh the page when looking through the pages) now I'm trying to include this on my user.php page but it doesnt seem to work, any help appreciated
User.php page
<?php require 'session.php';
require 'header.php';
require 'includes/database.php';
$userid = $_GET['id'];
$con = mysql_connect($servername, $username, $password);
if(!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname);
//CLIENT INFO TABLE
include 'user/clientinfo.php';
echo "<br>";
// XLRSTATS TABLE
include 'user/xlrstatsinfo.php';
echo "<br>";
//ALIAS TABLE
include 'user/aliases.php';
//IP TABLE
include 'user/ipaliases.php';
//PENALTY TABLE
include 'user/penalties.php';
//PENALTY TABLE
include 'user/userchatlog.php';
?>
userchatlog.php page
<?php
require '../session.php';
?>
<div id='retrieved-data'>
<!--
this is where data will be shown
-->
<img src="../images/ajax-loader.gif" />
</div>
<link rel="stylesheet" type="text/css" href="http://144.76.158.173/ech/includes/css/main.css" />
<script type = "text/javascript" src = "../includes/js/jquery-1.7.1.min.js"></script>
<script type = "text/javascript">
$(function() {
//call the function onload
getdata( 1 );
});
function getdata( pageno ){
var targetURL = '../includes/pagination/userchatlog/search_results.php?page=' + pageno;
$('#retrieved-data').html('<p><img src="../images/ajax-loader.gif" /></p>');
$('#retrieved-data').load( targetURL ).hide().fadeIn('slow');
}
</script>
and my search_results.php
<!-- include style -->
<link rel="stylesheet" type="text/css" href="http://144.76.158.173/ech/includes/css/main.css" />
<?php
//open database
include '../../database.php';
//include our awesome pagination
//class (library)
include 'ps_pagination.php';
//connect to mysql server
$mysqli = new mysqli($servername, $username, $password, $dbname);
//check if any connection error was encountered
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
function _ago($tm,$rcs = 0) {
$cur_tm = time(); $dif = $cur_tm-$tm;
$pds = array('second','minute','hour','day','week','month','year','decade');
$lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);
for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);
$no = floor($no); if($no <> 1) $pds[$v] .='s ago'; $x=sprintf("%d %s ",$no,$pds[$v]);
if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0)) $x .= time_ago($_tm);
return $x;
}
//query all data anyway you want
$sql = "SELECT * FROM chatlog WHERE msg NOT LIKE '%RADIO%' ORDER BY id DESC";
//now, where gonna use our pagination class
//this is a significant part of our pagination
//i will explain the PS_Pagination parameters
//$conn is a variable from our config_open_db.php
//$sql is our sql statement above
//3 is the number of records retrieved per page
//4 is the number of page numbers rendered below
//null - i used null since in dont have any other
//parameters to pass (i.e. param1=valu1¶m2=value2)
//you can use this if you're gonna use this class for search
//results since you will have to pass search keywords
$pager = new PS_Pagination( $mysqli, $sql, 45, 4, null );
//our pagination class will render new
//recordset (search results now are limited
//for pagination)
$rs = $pager->paginate();
//get retrieved rows to check if
//there are retrieved data
$num = $rs->num_rows;
if($num >= 1 ){
//creating our table header
echo "<table id='my-tbl'>";
echo "<tr>";
echo "<th>Time</th>";
echo "<th>Name</th>";
echo "<th>Message</th>";
echo "</tr>";
//looping through the records retrieved
while( $row = $rs->fetch_assoc() ){
$msg=$row['msg'];
$team=$row['client_team'];
$team = str_replace("42","<img src=images/green.png>",$team);
$team = str_replace("3","<img src=images/red.png>",$team);
$team = str_replace("2","<img src=images/blue.png>",$team);
$team = str_replace("1","<img src=images/grey.png>",$team);
$msg = str_replace("^0","</font><font color=black>",$msg);
$msg = str_replace("^1","</font><font color=red>",$msg);
$msg = str_replace("^2","</font><font color=lime>",$msg);
$msg = str_replace("^3","</font><font color=yellow>",$msg);
$msg = str_replace("^4","</font><font color=blue>",$msg);
$msg = str_replace("^5","</font><font color=aqua>",$msg);
$msg = str_replace("^6","</font><font color=#FF00FF>",$msg);
$msg = str_replace("^7","</font><font color=white>",$msg);
$msg = str_replace("^8","</font><font color=white>",$msg);
$msg = str_replace("^9","</font><font color=gray>",$msg);
$name=$row['client_name'];
$name=htmlentities($name);
$time=$row['msg_time'];
echo "<tr class='data-tr' align='center'>";
echo "<td align=center>";
echo _ago($time);
echo "</td>";
echo "<td align=center>";
echo $team;
echo "<a href='http://144.76.158.173/ech/user.php?id=".$row["client_id"]."' > $name </a></td>";
echo "<td align=left> $msg </td>";
echo "</tr>";
}
echo "</table>";
}else{
//if no records found
echo "No records found!";
}
//page-nav class to control
//the appearance of our page
//number navigation
echo "<div class='page-nav' align='center'>";
//display our page number navigation
echo $pager->renderFullNav();
echo "</div>";
?>
Basically, I want to retrieve a certain product after clicking on an element. I'm using AJAX to pass the variable, and PHP to display the SQL query. I will use the product id on a WHERE statement, to retrieve and display the correct product.
Here is part of my code so far:
<html>
<head>
<title>Left Frame</title>
<link href='http://fonts.googleapis.com/css?family=Indie+Flower' rel='stylesheet' type='text/css'>
<link href="stylesheets/main.css" rel="stylesheet" type="text/css">
<script src="javascripts/jquery-1.11.2.js">
</script>
</head>
<body>
<div class="container">
<div id="bottomHalf">
<img id="blank" src="assets/bottom_half.png" style= "z-index: 5" >
<img src="assets/frosen_food.png"
usemap="#Map2"
border="0"
id="frozen"
style="z-index: 0;
visibility:hidden;" >
<map name="Map2">
<area shape="rect" coords="7,95,126,146" alt="Hamburger Patties" href="#" id="hamburgerPatties">
</div>
</div>
<script language="javascript">
$("#hamburgerPatties").click(function(){
var hamburgerPatties = "1002";
$.ajax({
type:"GET",
url: "topRightFrame.php",
data: "variable1=" + encodeURIComponent(hamburgerPatties),
success: function(){
//display something if it succeeds
alert( hamburgerPatties );
}
});
});
</script>
</body>
</html>
Part of my PHP code:
<?php
$product_id =(int)$_GET['variable1'];
$servername = "************";
$username = "************";
$password = "*************";
$dbname = "poti";
$tableName = "products";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM $tableName ";
$result = $conn->query($sql);
// Display all products on the database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Product ID: " . $row["product_id"]. " - Product Name: " . $row["product_name"]. " Unit Price:" . $row["unit_price"]. "<br>";
}
} else {
echo "0 results";
}
// Display product I clicked on the other frame
if (isset($GET['variable1'])) {
$sql = "SELECT * FROM $tableName WHERE product_id = " . $_GET['variable1'];
$result = $conn->query($sql);
if ($result) {
echo '<table>';
while ($row = $result->fetch_assoc())
{
echo '<tr>';
echo '<td>', "Product ID: " . $row["product_id"]. " - Product Name: " . $row["product_name"]. " Unit Price:" . $row["unit_price"]. "<br>";
echo '</tr>';
}
echo '</table>';
}
}
$conn->close();
?>
I'm able to display all the products. But starting from the ifsset statement, the code no long works. I get no error message or anything. How can I solve this? I'm pretty new to PHP.
EDIT: Ok, I managed to get the product I want when I hard code the product id. Now I need to get this variable using javascript.
You have syntax errors in your if statements.
When you're setting if, you should enclose the statement in braces:
instead of if something : do if(something): and then end it with endif; (when using colons :)
// Display product I clicked on the other frame
if (isset($GET['variable1'])):
$query = "SELECT * FROM $tableName WHERE product_id = " . $_GET['variable1'];
$result = mysqli_query($conn, $query);
if ($result):
echo '<table>';
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td>', $row['product_id'], '</td>'; // and others
echo '</tr>';
}
echo '</table>';
endif;
endif;
Or, use {} braces instead of colons :
// Display product I clicked on the other frame
if (isset($GET['variable1'])){
$query = "SELECT * FROM $tableName WHERE product_id = " . $_GET['variable1'];
$result = mysqli_query($conn, $query);
if ($result){
echo '<table>';
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td>', $row['product_id'], '</td>'; // and others
echo '</tr>';
}
echo '</table>';
}
}
You have syntax error in if block. use {} for if block also use echo instead of pure html tag(table). This error prevents successful state of ajax request. also don't forget to close table.
if ($result)
{
echo '<table>';
while ($row = $result->fetch_assoc())
{
echo '<tr>';
echo '<td>', $row['product_id'], '</td><td>'; // and others
echo '</tr>';
}
echo '</table>';
}
and the ajax code to display php result instead of test alert would be this:
<script language="javascript">
$("#hamburgerPatties").click(function(){
var hamburgerPatties = "1002";
$.ajax({
type:"GET",
url: "topRightFrame.php",
data: "variable1=" + encodeURIComponent(hamburgerPatties),
success: function(data){
alert(data);
}
});
});
</script>
I am trying to write a function that will fetch one column from mysql & return it. some how I am not able to write get_hash() function. Further is it safe to use $GLOBALS?
<?php
//Create Database Connection
$dbhost = "localhost";
$dbuser = "developer";
$dbpass = "abc";
$dbname = "abc";
$connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
//Test Connection`enter code here`
if(mysqli_connect_errno()) {
die("Connection Failed" .
mysqli_connect_error() .
"(" . mysqli_connect_errorno() . ")"
);
}
// Query
$query = "SELECT tweet FROM twc_hashtag";
// Fetch Data
function get_hash() {
if ($result=mysqli_query($GLOBALS['connection'], $GLOBALS['query'])){
while ($row=mysqli_fetch_row($result)){
//echo "<tr>";
//echo "<td>" . $row[0] . "</td>";
//echo "</tr>";
return $row[0];
}
}
//Test Query Error
if(!$result){
die("Database Query Failed" . mysqli_error($GLOBALS['connection']));
}
}
//Close The Connection
mysqli_close($connection);
?>
I need to fetch the data in a different php file & then pass that data to a javascript function. Hence I am going to call get_hash(); from a different php file.