Not able to access variable value in PHP - php

This is my code to print Questions and then their respective Answers.
<?php
$reg = $_SESSION['reg'];
$sql1="select users.reg,questions.question,questions.id from users,questions where users.reg=questions.reg and questions.company='infosys' and questions.reg!='$reg' limit 0,5";
$query1=mysqli_query($conn,$sql1);
$sql2="select questions.id,answers.reg,answers.answer from questions,answers where questions.id=answers.id";
$query2=mysqli_query($conn,$sql2);
while($row1 = mysqli_fetch_assoc($query1)){
echo "<p class='fill'><bold>".$row1["reg"]."</bold> asked:-" ;
echo '<br>QID:-'.$row1['id'].'  "'.$row1["question"].'"<br></p>';
while($row2 = mysqli_fetch_assoc($query2)){
echo "<pre align='right'><bold>".$row2["reg"]."</bold> answered:-" ;
echo '<br>  "'.$row2["answer"].'"</pre>';
}
echo '<form method="post" style="display:none;">';
echo '<textarea rows="2" cols="80" name="ans" class="form-control" required></textarea>';
echo '<button class="w3-button w3-blue w3-padding-medium w3-medium w3-margin-top w3-right" type="submit" name="answer">submit</button></form>';
echo '<button class="w3-button w3-blue w3-padding-small w3-small w3-right w3-margin-top show_button2">Answer</button><br><br>';
}
?>
But I'm not able to get correct output and plus I cant get the answer from the text area and insert into table with correct question ID. My INSERT code is:
if(isset($_POST['answer'])){
$id = $_SESSION['id'];
$reg = $_SESSION['reg'];
$answer = $_POST['ans'];
$sql="insert into answers VALUES('$id','$reg','$answer')";
$query=mysqli_query($conn,$sql);
if($query==TRUE){
header("location: infosys.php");
}
}
Please tell me how can i access the $row variable from that scope this insert scope

I got the solution. I stored the $row1['id'] in $id and stored that in "Submit" button's value
$id=$row31['id'];
echo '<form method="post" style="display:none;">';
echo '<textarea rows="2" cols="80" name="ans" class="form-control" required></textarea>';
echo '<button type="submit" name="answer_BTN" value='.$id.'">submit</button></form>';
and then i accessed the value via $_POST['answer_BTN'].
if(isset($_POST['answer_BTN'])){
$id = $_POST['answer_BTN'];
$reg = $_SESSION['reg'];
$answer = $_POST['ans'];
$sql2="insert into answers VALUES('$id','$reg','$answer')";
$query2=mysqli_query($conn,$sql2);
if($query2==TRUE){
header("location: infosys.php");
echo "<script>alert('Added your Answer!')</script>";
}
}

are you checking for submit on the same PHP File or another one?
if its another file mention the location here:
echo '<form method="post" action="../location/to/yourfile.php" style="display:none;">';
else make sure you are checking isset() at the top of the page

Related

php: getting a variable (user selection from radio button) to another file

I have a list of items in one file (fruit.php):
<form action="delete_items.php" method="post">
<input type="radio" value="apple" name="fruit">Apple<br>
<input type="radio" value="pear" name="fruit">Pear<br>
<input type="radio" value="banana" name="fruit">Banana<br>
<input type="submit" value="delete" name="deleteButton"><br>
</form>
In the delete_items.php, I have a variable that stores the selection:
<?php
$selection = $_POST["fruit"];
echo "are you sure you want to delete it?";
echo '<form action="delete_confirmation.php" method="post"><br>';
echo '<input type="submit" name="deleteYes" value="Yes"><br>';
echo '<input type="submit" name="deleteNo" value="No"><br>';
echo '</form>';
?>
Than in the confirmation file (delete_confirmation.php):
<?php
include 'delete_items.php';
if($_POST["deleteYes"]){
$query = 'DELETE FROM databaseName WHERE fruitName="' . $selection . '"';
$result = mysqli_query($connection, $query);
if(!$result){
die("Delete after check query failed!");
} else {
echo "Delete after check query success!";
}
} elseif($_POST["deleteNo"]){
echo "The course was not deleted!";
}
?>
But the varibale $selection in the delete_confirmation.php file is always null even though i included the delete_items.php file (when i echo it, nothing is shown). Is there a way to pass the selection variable from delete_items.php to the delete_confirmation.php file?

