Linking one php script to another - php

What i'm trying to achieve is to link my already completed SQL table query to another SQL table query. So to give some more information we need to make a game for my school assignment. I'm making a little Pokemon battle game. I've queried my SQL table and it's giving me all the Pokemon_Type that it currently has in the table. I want users to be able to click on that table entry that's being displayed and then it queries the database again displaying information on that type. Here is the webpage in question. Don't judge my html skills xD. So as you can see atm there is the 'Electric' type so i'd like to be able to click on that and it refreshes the page and shows all the Pokemon that's associated with that type in the SQL table. Is this possible? and if so how?
Here is my code so far if you'd like to see it.
<!DOCTYPE html>
<html>
<head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px
}
</style>
<title>Pokemon Fight!</title>
<center>Pokemon Fight!</center>
</head>
<body>
Select your type!
<?php
require_once('../mysqli_connect.php');
$query = "SELECT pokemon_type FROM pokemon";
$response = #mysqli_query($dbc, $query);
if($response){
echo '<table align="left"
cellspacing="5" cellpadding="8">
<tr><td align="left"><b>Pokemon Type</b></td></tr>';
while($row = mysqli_fetch_array($response)){
echo '<tr><td align="left">' .
$row['pokemon_type'] . '</td><td align="left"></td>';
echo '</tr>';
}
echo '</table>';
} else {
echo "Couldn't issue database query<br />";
echo mysqli_error($dbc);
}
mysqli_close($dbc);
?>
</body>
</html>

the easiest is to create a link into you pokemon type label to another page passing your type id through href.
Look at this post, it's about what you want to do : PHP passing variable id through href
But using ajax would be better to load informations dynamically without reloading the page

Related

Make elements in a list clickable (PHP)

