php cannot define variable - php

for some reason i cant find my error why i cant define my $id variable and paste it into my my_sqly query.
everything else is working fine.
Any help would be greatly appreciated.
This is my PHP "process" file (update.php)
if (isset($_POST['button1']))
{
$id = $_POST["id"];
mysql_query("DELETE FROM member WHERE id = '".$id."'") or die("cannot execute the query");
}
and my other file
while($row = mysql_fetch_assoc($results))
{
$id = $row["id"];
//echo '<form action="update.php" method="post">';
echo '<table border="1">';
echo '<tr>';
echo '<td> '.$row["username"].'</td>';
echo '<td> '.$row["password"].' </td>';
echo '<form method="POST" action="update.php">';
echo '<input type="hidden" name="return_url" value="'.$_SESSION["return_url"].'" />';
echo "<input type='hidden' name='hidden_id' value='$id' />";
echo '<input type="submit" name="button1" value="My Button">';
echo '</form>';
}

Change
$id = $_POST["id"];
to
$id = $_POST["hidden_id"];
That is the name of your input field and not only "id"

You are using hidden_id as name for the input where you store $id from previous request.
So to access it, you need to do
$id = $_POST["hidden_id"];
For future reference, take a look at How can I prevent SQL injection in PHP? as you are not sanitizing your user input.

Related

Any particular reason why this piece of code doesn't work? I can't seem the figure out the issue

The goal of this page is to check the tags table in my database and generate unordered list with the tag name and tag image of every row. The following code allows me to do that perfectly :
<?php
$sql = "SELECT * FROM tags";
echo "<ul id='ulTags'>";
$result = mysqli_query($conn, $sql);
while ($row = $result->fetch_assoc()){
echo '<div class="imageContainerTags"><li class="listTags"><h1>'.$row['tag'].'</h1></li><img class="tagThumbnail" src="images/Tags/'.$row['path'] .'" alt="Random image" /></div>';
}
echo "</ul>";
?>
However, I have decided to implement the possibility to delete a tag from the database if you have the permission. Every user has a permission and if you have a permission of 1, you should see a delete button under each image. This is the updated code featuring that functionality :
<?php
$userId = $_SESSION['id'];
$sql = "SELECT * FROM tags";
$result = mysqli_query($conn, $sql);
$sql2 = "SELECT * FROM user where id='$userId'";
$result2 = mysqli_query($conn, $sql2);
$getResult2 = mysqli_fetch_assoc($result2);
$userP = $getResult2['permission'];
echo "<ul id='ulTags'>";
if (isset($_SESSION['id']) && $userP == 1) {
while ($row = $result->fetch_assoc()){
echo '<div class="imageContainerTags"><li class="listTags"><h1>'.$row['tag'].'</h1></li><img class="tagThumbnail" src="images/Tags/'.$row['path'] .'" alt="Random image" /></div>';
echo "<form method='POST' action='".deleteTag($conn)."'>
<input type='hidden' name='id' value='".$row['id']."'>
<input type='hidden' name='tag' value='".$row['tag']."'>
<input type='hidden' name='path' value='".$row['path']."'>
<button id='delTag' type='submit' name='tagDelete'>Delete Tag</button>
</form>";
}
} else {
while ($row = $result->fetch_assoc()){
echo '<div class="imageContainerTags"><li class="listTags"><h1>'.$row['tag'].'</h1></li><img class="tagThumbnail" src="images/Tags/'.$row['path'] .'" alt="Random image" /></div>';
}
};
echo "</ul>";
?>
Unfortunately, there seems to be a problem with the code and it only echoes one tag and not all of them as it should do. The first piece of code echoed all the tags but that was before me trying to add a delete button. Any clues would be appreciated.
The best thing to do to debug is to insert echoes at each part of the code to see where its getting derailed.
First inspect the output html page source to see that the tags are properly echoed (no html error).
I would place echo $result->num_rows Just before the if else clause to see the total tags returned.
If there are multiple tags in the result and only one is displayed then I will see if that tag is the last or first tag in the returned result.
Check these to get started....
NB: Why don't you use consistent coding style?
//One place you use
$getResult2 = mysqli_fetch_assoc($result2); // functional programming
// another place you use
$row = $result->fetch_assoc(); // OOP programming
// Stick to one style, preferably OOP
Try replacing the if statement in your code with this.
if (isset($_SESSION['id']) && $userP == 1) {
while ($row2 = $result->fetch_assoc()){
echo '<div class="imageContainerTags"><li class="listTags"><h1>'.$row2['tag'].'</h1></li><img class="tagThumbnail" src="images/Tags/'.$row2['path'] .'" alt="Random image" /></div>';
echo "<form method='POST' action='".deleteTag($conn)."'>
<input type='hidden' name='id' value='".$row2['id']."'>
<input type='hidden' name='tag' value='".$row2['tag']."'>
<input type='hidden' name='path' value='".$row2['path']."'>
<button id='delTag' type='submit' name='tagDelete'>Delete Tag</button>
</form>";
}
} else {
while ($row2 = $result->fetch_assoc()){
echo '<div class="imageContainerTags"><li class="listTags"><h1>'.$row2['tag'].'</h1></li><img class="tagThumbnail" src="images/Tags/'.$row2['path'] .'" alt="Random image" /></div>';
}
};
PHP is server side programming language, HTML forms are client side.
here deleteTag() is a PHP function, it has no effect at the time when the form is submitted at the client.
echo "<form method='POST' action='delete.php'>
where delete.php have the logic necessary to handle deletion