How to associate query with changing variable in PHP

I'm in need of a bit help. I'm trying to find out how to associate a specific query (deletion of a record) with not the id of a record, but the record with which another query (selection of a record) is echoed out.
This line of code totally works when the id is specified, but again I need it for the record that gets called, where the id can skip numbers if I delete a record.
$querytwo = "DELETE FROM `paginas` WHERE id = 5";
I've got a table in my phpmyadmin database with columns 'id', 'pagetitle', 'toevoeging' (addition in Dutch) , 'message'. First one is an INT, rest are varchars/text.
This may be a stupid question, I'm sorry for that. I'm still new to PHP, and to programming in general.
Here is the code. I've commented on lines code to clarify. Thanks you!.
<?php
if (isset($_SESSION['email'])) //if the admin is active, forms can be written out.
{
echo '</nav>
<br><br> <div class="inlogscript">
<form action="verstuurd.php" method="post">
<input type="text" placeholder="Titel" method="POST" name="pagetitle" /><br><br>
<input type="text" placeholder="Toevoeging" method="POST" name="toevoeging" /><br><br>
<textarea class="pure-input-1-2" placeholder="Wat is er nieuws?" name="message"></textarea><br>
<input type="submit" value="Bevestigen" />
</form></div>';
}
?>
<div class="mainContent">
<?php
include_once("config.php"); //this is the database connection
$query = "SELECT * FROM paginas "; //selects from the table called paginas
$result = mysqli_query($mysqli, $query);
while($row = mysqli_fetch_assoc($result))
{
$pagetitle = $row['pagetitle'];
$toevoeging = $row['toevoeging'];
$message = $row['message'];
echo '<article class="topcontent">' . '<div class="mct">' . '<h2>' . "$pagetitle" .'</h2>' . '</div>' . "<br>" .
'<p class="post-info">'. "$toevoeging" . '</p>' . '<p class="post-text">' . '<br>'. "$message" . '</p>' .'</article>' . '<div class="deleteknop">' . '<form method="post">
<input name="delete" type="submit" value="Delete Now!">
</form>' . '</div>' ;
} //This long echo will call variables $pagetitle, $toevoeging and &message along with divs so they automatically CSS styled,
//along with a Delete button per echo that has the 3 variables
$querytwo = "DELETE FROM `paginas` WHERE id = 5";
if (isset($_POST['delete'])) //Deletes the query if 'delete' button is clicked
{
$resulttwo = $mysqli->query($querytwo);
}
?>
</div>
</div>
Also here is the Insert INTO query of the records. Thanks again!
$sql = "INSERT INTO paginas (pagetitle,toevoeging, message)
VALUES ('$_POST[pagetitle]','$_POST[toevoeging]','$_POST[message]')";
//the insertion into the table of the database
if ($MySQLi_CON->query($sql) === TRUE) {
echo "";
} else {
echo "Error: ". $sql . "" . $MySQLi_CON->error;
}
This won't be sufficient but, to begin with your echo :
echo '<article class="topcontent">
<div class="mct">
<h2>' . $pagetitle .'</h2>
</div><br>
<p class="post-info">'. $toevoeging . '</p>
<p class="post-text"><br>'.$message.'</p>
</article>
<div class="deleteknop">
<form method="post">';
// you ll want to use $_POST["id"] array to delete :
echo '<input type="hidden" name="id" value="'.$row['id'].'">
<input name="delete" type="submit" value="Delete Now!">
</form>
</div>' ;

Update and delete for specific record

