PHP get information from database when echoed html code is clicked - javascript

In my code, I am retrieving data from the database using a while loop so i can have all the $FormData['fullname'] in the db.
What i want to do is, have each name display on the page and also have clickable so when someone clicks a name, it gets their user_id and pulls up information about them.
The problem i am having is that I can't figure out a way to make a it so where i can get the user_id when the user clicks a name. I tried putting a "name" in the button attribute and I checked if isset() but that didn't work.
If someone can properly figure out a way for me to basically, display all the fullnames in my database and when someone clicks a name, it pulls up information about them that is stored in the database. Here is my code
$stmtGet = $handler->prepare("SELECT * FROM formdata");
$stmtGet->execute();
while($formData = $stmtGet->fetch()){
echo "<button name='name'>$formData[fullname]</button>";
if($_SERVER['REQUEST_METHOD'] =="POST"){
if(isset($_POST['name'])){
echo "ok";
}else{
echo "bad";
}
}
}

As far i can see you are trying hit a button inside the while loop , i would not say its a bad approach , but i will suggest you not to do that . and from your code i can see you have lack of understanding post and get request learn from here . and other than this you need to know the transition of web url . how its actually works . anyway , i have given a sample code without . i hope it will help you understanding this concept.
$stmtGet = $handler->prepare("SELECT * FROM formdata");
$stmtGet->execute();
while($formData = $stmtGet->fetch(PDO::FETCH_ASSOC)){
$id = $formData['formdataid'];
echo "<a href='somepagename.php?infoid={$id}'>". $formData['fullname']."</a></br>";
}
now in the somepagename.php file or in the same page you can actually show the details information for instance
if(isset($_GET['infoid'])){
$stmt = $handler->prepare("select * from formdata where formdataid='"$_GET['infoid']"'");
$qry = $stmt->execute();
$row = $qry->fetch(PDO::FETCH_ASSOC);
echo "<p>id =".$row['formdataid']."</p></br>";
echo "<p>id =".$row['name']."</p></br>";
echo "<p>id =".$row['email']."</p></br>";
echo "<p>id =".$row['address']."</p></br>";
code is not executed , it may have semicolon or comma error warning . you have to fix those on your own . this example above shown you only the way it works .
if still you have problem ask , or see the documentation

I should stress that this is not production code and you should totally validate the data input coming in before posting queries to your DB. You can do something like this.
<?php
// Connect
$connection = mysqli_connect('localhost', 'username', 'password', 'database','port');
// Grab all users
$sql = 'SELECT * FROM users';
$users = mysqli_query($connection, $sql);
if (($_SERVER['REQUEST_METHOD'] == 'POST') && !empty($_POST['user_id'])) {
$query = "SELECT * FROM users WHERE user_id = {$_POST['user_id']};";
$user = mysqli_fetch_assoc(mysqli_query($connection, $query));
}
?>
// This only runs if our $user variable is set.
<?php if (isset($user)) : ?>
<?php foreach ($user as $key => $value) : ?>
<span><?= print_r($value) ?></span>
<?php endforeach; ?>
<?php endif; ?>
// Display all users in a dropdown and when the button is clicked
// submit it via post to this page.
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post">
<select name="user_id">
<?php foreach ($users as $user) : ?>
<option value="<?= $user['user_id'] ?>"><?= $user['name'] ?></option>
<?php endforeach; ?>
</select>
<button type="submit">Submit</button>
</form>
This is going to refresh your page every time. If you want to have an interactive page you are going to need to use JavaScript/AJAX to update the page elements without reloading the page. This example just demonstrates how you can achieve this with PHP and HTML.

you need to know about server-side language(php) and client-side language(javascript).
php runs before page loaded. it cannot runs when click something by itself(with ajax, it can).
most interactions without page move runs with javascript.
in your case, there are two methods.
store all information into hidden input or button's attribute. and get them by user_id via javascript.
use ajax to call another php that can select informations you need by user_id.
both use javascript or jquery. so you must learn about them.

Related

Redirect and popup when sql is done

I want to get my application when a item is deleted pop up a messege and redirect to another page. I used javascipt for the popup and php header for the redirection. Now its only doing or the popup or the redirect depending which one is listed first. how do i fix this?
<?php
session_start();
require_once('../../includes/mysql_config.php');
$id = isset($_SESSION['id']) ? $_SESSION['id'] : header('location: ../../login.php');
$Cursist = mysqli_query($con, "SELECT id FROM users WHERE id =".$_SESSION['id']);
if(!$Cursist){
header('location: ../login.php');
}
$test = $_GET['id'];
$sql = "DELETE FROM cursus WHERE id = $test";
$result = mysqli_query($con, $sql);
if ($result) {
echo "<script type='text/javascript'>alert('Verwijdert!')</script>";
header("Location: ../cursussen.php?destoyed=true&destroyed_id=".$_GET['id']);
}else {
echo "mislukt";
}
?>
If you send sometrhing before header will not work. You can use only header before sending sometrhing to the client.
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
http://php.net/manual/en/function.header.php
You could do with javascript but It not recommended because the user could have javascript disabled:
echo "<script type='text/javascript'>";
echo "alert('Verwijdert!')";
echo "document.location.href='index.html'";
echo "</script>";
The best way is to use session and header, you can save a var in session and show a message when the var is true and when you show the messasge delete the session var
delete.php
$_SESSION['deleted'] = true;
header("Location: index.php);
index.php
<?php if($_SESSION['deleted']){ ?>
<?php unset($_SESSION['deleted']) ?>
<div>Item was deleted</div>
<?php } ?>
Well, the problem is that the redirect immediately moves you to a new page, so any javascript on the old page becomes irrelevant. You might be able to use a delay before redirect so that the javascript alert can display.
Otherwise, introduce a variable that you send to the redirect destination page, and use this variable to trigger a javascript popup there.

outputting data From Mysql to js/HTML

So Basically this is what i want to do , I want to take data from my database and then put that data on a page after the user logs in , however i am havinng problems understanding a way , So here's some sample code for clarity :
//user has logged in:
//fetched data from database to php file
$name = $result['name'] //result being the object after the queried row is fetched
now i want to add this name in lets say a div in my HTML
<div id="name"><!--$name comes here--></div>
So what is the way to do this using JS ? is AJAX the answer?
I guess that you have $name in the login.php file and the div is in profile.php. You can use session variables or ajax:
By php:
login.php
<?php
session_start();
$_SESSION["name"] = $result['name']
?>
profile.php
<?php
session_start();
?>
<div id="name"><?php echo $_SESSION["name"]; ?></div>
By ajax:
getName.php
$name = $result['name'];
echo $name;
profile.js
$.get("getName.php", function(data, status){
$("#name").append(data);
});

Post data to one page but navigate to another [duplicate]

This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 7 years ago.
I have a drop down box from which the user selects a value. I want to post this value to Map.php where it will be used. I currently have my form posting to Map.php which is fine - however, I want to navigate to index.php after the user has made their selection and clicked the button, rather than navigating to Map.php. I have looked for a solution to this, but they all appear to be for situations where you would be visiting the page that the data is posted to...
userInterface.php
<form name="formname" method="post" action="Map.php">
<div id='userList'>
<?php
//get constants for database
require("database.php");
// Opens a connection to a MySQL server
$connection = mysqli_connect ($server, $username, $password);
$query = "SELECT distinct user FROM route";
$result = mysqli_query($connection, $query);
echo '<select name="dropdown" style="width:400px;">';
$count = 1;
while($r = mysqli_fetch_assoc($result)){
echo "<option value =".$count.">".$r['user']."</option>";
$count++;
}
echo '</select>';
?>
<input type="submit" id="button" value="Get Started!" />
Map.php
$value = $_POST['dropdown'];
if($value==1){....
Just use header like this :
header('Location: http://www.example.com/');
Based on PHP docs : http://php.net/manual/en/function.header.php

Assign a PHP variable into a javascript variable not working As expected

Hi I am checking my company web sites XSS vulnerability , by adding some script tags to inputs . actually my company site was vulnerable .
<script>alert("Xss Attack");</script>
This alerts
Xss Attack
Now I am trying to do more testing to understand it more , now I am trying to get the session id and pass it to some other web site , then I will get the session id and I will gain the user access using that session_id . this is my code to get session_id , I typed this to my input field and submitted the form.
<script>var sess_id = "<?php echo session_id(); ?>"; alert(sess_id); </script>;
but this only alert <?php echo session_id(); ?>
In my php I out put the variable as
<td> <?php echo $name;?> </td>
BUT
In my PHP page if I directly type the code
<script>var sess_id = "<?php echo session_id(); ?>"; alert(sess_id); </script>
It correctly gets me the session id like ba6k806tlcbvqs0l39ipcms956
I think in my 2 nd case it works correctly because it has no wrapping PHP tags.
In the 1 st case It has wrapping PHP tags <?echo $name;?> .
So how should i add the session_id to javascript variable sess_id ? , please help . thanks in advance :)

Fetch altered data after page is updated

When update button is submitted a function edit_page() is called. This function alter the database table row with new data entered.
This works fine table altered correctly entries are ok.
But problem is that when update button is submitted
1. Entries is database inserted or altered correctly.
2. But when page reloads content of this updated page remains as it is as previous or like before updation on front end or just after submission.
My code:
<?php
function edit_page()
{
add_cat();
global $page_id;
?>
<?php
if (isset($_GET['page_action']) && ($_GET['page_action'] == 'edit'))
{
$page_id = $_GET['post'];
}
?>
<?php
$page_id = $_GET['post'];
$result = mysql_query("SELECT * FROM pages WHERE page_id = '$page_id'"); //execute the SQL query and return records
$row = mysql_fetch_array($result);
$page_title = $row['page_title'];
$page_content = $row['page_content'];
?>
<form method="post" action="" name="edit_page" class="edit_page">
<h4>Page Title:</h4> <input type="text" name="title" class="title" placeholder="Add title of the Page" required value="<?php echo $page_title;?>"/><br/>
<h4>Page Content:</h4><br/>
<textarea cols="80" id="content" name="content" rows="10"><?php echo $page_content;?></textarea>
<input type="hidden" name="page_edits" value="yes" />
<input type="submit" name="edit_page" class="button" value="Update"/>
<?php
save_edits(); }
function save_edits()
{
if (isset($_POST['edit_page']) && $_POST['page_edits'])
{
$page_id = $_GET['post'];
$page_id = $_GET['post'];
$page_title = $_POST['title'];
$page_content = $_POST['content'];
$date = date('Y-m-d h:i');
$query = "UPDATE pages SET page_title='$page_title', page_content='$page_content', date_gmt='$date' WHERE page_id = '$page_id'";
$result = mysql_query($query) or die("Unable to create Page: " . mysql_error());
}
}
?>
<div class="right_sidebar">
<?php edit_page();?></div>
Finally, my mean is that i just want functionality like wordpress in which when update button is clicked just after that we see updated data.
You're doing PHP the procedural way here. That means the statements are executed one after another so the problem lies in the way you place your statements.
In your code, you are displaying the form first and only then updating it, so that's why the previous values get fetched although update is happening only later.
Solution: The function save_edits() and its call should come first followed by edit_page().
Another important thing in terms of security, you are directly inserting the value you get from the address bar. Right now the way it is, someone can drop your whole table by writing in a piece of code. You could use mysql_real_escape_string() to prevent it (although not totally) or better yet:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Lastly, you are not closing your <form> tag.

Categories