Display Contents of Textbox That was created by PHP

I would like some help printing what is in a certain textbox that was created by an echo command.
while($row = $result->fetch_assoc()){
$stringTest = $row['Price'];
$AssetId = $row['AssetId'];
echo "<center><div> <h3>Cost: ".$stringTest."";
echo '<form action="" method="get"><input type="text" name="uid">';
echo "</br><input class='myButton' type='submit' Name='Submit1' VALUE='I have bought'></a></form>";
/** ^ Input value I would like to get *//
echo "<a href='https://www.roblox.com/item-item?id=".$AssetId."' class='myButton'>Buy</a></h3></div></center>";
}
Use the code below to get the value from submit:
if(isset($_GET['Submit1'])) {
echo $_GET['Submit1'];
}
When the user clicks submit, it will echo the value of it.
If you want to print PHP element in a textbox you should put it in the value tag of the input
<?php
echo "<input type='text' value='" . $val . "'>";
?>

PHP variables inside HTML Code

I am making a student sign-up form using html and php.
First you are asked to insert your name, password and email and when you click submit, it takes you to another page (ChooseDepartment.php) in which you get a list of all departments from my database to choose your own.
Now, I am a total newbie, so here is the part of my php code that I am stuck with in ChooseDepartment.php:
$ShowPossibleDep = mysql_query("SELECT NAME,DEPT_ID FROM DEPARTMENT");
if(mysql_num_rows($ShowPossibleDep) > 0){
echo "<br />"."Available departments: "." ".mysql_num_rows($ShowPossibleDep)."<br />";
echo "<br />";
echo '<form id = "dept" action = "Courses.php" method = "post">';
while($row = mysql_fetch_array($ShowPossibleDep))
{
echo $row['NAME'];
echo '<input type="radio" name="department" value=<?php $row['DEPT_ID'] ?>>';
echo "<br />";
}
echo '<input type = "submit" value = "Submit" id = "submitDepartment">';
echo </form>;
}
I am trying to make the value of the radio button carry the value of the
the department id so I can then update my database with the student's department which is currently NULL, but I can't figure out how to use both html and php at the very same line correctly! This gives me syntax error!
as you're in PHP, so you don't need to open and close PHP tag.
The reason you're getting Syntax error is just because you're not manipulating string properly.
error is with this line
echo '<input type="radio" name="department" value=<?php $row['DEPT_ID'] ?>>';
^ here ^ here
So you need to remove the PHP tags and need to concatenate string properly like:
echo '<input type="radio" name="department" value="'.$row['DEPT_ID']. '">';
and with this one
echo </form>;
you're missing quotes around form tag. So it should be,
echo '</form>';
There are some other typos are as well, so your final code will be look like this.
$ShowPossibleDep = mysql_query("SELECT NAME,DEPT_ID FROM DEPARTMENT");
if(mysql_num_rows($ShowPossibleDep) > 0){
echo "<br />Available departments: ".mysql_num_rows($ShowPossibleDep);
//echo "<br />"; add this <br /> tag to next echo
echo '<br /><form id = "dept" action = "Courses.php" method = "post">';
while($row = mysql_fetch_array($ShowPossibleDep))
{
echo $row['NAME'];
echo '<input type="radio" name="department" value=" '.$row['DEPT_ID'].'"><br />';
//or you can do this way
//echo "<input type='radio' name='department' value='$row[DEPT_ID]'><br />";
//echo "<br />"; appended in upper statement.
}
echo '<input type = "submit" value = "Submit" id = "submitDepartment"></form>';
//echo </form>; closed already(above statement).
}
and without comments, more cleaner :)
$ShowPossibleDep = mysql_query("SELECT NAME,DEPT_ID FROM DEPARTMENT");
if(mysql_num_rows($ShowPossibleDep) > 0){
echo "<br />Available departments: ".mysql_num_rows($ShowPossibleDep);
echo '<br /><form id = "dept" action = "Courses.php" method = "post">';
while($row = mysql_fetch_array($ShowPossibleDep))
{
echo $row['NAME'];
echo '<input type="radio" name="department" value=" '.$row['DEPT_ID'].'"><br />';
}
echo '<input type = "submit" value = "Submit" id = "submitDepartment"></form>';
}
Take a look at string operators
http://php.net/manual/en/language.operators.string.php
You can combine two strings in php with a dot, so that part of your code would become this:
{
echo $row['NAME'];
echo '<input type="radio" name="department" value="'.$row['DEPT_ID'].'">';
echo "<br />";
}
No need to open php tag again
$ShowPossibleDep = mysql_query("SELECT NAME,DEPT_ID FROM DEPARTMENT");
if(mysql_num_rows($ShowPossibleDep) > 0) {
echo "<br />"."Available departments: "." ".mysql_num_rows($ShowPossibleDep)."<br />";
echo "<br />";
echo '<form id = "dept" action = "Courses.php" method = "post">';
while ($row = mysql_fetch_array($ShowPossibleDep)) {
echo $row['NAME'];
echo '<input type="radio" name="department" value="' . $row['DEPT_ID'] .'">';
echo "<br />";
}
echo '<input type = "submit" value = "Submit" id = "submitDepartment">';
echo "</form>";
}