I have written code to retrieve all the images from database for a specific city, and I want to be able to delete a specific image or to change the caption.
The problem is:
the code always work on the last image only!
I hope you guys will be able to help me with this problem.
Retrieve code:
<?php
$City_name=$_REQUEST['id'];
$Image_query = "SELECT * FROM image where City_name ='".$City_name."' ";
$Image_result = mysqli_query($dbcon,$Image_query);
echo "<table>";
while ($row = mysqli_fetch_array($Image_result))
{
$image_id = $row['Image_id'];
$image = $row['Image_url'];
$Caption = $row['Caption'];
echo "<tr style='float:right;'>";
echo "<td>"; ?> <img src="<?php echo $image ; ?>"/> <br>
<input type="text" name="caption" value="<?php echo $Caption ;?>" />
<br> <input name="delete" type="submit" value="Delete picture" />
<br> <input name="Update_caption" type="submit" value="change caption" />
<?php echo "</td>";
echo "<td>"; ?> <input class="input-image" type="hidden" name="id" value="<?php echo $image_id ;?>" />
<?php echo "</td>";
} /* End of while loop */
echo "</tr>";
echo"</table>";
?>
Update code :
if (isset($_POST['Update_caption'])) {
$ImageID = $_POST['id'];
$ImageCaption = $_POST['caption'];
$sql = mysqli_query ($dbcon,"UPDATE `image` SET `Caption`='".$ImageCaption."' WHERE `Image_id`='".$ImageID."' ");
if ($sql) {
echo "done";
} else { echo "error"; }
}
Delete code :
if (isset($_POST['delete'])) {
$ImageID = $_POST['id'];
$sql = mysqli_query ($dbcon,"DELETE FROM `image` where `Image_id` = '".$ImageID."' ");
if ($sql) {
echo "done";
} else { echo "error"; }
}
$_POST['id'] (sql injection alert!) contains the contents of the input element that has a name attribute id.
You are echoing out your input elements in a loop, all with the same name so the last one will overwrite all the previous ones.
You should use an array like for example:
<input class="input-image" type="hidden" name="id[<?php echo $image_id ;?>]" value="<?php echo $image_id ;?>" />
So that your $_POST['id'] is an array containing all elements.
The same applies to other input elements like the caption.
An alternative, especially for your delete option, would be to wrap every image in its own form. But keep in mind that you will need valid html for that to work, you can't have a form that opens in a row element and spans different columns.
And note that you should really use a prepared statement to close the sql injection hole you have now.

PHP error when updating MySQL row with PDO

I'm trying to make a way to edit my posts on a blog I'm making but for some reason when I try to submit the "update post" form it will give me the error "Something went wrong..." (meaning it got to update post.php) and I'm not sure why. The only thing I could see it being is because I'm using TinyMCE to edit the content of the post and the way I'm doing it is wrong?
editpost.php
<?php
include 'php/mysql_connect.php'; // opens a PDO of variable $db
if(isset($_GET['id'])){
$q = $db->prepare('SELECT * FROM posts WHERE id=:post_id LIMIT 1');
$q->execute(array(':post_id'=>$_GET['id']));
$row = $q->fetch(PDO::FETCH_ASSOC);
if($row){
echo '<form method="post" action="php/update_post.php?post_id='.$_GET['id'].'">';
echo '<div class="form-group">';
echo ' <input type="text" class="form-control" name="title" id="title" placeholder="Post Title" autocomplete="off" value="'.$row['title'].'" required />';
echo '</div>';
echo '<div class="form-group">';
echo ' <textarea class="form-control" name="body" id="body">'.$row['body'].'</textarea>';
echo '</div>';
echo '<input type="submit" value="Update Post" class="btn btn-default" />';
echo '</form>';
}
else{
echo 'Post not found.';
}
}
else{
echo 'Post not found.';
}
?>
update_post.php
<?php
$post_id = $_GET['post_id'];
$title = $_POST['title'];
$body = $_POST['body'];
include 'mysql_connect.php'; // establishes $db, a PDO connection
// insert the records
$sql = "UPDATE posts SET title=:title, body=:body WHERE id=:post_id)";
$q = $db->prepare($sql);
if($q->execute(array(':title'=>$title, ':body'=>$body, ':post_id'=>$post_id))){
echo '<script type="text/javascript">alert("Success!");location.href="../posts.php";</script>';
}
else{
echo '<script type="text/javascript">alert("Something went wrong...");location.href="../posts.php";</script>';
}
?>
I've changed the form method to GET, and it is passing the variables correctly, so that isn't the problem. The update_post.php is a modified version of my add_post.php, which works perfectly fine so I don't understand why updating it doesn't work right.
$sql = "UPDATE posts SET title=:title, body=:body WHERE id=:post_id)";
remove this one >-----^
you have a bracket at the end wrong ;)
Remove it and it should work:
$sql = "UPDATE posts SET title=:title, body=:body WHERE id=:post_id";
If you use GET use GET then ;-)
$post_id = $_GET['post_id'];
$title = $_GET['title'];
$body = $_GET['body'];
if you use POST use POST:
$post_id = $_POST['post_id'];
$title = $_POST['title'];
$body = $_POST['body'];
According to your last comment try change here:
if($row){
echo '<form method="post" action="php/update_post.php">';
echo '<input type="hidden" name="post_id" value="'.$_GET['id'].'">';
echo '<div class="form-group">';
echo ' <input type="text" class="form-control" name="title" id="title" placeholder="Post Title" autocomplete="off" value="'.$row['title'].'" required />';
echo '</div>';
echo '<div class="form-group">';
echo ' <textarea class="form-control" name="body" id="body">'.$row['body'].'</textarea>';
echo '</div>';
echo '<input type="submit" value="Update Post" class="btn btn-default" />';
echo '</form>';
}

