How can i use selected link value on another php page - javascript

I'm new with questions and generally with "Stack Overflow", so forgive me if it is not formatted well.
So, I have problem with transferring some informations from one page to another. It is a value of <a> tag from an php while loop.
At the moment I have something like this:
$query = mysql_query("SELECT DISTINCT `a`.`id`,`o`.`first_name` , `o`.`last_name` , `a`.`name` FROM `owner` AS `o` , `animal` AS `a` WHERE `o`.`id` = `a`.`fk_current_owner` AND `o`.`fk_user` = '".$_SESSION['user_id']."'");
while($row = mysql_fetch_assoc($query)){
$pet_id = $row['id'];
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$pet_name = $row['name'];
echo 'Owner: <strong>'.$first_name.' '.$last_name.'</strong> ';
echo 'Pet: <strong>'.$pet_name.'</strong><br>';
}
So you can assume that this will display names of pets that logged user got.
So I linked their names and I need to get ID of selected name on another page so I can display details of pet on page viewPet.php.

You can also send the pet id along as a GET parameter with the link.
echo ''.$pet_name.'';
On the viewPet.php page you'd access it by $_GET['id']

you can put the link in a cookie:
setcookie(name, value, expire, path, domain);
that is the code to set the cookie and then to receive the cookie you can do $_COOKIE['name'];
or you can do a session.
session_start();
$_SESSION['name']=value;

Related

how to display form content after php processing

Im creating a forum for a little project of mine.
So far I have been able to get the form contents and use php to process (YES I HAVE NOT ACCOUNTED FOR SQL INJECTION).
Anyway, the php code is as follows:
test.php
<?php
if (isset($_POST["add"])){
// "Save Changes" clicked
$title = $_POST['title'];
$message = $_POST['message'];
$username = 'root';
$password = '';
$db = 'main_database';
$conn = mysqli_connect('localhost', $username , $password,$db);
if (!$conn){
die("unable to connect");
}
$dt = date('Y-m-d h:i:s');
$sql = "INSERT INTO threads (title,author,date_posted,post) VALUES ('$title', 2, '$dt', '$message')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
header('Location: http://127.0.0.1:5500/RuneScape_website/RS.com/aff/runescape/forums/ForumThread/~tm10CE.html');
}
?>
Now what I really want to do, is after this data has been saved to the database, I want to display the newly created blog comment to the direct page on load up. For example, When you click submit, the comment should appear in the directed html page.
The only way I think about it, is that I need either javascript to create a new attribute and append it to the list of existing attributes (e.g. ), or in the php create the div and use javascript/JQuery to access the php file and collect the html.
So I want the $title and $message to be used in the html page where its directed to.
A real example is like stack overflow. After I write an answer the page appends my response. This is what I want to achieve.
I'm curious how to go about this. Thanks :)
Don't you need to know which forum page this submitted comment belongs to?
If you add a column to threads table and store the name of the forum page in it (in this case: ~tm10CE.html), then from your html page, you can make an ajax call to a php file and include the name of the page as a querystring value. Inside the php file, query the threads table for the name of the page and return all the entries related to that page.

posting data from website to MySQL using PHP does not work