I'm currently developing a simple web page that enables the user to: upload an image and a corresponding caption to a DB, let the user view the images and delete them.
I have already accomplished the first two with the following code:
<?php
#include_once("connection.php");
$db = new mysqli("192.168.2.2", "root", "", "proyectoti");
if ($db->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo "Información de servidor: ";
echo $db->host_info . "\n";
// Initialize message variable
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); #$_FILES['image']['name'];
// Get text
$image_text = mysqli_real_escape_string($db, $_POST['image_text']);
$sql = "INSERT INTO images (image, image_text) VALUES ('{$image}', '{$image_text}')";
// execute query
mysqli_query($db, $sql);
}
$result = mysqli_query($db, "SELECT * FROM images");
?>
<!DOCTYPE html>
<html>
<head>
<title>Proyecto TI | Sube imágenes</title>
<style type="text/css">
#content{
width: 50%;
margin: 20px auto;
border: 1px solid #cbcbcb;
}
form{
width: 50%;
margin: 20px auto;
}
form div{
margin-top: 5px;
}
#img_div{
width: 80%;
padding: 5px;
margin: 15px auto;
border: 1px solid #cbcbcb;
}
#img_div:after{
content: "";
display: block;
clear: both;
}
img{
float: left;
margin: 5px;
width: 300px;
height: 140px;
}
</style>
</head>
<body>
<h1>Proyecto TI | <a> Interfaz </a></h1>
<div id="content">
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
#echo "<img src='images/".$row['image']."' >";
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>';
echo "<p>".$row['image_text']."</p>";
echo "</div>";
}
?>
<form method="POST" action="index.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<textarea
id="text"
cols="40"
rows="4"
name="image_text"
placeholder="Di algo de esta imagen ^^"></textarea>
</div>
<div>
<button type="submit" name="upload">Publicar</button>
</div>
</form>
</div>
</body>
</html>
It looks like this:
Now, the only part I'm missing is being able to delete an image (basically I only echo each image), how would you suggest for me to accomplish this, to make each item clickable and let's say, pop up a dialog or button to perform an action (delete from DB).
I really don't know much about PHP or CSS/HTML, any help would be much appreciated, Thank you!
Within this loop:
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
#echo "<img src='images/".$row['image']."' >";
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>';
echo "<p>".$row['image_text']."</p>";
echo "</div>";
}
?>
Personally I would add an element to click on - like an 'x' or whatever - with a unique data attribute:
https://www.abeautifulsite.net/working-with-html5-data-attributes
You have to add the unique id of the image obviously, so you can let SQL know which row to delete... Like this:
echo "<div class='delete-image' data-id='" . $row['id'] . "'>x</div>';
Then I would link this class to an AJAX call to make an asynchronous request to the server and delete the image without reloading the page. It's not very hard.
An easier solution would be to create a new form in the loop, so you create multiple forms per image, add a hidden field with the image id in the form and make a submit button with the valeu 'delete' or simply 'x'.
The same way you created the check:
if (isset($_POST['upload'])) { ... }
You can create something like this:
if (isset($_POST['delete-image'])) { ... }
You will be carrying the image id value like a normal form input. And you can do whatever you want with it.
I would HIGHLY suggest you to look into how to work with jquery and ajax calls though.
Opening a dialogue and ask the user before he deletes an item will require that you either go another page for deletion or use javascript for this.
In both cases, you should somehow set an identifier for your image in your html-code.
I would suggest you give every image an id
'<img ... id="'.$yourImageId.'">'
or a data-attribute
'<img ... data-identifier="'.$yourImageId.'" >'
with that identifier.
First variant:
...
echo '<a href="/path/to/delete/view/page.php?image=yourImageId">'
echo '<img ... id="'.$yourImageId.'"/>'
echo '</a>'
...
and on this delete-view-page, you just have a form that triggers your delete-code
<form action="/path/to/delete/view/page.php" method="POST">
<input type="hidden" name="id" value="<?php echo $yourImageId ?>">
</form>
<!-- after this, react with $_POST['id'] --> to the id sent to the server side and delete the image in your database -->
The other way is not server side rendered.
You should give your Elements some class like "my-clickable-image".After that, you have a script on your page, that looks something like the following
<script>
/* get your images with querySelectorAll, the . stands for class and after that your name */
var clickables = document.querySelectorAll(".my-clickable-image");
clickables.foreach(function(image){
// say that for each image, when clicked the generated function is called image.addEventListener('click',generateShowDialogueFunc(image.getAttr("id")));
});
// generate a function(!) that reacts to an image being clicked
function generateShowDialogueFunc(imageIdentifier){
// return a function that adds a Pop Up to the page
// the Pop Up has approximately the code of the first options second page
// except that now, it must create and remove elements in javascript
return function createPopUp(){
removePopUp();
var popup = document.createElement("div");
popup.setAttribute("id","deletePopUp");
var deleteForm = document.createElement("form");
deleteForm.setAttr("action","/path/to/file/that/deletes/given/query.php?id="+imageIdentifier);
var deleteContents = '<p> Do you want to delete this image? </p>'
+ '<button type="submit"> yes </button>'
+ '<button onclick="removePopUp()"> no </button>'
deleteForm.innerHTML = deleteContents;
document.body.appendChild()
}
}
// remove the Pop Up that can be used to delete an image from the page
function removePopUp(){
var existingPopUp = document.getElementById("deletePopUp");
if(existingPopUp) document.body.removeChild(existingPopUp);
}
</script>
<!-- just add some styling to make the popup show on top of the page -->
<style>
#deletePopUp{
width: 50vw;
height: 50vh;
position: absolute;
z-index: 1;
padding: 1em;
}
</style>
In this case, you just call the server to delete the image, not to show the delete form.
I would suggest the second one but stack overflow is not made for opinion based answers.
Regarding simple security:
It looks like your users could give titles or texts to images.
try what happens if a user gives a title like <bold>some title</title>
and guess what would happen if the title is <script>window.location.href="google.com"</script>
(XSS * hint hint *)
Regarding code structure:
If you want to do something like web development more often, think about separating your database accessing code, and your logic code from your php page template code, this is called 3 tier architecture and standard for bigger projects but i guess this is really just a first, short prototype or test.

How to style a table that is part html and part php