If content exists in database, provide form to update it - else provide form to add new row

It's all going wrong. I need to output a form onto my website that will do 1 of 2 things:
If the user already has content in the database, provide a form that posts to self to update the existing content.
If the user does not have content in the database, provide a form to let the user add information to the database.
The forms should submit to themselves to keep coding tidy. I'm getting into a right mess. I'll show what I have so far, but I'm getting in a muddle.
//look in db to see if content exists, if it does set variable
$result = mysql_query(
"SELECT * from tbl_profiles
WHERE user_id = $who
");
while($row = mysql_fetch_array($result))
{
$profileText = $row['text'];
}
// Check if user has content in db
$result = mysql_query(
"SELECT * FROM tbl_profiles WHERE user_id='$who'");
if(mysql_fetch_array($result) !== false){
echo
'<form action="../edit/indexUpdate.php" method="post" name="edit">
Comments:<br />
<textarea name="updatedText" id="comments">' .
$profileText .'
</textarea><br />
<input type="submit" value="Submit" />
</form>'
;}
else{
$profileText = $row['text'];
echo
"<form action='../edit/index.php' method='post' name='add'>
Comments:<br />
<textarea name='comments' id='comments'>" .
$profileText
."</textarea><br />
<input type='submit' value='Submit' />
</form>"
;}?>
You've pretty much got the functionality there, just needs tidying up.
Try something like this:
<?php
//look in db to see if content exists, if it does set variable
$profileText="";
if($result = mysql_query("SELECT * from tbl_profiles WHERE user_id = $who")) {
while($row = mysql_fetch_array($result))
{
$profileText .= $row['text'];
}
?>
<form action="../edit/indexUpdate.php" method="post" name="edit">
Comments:<br />
<textarea name="updatedText" id="comments">
<?php echo $profileText; ?>
</textarea><br />
<input type="submit" value="Submit" />
</form>
<?php
} else {
?>
<form action='../edit/index.php' method='post' name='add'>
Comments:<br />
<textarea name='comments' id='comments'>
<?php echo $profileText; ?>
</textarea><br />
<input type='submit' value='Submit' />
</form>
<?php
}
?>
The basic idea is to add a record if new and update if not. What you can do is use an id to represent the record or -1 if it's a new entry
Something along the lines of:
//Defaults
$recordid=-1;
$name='';
$comments='';
//look in db to see if content exists, if it does set variable
$result = mysql_query(
"SELECT * from tbl_profiles
WHERE user_id = $who
");
// Check if user has content in db
$result = mysql_query(
"SELECT * FROM tbl_profiles WHERE user_id='$who'");
if(mysql_fetch_array($result) !== false){
//Yes. Get the id
$recordid = $result->id;
//Get the values
$name= $result->name;
$comments= $result->name;
}
<form action="../edit/index.php" method="post" name="formdata">
<input type="hidden" name="recordid" value="<? echo htmlspecialchars($recordid) ?>">
<input type="hidden" name="name" value="<? echo htmlspecialchars($name) ?>">
<textarea name="comments" id="comments"><? echo htmlspecialchars($comments) ?></textarea>
<input type="submit" value="submit"/>
</form>
This way a new form will have a -1 but an existing will have an id.
As an additional point it is very important to sanitize your inputs for SQL and what you output in HTML to stop SQL Injections. For your reference on this:
SQL
Little Bobby Tables
Cross Site Scripting

Categories