I am new on PHP and trying to do get the user agent from the visitor of the website then send this information to the MySQL.
Home.html (this page has a button where the user should click on it to take him to another page where he will see his device information
<div id="TestMe_img">
<a href="Result.php">
<input type="submit" value="Test Your Device">
</a>
</div>
Result.php (the result page contain 2 things: 1- php code. 2- html code)
PHP
<?php
$server = "localhost";
$user = "root";
$pass = "";
$dbname = "user_data";
$userAgent = $_POST['userAgent'];
// Create connection
$conn = new mysqli($server,$user, $pass, $dbname);
// Check connection
if($conn -> connect_error) {
die("Conneciton Failed: " . $conn -> connect_error);
}
if (empty($userAgent)) {
echo "User Agent is blank";
die();
}
$sql = "INSERT INTO UserData (UserAgent) VALUES ('$userAgent')";
if ($conn -> query($sql) === TRUE) {
echo "Thank you! Hana is stupid";
}
else
echo "Unfortunately Hana is smart";
$conn -> close();
?>
HTML Part
<body onload="userAgent();">
<table>
<tr>
<td>user agent</td>
<td id="userAgent"></td>
</tr>
</table>
</body>
JavaScript
function userAgent(){
var userAgent = navigator.userAgent;
document.getElementById('userAgent').innerHTML = userAgent;
}
However, there is a mistake that I can not find because every time I click on the button it takes me to the result.php and show me the code on the browser with no result appear on the database!
OK, this is going to be slightly longer, but bear with me.
1st: You will be getting a "User Agent is blank" message, because the user agent is not actually submitted to the PHP page. You need to put an input (hidden or text) into a form, push the data inside and then submit that form. Change your HTML like this, then at least your date will be submitted:
<form method="post" action="Result.php">
<input type="hidden" id="userAgent">
<input type="submit" value="Test Your Device">
</form>
2nd: You don't even need to do that, because the userAgent is available to PHP already, even without submitting it manually. Just use this variable:
$_SERVER['HTTP_USER_AGENT']
3rd: You should NEVER put unsanitized input into an SQL string. This will lead to SQL injections and your server will be hacked.
Instead of:
$sql = "INSERT INTO UserData (UserAgent) VALUES ('$userAgent')";
$conn->query($sql);
You have to use a prepared statement (for pretty much any query that accepts variables), so that nobody can manipulate your query. Otherwise if your $userAgent variable contained a single quote, you could break out of your query and the attacker could inject any SQL code he wanted. So do this to fix your security issue:
$statement = $conn->prepare("INSERT INTO UserData (UserAgent) VALUES (?)");
$statement->bind_param('s', $userAgent);
$statement->execute();
The 's' parameter is actually one letter per each parameter you want to prepare in the statement. In this case it indicates you want to pass a string. "i" would be an integer, "d" a double, see here for more: http://php.net/manual/de/mysqli-stmt.bind-param.php
4th: Your question has absolutely nothing to do with phpMyAdmin, so you should probably change the title.
I hope this helps you get started.

Set java script value to php session and get session value onto another php file

I'm trying to set the JavaScript value to a PHP Session variable and get this session value to another php page.
here my code.
on the same it will show the value using alert.
here's my first page index_1.php
<Script>
function(no_user){
`var num_user = no_user;
'<?php $_SESSION["num_user"] = "' + no_user+ '"; ?>';
//alert('<?php echo $_SESSION["num_user"] ?>');*/
window.open("demo.php");
}
</script>
another page index_2.php
<?php
if(isset($_SESSION['num_user'])){
$a = $_SESSION['num_user'];
echo "Number of user: ". $a;
?>
You can not set php variable in js try to set it another location(demo.php)
<script>
function(no_user){
var num_user = no_user;
window.open("demo.php?no_user="+no_user);
//or window.location = 'index2.php?no_user'+no_user;
}
</script>
and set session on demo.php/index2.php
session_start();
if(!empty($_GET['no_user'])) {
$_SESSION['num_user']= $_GET['no_user'];
}
Just make sure to set session_start() in all PHP.Files before accessing $_SESSION-Variables and you're fine. PHP will automagically take care of re-using that session in other .php-files (same server, same domain etc.).

DELETE query onclick automized

Having a slight problem here. I'm trying to create an admin side function to delete FAQ's, and despite the fact that I got a script working, I need to figure out how to automate a [WHERE clause] per added question.
To describe it, every question gets posted and has an ID in the database. I want to delete on that ID, but per question I add the
DELETE FROM faq [WHERE faq_id=#]
My current code:
$sql = "SELECT question, answer FROM faq";
$queryresult = mysql_query($sql) or die (mysql_error());
while ($faqResult = mysql_fetch_array($queryresult)){
$faqQuestion = $faqResult['question'];
$faqAnswer = $faqResult['answer'];
echo "<p class='faqQuestionAdmin'>$faqQuestion</p>" .
"<p class='faqAnswerAdmin'>$faqAnswer</p>" .
"<a class=faqDelete>X</a>";
}
if(mysql_num_rows($queryresult) <= 0) {
echo("<div><p>No Questions available</p></div>");
}
mysql_free_result($queryresult);
mysql_close($conn);
that serves as the deleting button. I was thinking a get function, but does anyone know how can I do this? Currently the only columns in the database for each question is the ID, question, and answer.
Thanks in advance!
If you have in the database:
Id | Question
--------------------------
1 | This is a question
2 | This is question 2
And when you render your page and have a own delete page
<?php
//You have get the questions by a query and stored in the local $sqlResults
echo "<table>
<tr><th>Id</th><th>Question</th><th>Delete</th></tr>";
foreach($sqlResults as $result)
{
echo "<tr><td>" . $result["id"] . "</td><td>" . $result["question"] . "</td>";
echo "<td><a href='your-domain.com/delete.php?id=" . $result["id"] . "'>X</a></td></tr>";
}
echo "</table>";
?>
And when you have a javascript function which makes a AJAX post call, make the href like:
yourDeleteJavascriptFunction(" . $result["id"] . ")
In both cases you render a list, and per item you add the id of the question. You can get the value when you receive the id and delete only that question by his id ;-)
If you want to avoid AJAX, you could simply put a link in your anchor tag to php file with GET variable in it:
X
Than in deleteFAQ.php you use
$id = $_GET['id'];
$query = "DELETE FROM faq WHERE faq_id=$id";
best way you can use ajax call and call php file and pass id to that file and write delete query in that php file

Deleting forum posts

I have a table with the following fields: wall_posts, group_id, id, and user_id.
Wall_posts is user entries, group_id is imported from another table and is just a unique group id, id is just a simple counter, and user_id gets the user id from the session.
My code gets rid of all the wall_posts if you press the delete button by comparing the user id to the user in session. I'm trying to find a way to delete individual posts and not all the posts by the user.
Here is the code:
if (isset($_POST['delete'])) {
$current_user = $_SESSION['user_id'];
$result = mysql_query("SELECT * FROM group_posts");
while ($user_id = mysql_fetch_array($result)) {
$id = $user_id['user_id'];
}
if ($current_user == $id) {
mysql_query("DELETE FROM group_posts WHERE $current_user = $id") or die(mysql_error());
}
}
How can I bound the delete button to individual posts instead of deleting all the posts made by the user currently in session?
Your SQL query above doesn't make sense - the WHERE statement should be in the form WHERE column_name = value.
Assuming id is the primary key for group_posts, as you're displaying posts, create a link for each post created by the author, e.g. Delete This Post for post with id 3. Then you'd do a query like this:
DELETE FROM group_posts WHERE id = postIdValueHere
Using the code pattern you have above:
if (isset($_POST['delete']) && $_POST['delete'] > 0) {
$current_user = $_SESSION['user_id'];
$post_id = (int) $_POST['delete'];
if ($current_user == $id) {
mysql_query("DELETE FROM group_posts WHERE id = $post_id AND user_id = $id") or die(mysql_error());
}
That query ensures that only posts with a given ID, created by the current author, can be deleted.
Does that answer your question?
Once you get more comfortable with SQL, you might also want to look into using prepared statements with mysqli or PDO. That will help your code clean and secure.
I'm assuming your delete buttons are simple links. Your links must contain all the information to delete a post. One way would be to pass a post id as a GET variable (e.g. link="myurl.com/posts/delete?id=#").
Your script would then at first make sure the current user is allowed to delete the post. For example:
$user_id = $_SESSION['user_id'];
$post_id = (int) $_GET['id'];
if(canDelete($user_id, $post_id))
{
// assuming post_id is unique for every post
$sql = sprintf("DELETE FROM group_posts WHERE id = %d", $post_id);
mysql_query($sql);
}
Of course, you'd have to implement canDelete($user_id) yourself.
By the way, "DELETE FROM group_posts WHERE $current_user = $id" always deletes every record in your table. At first you're comparing if $current_user equals $id and if they do happen to be equal, your query would look something like WHERE 1 = 1. I think you mean "DELETE FROM group_posts WHERE user_id = '$id'"
EDIT: It seems you want to use ajax for deleting your posts. I recommend using jQuery or any other proper javascript framework as it saves you time. Here is a link from the jQuery documentation describing how to make an ajax call to the server and a similar question to help you understand better.

Categories