I found it hard to phrase this question but I will try my best. I am creating a php and MYSQL leaderboard, it all works but now I want to style it. I don't know very much css and this might be a simple fix. I am trying to style the table so that all the data table elements sit symmetrical like a table should be, and aligned to the center of the headers. I think it is not working because I technically have 2 tables I am trying to style and they are not working in conjunction with each other. Here is the code and forgive my usernames in the table, I get lazy sometimes.
<!DOCTYPE html>
<html>
<head>
<title>Leaderboards</title>
<style type="text/css">
th {
overflow: auto;
font-size: 25px;
border: 1px solid;
padding: 5px;
margin: 2px 2px 2px 2px;
}
td {
font-size: 25px;
padding-left: 30px;
padding-top: 3px;
}
</style>
</head>
<body>
<h1>Leaderboard</h1>
<table>
<tr>
<th>Rank</th>
<th>User</th>
<th>Score</th>
</tr>
</table>
<?php
include 'HytecFunctions.php';
$conn=connectDB();
$rank = 1;
$sql = 'SELECT Name, Score FROM Names ORDER BY Score DESC';
foreach ($conn->query($sql) as $row) {
echo "<table>
<td>$rank</td>
<td>$row[Name]</td>
<td>$row[Score]</td>
</tr>
</table>";
$rank++;
}
$conn->close();
?>
</body>
</html>
The table as it shows in my browser
Because you try to create another table every loop. Try to put them all in a single table.
<table>
<tr>
<th>Rank</th>
<th>User</th>
<th>Score</th>
</tr>
<?php
include 'HytecFunctions.php';
$conn=connectDB();
$rank = 1;
$sql = 'SELECT Name, Score FROM Names ORDER BY Score DESC';
foreach ($conn->query($sql) as $row) {
echo '<tr>
<td>'.$rank.'</td>
<td>'.$row["Name"].'</td>
<td>'.$row["Score"].'</td>
</tr>';
$rank++;
}
$conn->close();
?>
</table>
Note: Don't mind much the way I input your $row variables. Yours will still work even if you use double tick (") to display rows. I just use a single tick (') to display your data as is to have a much cleaner look on your code. Refer here for the difference.

php / mysql sorting issue and form sanitizing?