Use Delete Button to Delete Record from Database

I have a database containing books. On a page, I have loop that prints each record in the database which each book's title, author, publisher, date, and rating. I want to use a delete button at the bottom of each record in order to delete it.
When I click on the delete button, the page is updated, but the record is not deleted.
I have tried to find solutions to this problem, but have yet to. I tried to use the book_id category in my database table as my index, in order to identify each record and delete it but it does not work.
Here is the code for my button form, as it appears with html code:
while ($row = mysqli_fetch_array($result))
{
echo '<div id="forminput">';
$timestamp = strtotime($row['date']);
echo '<div id = "bookpicture">';
echo '<img src="images/Book Cover 8crop.jpg" alt="Book Cover">';
echo '</div>';
echo '<div id = "bookinfo">';
echo '<div id = "titleauthor">';
echo '<h3>' . htmlspecialchars($row['title'], ENT_QUOTES, 'UTF-8') . '</h3>';
echo '<p>' . htmlspecialchars($row['author'], ENT_QUOTES, 'UTF-8') . '</p>';
echo '</div>';
echo '</div>';
$id = htmlspecialchars($row['book_id'], ENT_QUOTES, 'UTF-8');
echo '</div>' ;
echo '<div id = "publisher">' ;
echo '<p>' . 'Published on' . " " . htmlspecialchars(date('F j, Y,', $timestamp),
ENT_QUOTES, 'UTF-8') .
" " . 'by' . " " . htmlspecialchars($row['publisher'], ENT_QUOTES, 'UTF-8') . '</p>';
echo '</div>';
echo '<div id = "formDelete">';
echo '<form name="deleteForm" method="post" id="deleteForm" action="index.php">';
echo '<input type="submit" value="Update" name="myAdd" id="myAdd" style = "width:
100px" required>';
echo '<input type="submit" value="Delete" name="myDelete" id="$id" style = "width:
100px" required>';
echo '</form>';
echo '</div>';
echo '</div>';
echo '<hr>' ;
echo '</div>';
}
?>
Here is the code from my index.php file.
else if (isset($_POST['myDelete']))
{
$ids = mysqli_real_escape_string($link, $_POST['$id']);
$sql="DELETE FROM readbooks WHERE book_id = '$ids'";
if (!mysqli_query($link, $sql))
{
$error = 'Error with submission: ' . mysqli_error($link);
include 'php/error.html.php';
exit();
}
}
Here is the updated code.
The Problem is you are not trying to send the row ID from the form.
In Form try sending row id from the form
echo '<input type="hidden" name="id" value="$id">'
try receiving that parameter
$id = $_POST['id'];
$con = mysql_connect("host address","mysql_user","mysql_pwd");
$query = "DELETE FROM readbooks WHERE id = $id";
mysql_query($query,$con);
Moving from comment, you're not actually getting the $id anywhere. Add a field to your form:
<input type='hidden' name='id' value='$id'>
and then refer to it in your php:
$ids = mysqli_real_escape_string($link, $_POST['id']);
Since your using mysqli now, use prepared statements. Do not directly use your user input to the query! Example:
$books = array();
// connection
$con = new mysqli('localhost', 'your_username', 'password_of_username', 'your_database');
if(isset($_POST['myDelete'])) {
$book_id = $_POST['myDelete']; // get the variable id
$stmt = $con->prepare('DELETE FROM readbooks WHERE book_id = ?');
$stmt->bind_param('i', $book_id);
$stmt->execute();
}
$result = mysqli_query($con, 'SELECT * FROM readbooks');
while($row = $result->fetch_assoc()) {
$books[] = $row;
}
?>
<form method="POST">
<table border="1" cellpadding="10">
<tr>
<th>Title</th>
<th>Author</th>
<th>Publisher</th>
<th></th>
</tr>
<?php foreach($books as $book): ?>
<tr>
<td><?php echo $book['title']; ?></td>
<td><?php echo $book['author']; ?></td>
<td><?php echo $book['publisher']; ?></td>
<td><button type="submit" name="myDelete" value="<?php echo $book['book_id']; ?>">Delete</button></td>
</tr>
<?php endforeach; ?>
</table>
</form>
I think you're having problem with the id that you are passing to your PHP code. Try to use var_dump($_POST) to see what is the content of your $_POST variable. As I can see, the index of $_POST is wrong.
<input type="submit" value="Delete" name="myDelete" id="$id" style = "width:100px" required>';
Try to change this to
<input type="submit" name="book_id" value="$id" style = "width:100px" required>';
In your php use this $_POST["book_id"] to get the value of book_id you posted.
Note : The attribute "name" of the input tags will be the index of your $_POST variable
I understand that you want to have a delete and update button at the same time. The problem is your logic behind the situation. You need to have a hidden field and put the id inside it. Try to use this.
echo '<form name="deleteForm" method="post" id="deleteForm" action="index.php">';
echo '<input type="hidden" value="$id" name="book_id" id="myAdd" required>';
echo '<input type="submit" value="Update" name="action" id="myAdd" required>';
echo '<input type="submit" value="Delete" name="action" id="$id" required>';
echo '</form>';
In your php code use try to have a condition like this :
$book_id = $_POST["book_id"];
if($_POST["action"] == "delete")
{
//do your deletion code here. use the variable $book_id
}
else{
//do your update code here.use the variable $book_id
}

