I have a list of products on my website a Catalogue. The following PHP Code uses javascript to create a div and insert all the product description links inside it.
$sql = "SELECT * from Products ORDER BY `Name` ASC";
$result = mysqli_query($con, $sql);
echo "<script>document.getElementById('products').innerHTML = '<div class=ks>';</script>";
while($row = mysqli_fetch_assoc($result))
{
$rowid = $row['Id'];
$xx = '<a href="Getdesc.php?hid='.$rowid . '" class=lnk>' . $row['Name'] . '</a><br>';
echo "<script>document.getElementById('products').innerHTML += '$xx';</script>";
}
echo "<script>document.getElementById('products').innerHTML += '</div>';</script>";
Ignore all the ks style sheet class and all the mysql stuff for now.
The problem is it displays the grey backgrounded div (grey from style sheet)
and THEN the links. I need the links to be inside the div.
For a little explanation for those of you who are confused by the pieces of code unrelated to the primary purpose of this question,
The Products table in MySQL is a table that hold all my product info including price, name, id, e.t.c.
the "Getdesc.php?hid=..." link is a link to a php web page that will display all the information about the product from it's Id.
"Products" is an Id of a different div that contains this internal div (With the products I mean) PLUS some other stuff ( I don't feel like telling you all about it).
Sorry for the messy code, thanks in advance.
Javascript:
//from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
function reqListener () {
document.getElementById('products').innerHTML = this.responseText;
}
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "yourFile.php", true);
oReq.send();
PHP
$sql = "SELECT <columns> from Products ORDER BY `Name` ASC";
$result = mysqli_query($con, $sql);
echo '<div class="ks">';
while($row = mysqli_fetch_assoc($result))
{
$rowid = $row['Id'];
echo '' . htmlspecialchars($row['Name']) . '<br>';
}
echo '</div>'
why not put everything in a variable :
$html = '<div class="ks">'; // btw you forgot those double-quotes. you html won't evaluate the class if not surrounded by double-quotes
while($row = mysqli_fetch_assoc($result))
{
$rowid = $row['Id'];
$xx = '<a href="Getdesc.php?hid='.$rowid . '" class=lnk>' . $row['Name'] . '</a><br>';
$html.= $xx;
}
$html.= '</div>';
then echo it? if you're using php, then there's no need to change the page with javascript after it's been loaded, you just sent all the remainder of the page to the client, why not directly put this code at the right place?
echo $html;
Related
I am brand new to programming and I had a unique (I think) question.
I made a MySql database for storing employee records. I am able to submit new employee data to the db and am able to retrieve employee data from the db and display it in an HTML table.
I want to create buttons on the table for each ID#. Each button would redirect you to a different php page and display the employee information associated with the ID# whose button was clicked.
Does anyone know how would I go about doing this?
echo '<table border="0" cellspacing="25" cellpadding="2">
<tr>
<td>ID</td>
<td>First</td>
<td>Last</td>
<td>SIN</td>
<td>Password</td>
</tr>';
function loadList() {
include_once 'includes/dbh.inc.php';
try {
$sqlarray = "SELECT * FROM employee;";
$result = mysqli_query($conn, $sqlarray);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$employeeID = $row['id'] . "<br>";
$employeeFN = $row['firstname'] . "<br>";
$employeeLN = $row['lastname'] . "<br>";
$employeeSIN = $row['sin_'] . "<br>";
$employeePASS = $row['pass_'] . "<br>";
echo '<tr>
<td>'.$employeeID.'</td>
<td>'.$employeeFN.'</td>
<td>'.$employeeLN.'</td>
<td>'.$employeeSIN.'</td>
<td>'.$employeePASS.'</td>
</tr>';
}
}
else {
echo "error no data";
}
} catch (\Exception $e) {
echo ("error");
}
}
Mate, welcome in the programming world. You can create a anchor tag which will redirect user to a new php page with employee id in URL. check below code:
echo '<tr>
<td>'.$employeeID.'</td>
<td>'.$employeeFN.'</td>
<td>'.$employeeLN.'</td>
<td>'.$employeeSIN.'</td>
<td>'.$employeePASS.'</td>
<td><a href="details.php?id='$employeeID.'>View Details</a></td>
</tr>'
Here you need to create a new php page with details.php name. There you need to get employee id by GET global variable and need to fetch details from database to show. Check below code:
<?php
include_once 'includes/dbh.inc.php';
$employeeId = $_GET['id'];
$sqlarray = "SELECT * FROM employee where id = '".$employeeId."';";
$result = mysqli_query($conn, $sqlarray);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$employeeDetails = mysql_fetch_row($result);
Here $employeeDetails has all data which you can use to render in HTML. But please read little bit about SQL injection before using the same code to avoid crashes. Hope it helps you.
You could do like this by adding <a></a> tag
echo '<tr>
<td><a href="show.php?id='$employeeID.'>Show</a></td>
<td>'.$employeeID.'</td>
<td>'.$employeeFN.'</td>
<td>'.$employeeLN.'</td>
<td>'.$employeeSIN.'</td>
<td>'.$employeePASS.'</td>
</tr>';
And in show.php page get this id by $_GET['id']
I have a problem and i can't find any solution on the internet.
So i have a db with about 20 columns. I print from this db only 5 columns for a preview like this:
<?php
$host = "localhost";
$user = "user";
$pass = "";
$db_name = "db_test";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//get results from database
$result = mysqli_query($connection,"SELECT id,first,sec,school,data FROM test");
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table" border ="1">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
?>
After the table is print, I want when click is press to create a new page with all the records from the db for that specific id. I have search over the internet but i can't find any solution. Can anyone help me ?:) Thanks in advice.
I’ve take the liberty of making a few changes to the structure of the code to make it simpler.
The solution is to embed something in an anchor (a) which has a query string linking to the next page. Something of this nature:
details.php?id=…
Anyway, here is a solution:
$thead=array();
$tbody=array();
// Set Properties
$all_property = array('id','first','sec','school','data'); // ***
// Note: corrected an error which incorrectly imploded thead:
$thead=sprintf('<tr>%s</tr>',implode('',$all_property)); // implode & put into a proper row
// Get Data
while ($row = mysqli_fetch_array($result)) {
$tr=array();
foreach ($all_property as $item) {
// Here is a solution: Make id clickable
if($item=='id')
$tr[]=sprintf('<th>%s</th>',$item,$item);
else $tr[]=sprintf('<td>%s</td>');
}
$tbody[]=sprintf('<tr>%s</tr>',implode('',$tr));
}
And in the HTML after the PHP block:
<table class="">
<thead>
<?php print $thead; ?>
</thead>
<tbody>
<?php print $tbody; ?>
<tbody>
</table>
Note the following points:
You shouldn’t put the logic into the HTML part of the document. Here I have just put the data into some variables to be output when the time comes. It’s cleaner and easier to maintain.
The recommend way to push onto an array is to use the $array[]=… notation.
I’m not sure why you are reading the column names if you already know that for your SQL query. However, I’ve left it that way.
I’ve also include suitable th elements and table sections.
That might work …
Basically you can play with hide() and show() using Jquery to achieve this. Initially you load all columns from the db and next you hide using some jquery functions. So on click the table again call jquery show method to display remaining columns
For that, use jQuery or other javascript supports. Basically redirect user to another page with "page?id=1". then extract id from url then use jQuery or js to load the corresponding values.
create a new page with empty form fields. then on load, get url parameter and use javascript to fill the fields.
<?php
$host = "localhost";
$user = "user";
$pass = "";
$db_name = "db";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//get results from database
echo '<table class="data-table" border ="1">
<tr class="data-heading">'; //initialize table tag
$result = mysqli_query($connection,"SELECT id,firstname,lastname,email FROM test");
// Set Properties
$all_property = array('id','first','sec','school','data'); // ***
$thead=sprintf('<tr>%s</tr>',implode('',$thead)); // implode & put into a proper row
// Get Data
while ($row = mysql_fetch_array($result)) {
$tr=array();
foreach ($all_property as $item) {
// Here is a solution: Make id clickable
if($item=='id')
$tr[]=sprintf('<th>%s</th>',$item,$item);
else $tr[]=sprintf('<td>%s</td>');
}
$tbody[]=sprintf('<tr>%s</tr>',implode('',$tr));
}
?>
<table class="data-heading">
<thead>
<?php print $thead; ?>
</thead>
<tbody>
<?php print $tbody; ?>
<tbody>
I have this modal jQuery AJAX:
$('#switch_modal').on('show.bs.modal', function (e) {
var rowid = $(e.relatedTarget).attr('data-id');
$.ajax({
type : 'post', // commented for this demo
url : 'pars.php', // commented for this demo
data : 'id='+ rowid,
success : function(data) {
$('.fetched-data').show().html(rowid); // show rowid for this demo
}
});
});
My mysql query:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
while ($row = $result->fetch_assoc()) {
My modal data-id:
<a href="#viewgame" data-toggle="modal" data-id="<?php echo $row['id'];?>"">
How can i do to use the var rowid like a PHP post? Something like that:
$id = $_POST['rowid'];
echo $id;
If i understand well this test your doing...
Your JavaScript rowid is the value.
The $_POST identifier is id.
Try this in your PHP:
$id = $_POST['id'];
echo $id;
You'll get the javascript rowid sent as a POST value (named as $_POST['id']) via ajax... And returning in data on ajax success.
$('.fetched-data').show().html(data);
So you'll have to use data in your jQuery html()... Wich is the echoed text.
-----
EDIT AFTER ACCEPTATION of this answer
(Based on your last comment)
So i have this query:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
if ($result = $conn->query($query)) {
while ($row = $result->fetch_assoc()) {
$gameid = $row['id'];
}
}
So i want to use $gameid variable into this query:
$sql = "SELECT * FROM games WHERE id='".$gameid."'";
I understand, that you want to get THE LAST matching full line where winner value is empty from games table.
No need for an ajax call...
No need for a second query.
Just do it:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
$result = $conn->query($query);
$row = $result->fetch_assoc();
for ($i=0;$i<sizeOf($row);$i++){ // This is the «size» (number of values) of one row, the last fetched.
echo $row[$i] . "<br>";
}
You'll get all your line values echoed...
This will be the LAST matching line fetched.
If you have many matching lines and want all results, do it like this:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
$result = $conn->query($query));
while ($row = $result->fetch_assoc()) { // While fetching, echo all values of one matching line.
echo "row id: " . $row['id'] . "<br>";
echo "values: <br>";
for ($i=0;$i<sizeOf($row);$i++){
echo $row[$i] . "<br>";
}
}
Notice that this script, that I suggest, will enlight you about the while fetch loop possible results. You'll have to work a little to have it displayed correctly on your page.
;)
So I have this jQuery AJAX call that activates when I click on any of the divs with the class="username" attribute, which contains a user's username, like:
<div class="username">Sneaky</div>
Here's the jQuery AJAX call:
var usersName = '';
$('#chatContainer').delegate('div.username', 'click', function(e) {
usersName = $(this).text();
$.ajax({
method: 'GET',
url: 'profile_popup.php',
data: { usersName: usersName },
success: function(data) {
$("#profilePopup").show().offset({left:e.pageX,top:e.pageY}).html(data);
}
});
});
Here's the PHP file that it calls:
include 'MySQL_connect.php';
$name = mysql_real_escape_string($_GET['usersName']);
$sql = "SELECT chat_color FROM users WHERE username='$name'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$chatColor = $row["chat_color"];
$sql = "SELECT profile_pic FROM profiles WHERE username='$name'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$profilePic = $row["profile_pic"];
echo "<div style='color:$chatColor'>$name</div>
<img style='height:64px' src='../profile/profile_pictures/$profilePic'>";
My problem is that it returns with no error but without the MySQL database values, like so:
<div id="profilePopup">
<div style="color:"> Sneaky</div>
<img src="../profile/profile_pictures/" style="height:64px">
</div>
Any clues as to why this isn't working as intended? I've done quite a lot with jQuery, PHP and MySQL on this site and this seems like it should work correctly.
Don't bite me if I'm wrong, assuming all your SQL codes are correct, can you try
echo "<div style='color:" . $chatColor . "'>" . $name . "</div>
<img style='height:64px' src='../profile/profile_pictures/" . $profilePic . "'>";
-- EDIT --
Perhaps edit your PHP file to:
include 'MySQL_connect.php';
$name = $mysqli->real_escape_string($_GET['usersName']);
$sql = "SELECT `chat_color`, `profile_pic` FROM users LEFT JOIN profiles ON (`users`.`username` = `profiles`.`username`) WHERE `username` = '" . $name . "'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$chatColor = $row['chat_color'];
$profilePic = $row['profile_pic'];
echo "<div style='color:$chatColor'>$name</div>
<img style='height:64px' src='../profile/profile_pictures/$profilePic'>";
I figured it out. I did some testing, and after checking what the javascript "usersName" variable was set to, I noticed that there was a space at the beginning. I don't know why, or how it got there, but it was there. I just did a quick workaround in the PHP file as follows:
$name = mysql_real_escape_string($_GET['usersName']);
$name = ltrim($name," ");
This simply trims the whitespace from the beginning of the string. Thanks for all the help! :)
Try this.
PHP
$text='<div style="color:'.$chatColor.'">'.$name.'</div>
<img style="height:64px"src="../profile/profile_pictures/'.$profilePic .'">';
echo '{"item" :'.json_encode($text).'}';
AJAX
success: function(data) {
obj=$.parseJSON(data);
$("#profilePopup").show().offset({left:e.pageX,top:e.pageY}).html(obj.item);
}
I have a table generated from some PHP code that lists a SMALL amount of important information for employees. I want to make it so each row, or at least one element in each row can be clicked on so the user will be redirected to ALL of the information (pulled from MySQL database) related to the employee who was clicked on. I am not sure how would be the best way to go about this, but I am open to suggestions. I would like to stick to PHP and/or JavaScript. Below is the code for my table:
<table>
<tr>
<td id="content_heading" width="25px">ID</td>
<td id="content_heading" width="150px">Last Name</td>
<td id="content_heading" width="150px">First Name</td>
<td id="content_heading" width="75px">SSN</td>
</tr>
<?php
$user = 'user';
$pass = 'pass';
$server = 'localhost';
$link = mysql_connect($server, $user, $pass);
if (!$link){
die('Could not connect to database!' . mysql_error());
}
mysql_select_db('mydb', $link);
$query = "SELECT * FROM employees";
$result = mysql_query($query);
mysql_close($link);
$num = mysql_num_rows($result);
for ($i = 0; $i < $num; $i++){
$row = mysql_fetch_array($result);
$class = (($i % 2) == 0) ? "table_odd_row" : "table_even_row";
echo "<tr class=".$class.">";
echo "<td>".$row[id]."</td>";
echo "<td>".$row[l_name]."</td>";
echo "<td>".$row[f_name]."</td>";
echo "<td>".$row[ssn]."</td>";
echo "</tr>";
}
?>
</table>
EDIT
Ok, after modifying what #DrColossos posted I have been able to get my links to work correctly, but now I'm having trouble with the uniqueness part. Below is the code I am now using to create my table:
echo "<td>".$row[id]."</td>";
echo "<td>".$row[l_name]."</td>";
echo "<td>".$row[f_name]."</td>";
echo "<td>".$row[ssn]."</td>";
This makes all of the elements of a row hyperlink to Edit_Employee.php?**id**. For instance if the id was one the hyperlink would be Edit_Employees.php?1. Now what do I need to do in my Edit_Employee.php page to get or recognize the id in the link, because it is that id that is unique and that is what I need to base my MySQL search on.
EDIT
Figured it out. This did the trick:
$id = $_GET['id'];
I found that creating my links as I did makes the id a global variable which PHP can pull from the hyperlink. I used the code above in the page that the hyperlink points to and I was able to get what I wanted. Not too hard, but frustrating if you don't know how it is done!
You can already create an unique link with the "ID" of each employee.
You could do the following:
echo "<td><a href="employee.php?id=\"" . $row['id'] . "\">" . $row['id'] . "</td>";
or more readable
echo "<td><a href="employee.php?id=\"{$row['id']}\">{$row['id']}</td>";
Then you can use the employee.php to display it's detail (the id will be in $_GET['id'], see here). Don't forget to check the value of $_GET['id'] before you process it, since it can contain harmfull data (e.g. SQL-Injection).
BTW, the HTML attribute 'id' that you use in the table id="content_heading" is supposed to be unique on the site, just as a site note.