I'm pretty new to scripting but I've been following code logic pretty well. I've got two working scripts (posted below,) one that posts a form to a mysql database and another the pulls up the information on a same page in a table. I'm having trouble finding help on the following things I want to accomplish.
1.) Sanitizing the form, I've been told it's very open to injection/other. The most people will submit is text, and I'd like for them to eventually be able to post html links that are called up and clickable by the second script.
2.) I want the callback script to sort the information so that the most recent post is on top. (can I create a new mysql column alongside category and contents called "date" that auto detects the date/time and uses it for sorting? I'd love to see some example code of that.
Here's the submit form
<html>
<div style="width: 330px; height: 130px; overflow: auto;">
<form STYLE="color: #f4d468;" action="send_post.php" method="post">
Category: <select STYLE="color: #919191; font-family: Veranda; font-weight: bold; font-size: 10px; background-color: #000000;" name="category">
<option value="category 1">category 1</option>
<option value="category 2">category 2</option>
<option value="category 3">category 3</option>
<option value="Other">Other</option>
</select> <br>
<textarea overflow: scroll; rows="4" cols="60" STYLE="color: #919191; font-family: Veranda; font-weight: bold; font-size: 10px; background-color: #000000; width:300px; height:80px; margin:0; padding:0;" name="contents"></textarea><br>
<input type="submit" STYLE="color: #919191; font-family: Veranda; font-weight: bold; font-size: 10px; background-color: #000000;" value="Create Log">
</form>
</div>
</html>
sendpost.php
<?php
//Connecting to sql db.
$connect=mysqli_connect("localhost","myuser","mypassword","mydb");
header("Location: http://mywebsite.com/myhomepage.php");
if (mysqli_connect_errno()) { echo "Fail"; } else { echo "Success"; }
//Sending form data to sql db.
mysqli_query($connect,"INSERT INTO mydbtable (category, contents)
VALUES ('$_POST[category]', '$_POST[contents]')");
?>
And the get php to call it back on the page
<?php
$con=mysqli_connect("localhost","myuser","mypassword","mydb");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM mydbtable");
echo "<table border='1'>
<tr>
<th>Category</th>
<th>Contents</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['category'] . "</td>";
echo "<td>" . $row['contents'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Also in the cases of connecting with the $con=mysqli_connect command in two of the scripts, is that basically exposed? Can't someone just get to the php and see that information?
I really appreciate the help, very willing to read and learn the right way to do things!
These two questions will help you.
How can I prevent SQL injection in PHP?
How can I specify sql sort order in sql query
SELECT * FROM mydbtable ORDER BY date
And for having db passwords and connections in the open... typically people just include that php file (even though it doesn't make it any safer). However, if you have root access to your filing systems, you could put it in a high enough directory where it is above your htdocs, and it won't be accessible by url.
dbconnect.php
$con=mysqli_connect("localhost","myuser","mypassword","mydb");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
index.php
include 'dbconnect.php';
However, this doesn't actually make it any safer, it only is convenient that you won't accidentally post your code with your password.

displaying fetched mysql data using an external css

How can I attach an external CSS file to display data fetched from a MySQL database? Can I display data using CSS instead of using tables. I want to completely avoid tables in diplaying the fetched data.
This is the code to fetch data from the MySQL database:
<?php
echo "Database Date: " .date("Y-m-d");
?>
Variables included in this data are: Assigned NCL Number, Hospital, Age, Sex, Primary cancer and the date of diagnosis and latest management on the patient.
<style type="text/css">
table.data { width:100%; margin: 0;
border: 1px solid black; border-spacing: 2px; }
.id {width: 7%; background-color: #c7c7c0; }
.date {width: 12%; background-color: #d8d8d1; }
.nclnumber { width: 10%; background-color: #c7c7c0; }
.hospital {width: 17%; background-color: #d8d8d1; }
.age { width: 3%; background-color: #c7c7c0; }
.sex { width: 2%; background-color: #d8d8d1; }
.cancer { width: 10%; background-color: #d8d8d1; }
.dateofdiagnosis { width: 7%; background-color: #d8d8d1; }
.notes { width: 32%; background-color: #d8d8d1; }
</style>
<table class="data" border="0" cellspacing="2">
<tr>
<td class="id"><b>Id</b></td>
<td class="date"><b>Date</b></td>
<td class="nclnumber"><b>NCL Number</b></td>
<td class="hospital"><b>Hospital</b></td>
<td class="age"><b>Age</b></td>
<td class="sex"><b>Sex</b></td>
<td class="cancer"><b>Diagnosed Cancer</b></td>
<td class="dateofdiagnosis"><b>Date of Diagnosis</b></td>
<td class="notes"><b>Notes</b></td>
</tr>
</table>
<?php
// Connects to your Database
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("cancer") or die(mysql_error());
$data = mysql_query("SELECT * FROM cancer WHERE Age ='1'OR Age = '2' OR Age = '3'OR Age = '4'OR Age = '5'OR Age = '6'OR Age = '7'OR Age = '8'OR Age = '9'")
or die(mysql_error());
while($info = mysql_fetch_array( $data )) {
echo "<table class='data' border='0' cellspacing='2'>
<tr>
<td class='id'>".$info['Id']."</td>
<td class='date'>".$info['Date']."</td>
<td class='nclnumber'>".$info['NCL_Number']."</td>
<td class='hospital'>".$info['Hospital']."</td>
<td class='age'>".$info['Age']."</td>
<td class='sex'>".$info['Sex']."</td>
<td class='cancer'>".$info['Diagnosed_Cancer']."</td>
<td class='dateofdiagnosis'>".$info['Date_of_Diagnosis']."</td>
<td class='notes'>".$info['Notes']."</td>
</tr>
</table>";
}
?>
There is absolutely no reason not to use <table> elements for tabular data.
The anti-table hysteria that some people have is simply a misunderstanding: it's bad to misuse tables for layouting purposes. There's nothing wrong with the HTML tag, though. In fact, using any other HTML element to display tabular data is bad for semantics.
The <table> tag and its contained <tr> rows and <td> columns informs the browser rendering it that the data therein is related and columnar. Don't think of the <table> (or any HTML tag for that matter) as strictly a visual display element. They convey meaning about the data to the machine which is parsing it.
Let's sort out a little confusion. Displaying in CSS instead of tables doesn't make since as tables and its associated tags are HTML elements and CSS is styling you can apply to those elements. They are not equivalent.
The alternative to tables would be to create a complex, complicated and convoluted layout using a combinations of divs and spans.
However, there is absolutely no reason why, if the data is tabular, that you should bother with such an awkward design just to avoid the use of the <table> tag. That's why the <table> tag is in the HTML spec.
Abusing the <table> tag for layout purposes has given the tag a bad rep. When used properly though (i.e. to display tabular data) it can be very very useful.
Best advice: use the <table> tag and follow the advice of the community wiki.

Ajax, PHP, MySQL retrieve data

i'm trying to auto retrieve data from mysql server in specific DIV without manual refresh the web page.
My PHP code is:
function lastCodes(){
include('mysql.php');
include('config.php');
echo "<div id='content_data'>";
$get = mysql_query("SELECT * FROM scripts ORDER by date_added DESC");
if(mysql_num_rows($get)>0){
while($row = mysql_fetch_assoc($get)){
$get2 = mysql_query("SELECT * FROM accounts WHERE username = '$row[s_owner]'");
while($red = mysql_fetch_assoc($get2)){
echo "<table>
<tr>
<td width='22px'>";
if(!empty($red['avatar'])){
echo "<center>
<img src='$red[avatar]' style='width: 52px; height: 52px; margin-left: -30px; border: 2px solid #fff;' title='$row[s_owner]'/>
</center>
</td>";
} else {
echo "<td width='22px'>
<center>
<img src='/theme/$tema/icons/empty_avatar.png' style='width: 52px; height: 52px;' title='$row[s_owner]'/>
</center>
</td>";
}
echo "<td>
<a style='font-family: IndexName; color: #000; font-size: 14px; margin-left: 5px;'><b>$row[s_owner]</b> написа <a title='$row[s_name], Категория: $row[s_category].' href='#' style='text-decoration: none;'>нов код</a> <a style='font-family: IndexName; color: #000; font-size: 14px; margin-right: 10px;'>в $row[date_added]</a>
</td>
</tr>
</table>";
}
}
}
echo "</div>";
}
What should be in my case the jquery/ajax code if I want to retrieve this information in DIV called "content_data" in interval of 5 seconds? Thanks a lot!
You could place the contents of your lastCodes() function inside an otherwise empty PHP file, let's call it lastCodes.php.
And then use the load function from JQuery on the page where you want to retrieve the data
<div id="divTarget"></div>
<script type="text/javascript">
$("#divTarget").load("lastCodes.php");
</script>
But keep in mind that this way of coding can get messy real fast. I would recommend you to try any of the many great template systems available. It's not necessary for clean code but without one you will need some discipline keeping logic out of your view code.
And when you feel comfortable with one of those you could go even further and try a template system on the frontend using Javascript, for example Handlebars. With one of those you will be able to write clean code and send your data using JSON which will lower the size of the HTTP response and at the same time make the data more usable for other scenarios than simply rendering it as HTML.
Edit: To update the data every 5 seconds:
<script type="text/javascript">
window.setInterval(function() {
$("#divTarget").load("lastCodes.php");
}, 5000);
</script>
You just have to use the setInterval() function to load the contents of the page every 5 seconds(5000 milliseconds)
</div>
<script src="jquery.js"></script>
<script>
setInterval(function(){
$('#container').load('page.php');
}, 5000);
</script>
I can see that you have a function so you might as well call it. If that doesn't work then try to put your code outside of the function.
lastCodes();
Be sure that its actually changing its contents and that the page that you're calling actually works, you can test it by accessing the page itself and see if it has any output.

Categories