I need to upload an image with PHP and insert file names in database

I have a PHP form that updates records in a database. It looks something like this.
//update a record
$query1 = 'UPDATE mytable SET name="'.$name.'", description="'.$desc.'",
img="'.$img.'" WHERE id="'.$id.'" ';
mysqli_query($con,$query);
//get record set
$query2 = 'SELECT * FROM mytable WHERE id="'$id'"';
$result = mysqli_query($con,$query2);
echo '<form action="my-update-page.php" method="post">';
//table heading row
echo '<table width="1000" border="1" cellspacing="0" cellpadding="1">';
echo '<tr>';
echo '<td>ID</td>';
echo '<td>NAME</td>';
echo '<td>description</td>';
echo '<td>Image</td>';
echo '</tr>';
//display data
while($row = mysqli_fetch_array($result))
{
echo '<input type="hidden" name="id" value="' . $row['id'] . '" />';
echo '<tr>';
echo '<td>'. $row['id'] . '</td>';
echo '<td><input type="text" name="name" value="'. $row['name'].'" /></td>';
echo '<td><textarea name="description">'.$row['description'].'</textarea></td>';
echo '<td><input type="text" size="3" name="img" value="'. $row['img'].'"/>;
echo 'Upload Image</td>';
echo '</tr>';
}
//closing tag for table
echo '</table>';
echo '<br /><input type="submit" value="submit" /></form>';
I want my upload.php page to open in a popup where the user can upload the image. I'm pretty sure I can manage doing that. Where I get stuck is after the file is uploaded, I want the popup to close and file name to show in the form input.
Modify to reflect your names, but window.opener is the link to the other window. At that point, access any elements the same way.
window.opener.forms['myform'].elements['fileinput'].value = nameOfFile;
window.close();
As the comment above says, use AJAX to do the file post.

Categories