The query works fine. I get a table with the associated data in rows. As you see I'd like a button with each row that calls a function that affects that specific row with which it is echoed. I have it working with a normal form, that is, If I put the value of Part_Number in manually the function will run successfully, but the issue is to have it more dynamic. I provided the applicable code.
In short: When I push the button that is echoed with the Part_Number it should update (add one) to the Quantity of that Part_Number.
The SQL doesn't throw an error but it also doesn't work. Everything except passing the variables dynamically works.
$sql = "SELECT id, Part_Number, Description, Location, Quantity, Certificate
FROM Inventory WHERE Part_Number LIKE'%$q%'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
echo "
<form method='POST' action='plusone.php'><tbody>
<tr>
<th><h2>".$row["Part_Number"]."</h2></th>
<td><h2>".$row["Description"]."</h2> </td>
<td><h2>".$row["Location"]."</h2> </td>
<td>
<input type='submit' class='btn btn-success' value='Plus 1'>
<input type='hidden' class='form-control' name='Part_Number_Entry'
id='$Part_Number_Entry' value=''>
</tr>
</tbody>
</form>";
if (isset($Part_Number1)) {
// the single quotes around the last variable are very important. If left out
the update wont work
$sql = "UPDATE TestTable SET Quantity= Quantity + 1 WHERE Part_Number=
'$Part_Number1'";
}elseif (!isset($PartNumber)) {
echo "PartNumber is not set";
# code...
}
if (mysqli_query($conn, $sql)) {
echo "Added One to current Record successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
echo $Quantity;
echo " ";
}
mysqli_close($conn);
?>
there are quite a few issues but this is the least code i could come up wit that will hopefully get you at least going in the right direction:
<input type='hidden' class='form-control' name='Part_Number_Entry' id='$Part_Number_Entry' value=''>
should be
<input type='hidden' class='form-control' name='Part_Number_Entry' value='$row["Part_Number_Entry"]' >
its the 'name' that becomes the array key and the value is from your db row
if (isset($Part_Number1)) {
should be
if (isset($_POST['Part_Number_Entry')) {
your posting the form, and the value you want is in that array.
To get $Part_Number1 for the query
$Part_Number1=(int)$_POST['Part_Number_Entry');
cast as int by you need to much safer db queries in the future.
This is not a great answer and i hope some posts something better.
Related
I have the following button echo'd:
<input type='submit' name='delete_$id' value='x' title='Delete message' />
$id is gathered from here:
$get_messages = mysqli_query ($connect, "SELECT * FROM private_messages WHERE message_to = '$username' OR message_from='$username' AND
DELETED ='no' ORDER BY id DESC");
while ($get_msg = mysqli_fetch_assoc($get_messages)){
$id = $get_msg['id'];
}
I want to get the id of the message the x is assigned to and then execute this:
if (#$_POST['delete_' . $id . '']){
echo "Deleted";
}
But the echo is not displaying on my page, meaning the code is faulty. I have checked numerous times, and cannot figure out why it isn't working?
Edit:
I am simply trying to add a delete button which on click will SET the deleted column in my table to yes.
Here is the complete code where the delete button is found:
<?php
echo "
<div class='parent'>
<div class='msg_prof'>
<img class='img-rounded' src='/user_data/profile_pics/$my_pro_pic'/>
</div>
<div class='new_msg_from_user'>
<p><b style= 'color: red;'> You said:</b> $msg_body</p>
<span class='faded'>$date </span>
<input type='submit' name='delete_$id' value='x' title='Delete message' />
</div><hr/>
</div>";
?>
My thinking behind this is that, I can get the id of a post using the $id variable, and assign that to the name. Then by using if (#$_POST['delete_' . $id . '']) I can perform the query based on the $id - for now I am trying to echo a message, just for testing purposes. This is all the code I have for this functionality.
you forgot the php tag.
<input type='submit' name='delete_<?php echo $id ?>' value='x' title='Delete message' />
First of all, look what you are displaying the line:
<input type='submit' name='delete_$id' value='x' title='Delete message' />
e.g. name should/must be displayed as name='delete_1' or name='delete_9' or any other string having a number/digit at the end of its name. Generically said: name='delete_anyNumber'
For that you should have the Fetched Records of messages(those which you want to displayed and have a cross button just for a good presentation of NORMS) in PHP File and iterate through each result and in iteration-loop, echo all the messages with X buttons like:
echo "<input type='submit' name='delete_" . $ResultVariableHoldingRows['id'] . "' value='x' title='Delete message' />";
THE REASON BEING: (You'll have to display it correctly so that when you POST the form, you must be able to get the exact POSTED value that needs to be DELETED, so that you don't have to iterate to check which row needs to be DELETED.)
After you get the above problem resolved, follow below instructions:
Access the value, in PHP file that is called after Submitting:
$_POST['\'delete_' . $id . '\'']
SUGGESTION: Use AJAX-Calls to DELETE the respective messages as the many forms on a single page will not be a good an approach and do some good search on AJAX before posting a question
As in the comment mentioned you have to iterate through the global POST array.
<?php
function getRecordIdFromKey($sKey)
{
$sId = str_replace("delete_", "", $sKey);
$iReturn = -1;
if (strlen($sId) > 0 && is_numeric($sId))
{
$iReturn = (int) $sId;
}
return $iReturn;
}
foreach ($_POST as $sKey => $mValue)
{
$iId = getRecordIdFromKey($sKey);
if ($iId >= 0)
{
// fire up your delete query
}
}
First of all this is my first question on here, and altohugh I have searched the site none of the answers I've seen resolve my current problem.
I am a PHP novice and am currently working on an end project for a course. The object is to make a rudimentary blog where users can post, delete and edit their news, admins can edit or delete everything etc. I am mostly doing fine, but am having a bit of trouble with the editing feature.
The following code displays all blog posts, their authors and dates of posting. If the currently logged in person is the author of a post or a admin, they have the option of deleting or editing each individual post. A small form appears that contains the title and post text. When the user types something else in clicking on the edit button should change the values in the database to the new values the user specified. The problem is that whenever i click on the edit button in the current setup, nothing happens. If i move the if statement outside of the other if statement, the posts do update, but become blank in the database.
Running print_r($_POST) after the fact shows that the array it builds has correct names and updated values, but still they aren't updated in the database. Here is the code, the pertinent part starts at the last if statement( I know, it isn't injection proof, will get to that as soon as it works):
$query = "SELECT id, title, body, pub_date, user_id FROM posts ORDER BY id desc";
$query_fetch = mysql_query($query);
while ($blog_post = mysql_fetch_assoc($query_fetch)) {
$author_id = $blog_post["user_id"];
$post_id = $blog_post["id"];
$post_id2 = $blog_post["id"] . 2;
$title = $blog_post['title'];
$body = $blog_post['body'];
$query = "SELECT username FROM users WHERE id = '$author_id'";
$query_run = mysql_query($query);
$author = mysql_fetch_assoc($query_run);
echo "<h2>" . censor($blog_post["title"]) . "</h2>" . "<br> <p> Autor: " . $author["username"] . "</p><br><p>Objavljeno: " . $blog_post["pub_date"];
if ($_SESSION['admin'] == 1 or $_SESSION['username'] == $author["username"]) {
echo "<form action='' method='POST'><input type='submit' name= '$post_id' value= 'Obriši objavu'></form>";
echo "<form action='' method='POST'><input type='submit' name= '$post_id2' value= 'Uredi objavu'></form>";
}
echo "<p>" . censor($blog_post["body"]) . "</p>";
if (isset($_POST["$post_id"])) {
$del_post = "DELETE FROM posts WHERE id = '$post_id'";
mysql_query($del_post);
}
if (isset($_POST["$post_id2"])) {
echo "<form action='' method= 'POST'>New title<input type='text' value = '$title' name='title'>New text<textarea name='body' id='' cols='30' rows='10'>$body</textarea><input type='submit' name='edit' value='edit'></form>";
if (isset($_POST['edit'])) {
$edit_title = $_POST['title'];
$edit_body = $_POST['body'];
$query = "UPDATE posts SET title= '$edit_title', body= '$edit_body' WHERE id= '$post_id'";
mysql_query($query);
}
}
}
Any help would be appreciated.
This last piece of code
if (isset($_POST["$post_id2"])) {
echo "<form action='' method= 'POST'>New title<input type='text' value = '$title' name='title'>New text<textarea name='body' id='' cols='30' rows='10'>$body</textarea><input type='submit' name='edit' value='edit'></form>";
if (isset($_POST['edit'])) {
$edit_title = $_POST['title'];
$edit_body = $_POST['body'];
$query = "UPDATE posts SET title= '$edit_title', body= '$edit_body' WHERE id= '$post_id'";
mysql_query($query);
}
}
gets activated when post_id2 is sent, but generates a form where post_id2 is not contained anymore. So when you submit that form, the IF is not entered.
You can modify it like this:
if (isset($_POST["$post_id2"])) {
echo "<form action='' method= 'POST'>New title<input type='text' value = '$title' name='title'>New text<textarea name='body' id='' cols='30' rows='10'>$body</textarea><input type='submit' name='edit' value='edit'></form>";
}
if (isset($_POST['edit'])) {
$edit_title = $_POST['title'];
$edit_body = $_POST['body'];
$query = "UPDATE posts SET title= '$edit_title', body= '$edit_body' WHERE id= '$post_id'";
mysql_query($query);
}
In general I think you would find it easier to use forms differently, specifically by using some sort of action tag:
input type="hidden" name="command" value="edit"
input type="hidden" name="post" value="{$post_id}"
This way you could run one single query immediately, without the need for browsing all the posts in a cycle.
One other useful possibility is to split your code between different PHP files, and keeping common code in one include:
<?php // this is delete.php
include "common.php";
$post_id = my_get_var('post_id');
my_sql_command("DELETE FROM posts WHERE...");
used from
<form action="delete.php" method="post" ...>
As you can see this allows for different ways of retrieving post_id (centrally defined in a single function my_get_var in common.php) and the central definition of SQL functions. How this function interfaces to MySQL can then be updated, specifically passing from mysql_ functions (which are deprecated, and soon will no longer be available) to e.g. PDO.
It also allows you to test a single command independently, by directly entering delete.php in the browser (you need for my_get_var to accept both POST and GET variables to do this).
Details
You want to inspect and/or modify a collection of posts. You then require initially at least the following operations: list, edit, and delete.
Only the first works against all posts.
So you could have a list.php file running the SELECT. Also, it is only in this SELECT that you need information about the user, so your query could become:
$query = "SELECT posts.id, title, body, pub_date, user_id, username FROM posts JOIN users ON (posts.user_id = users.id) ORDER BY posts.id desc";
In the display cycle we would display this information:
$query_fetch = mysql_query($query);
// This file will receive requests to edit or delete
// We can use a single form.
echo '<form action="manage.php">';
while ($post = mysql_fetch_assoc($query_fetch)) {
echo "<h2>" . censor($post["title"]) . "</h2>" . "<br> <p> Autor: " . $post["username"] . "</p><br><p>Objavljeno: " . $post["pub_date"];
if ((1 == $_SESSION['admin']) or ($_SESSION['username'] == $post["username"]) {
echo "<input type=\"submit\" name=\"Obriši objavu\" value=\"{$post['id']}\" />";
echo "<input type=\"submit\" name=\"Uredi objavu\" value=\"{$post['id']}\" />";
}
echo "<p>" . censor($blog_post["body"]) . "</p>";
}
echo "</form>";
This way you need only one form, and it will submit one field with a name describing the action to be taken, and the post on which to do it.
The file manage.php will then receive this information -- and can also be used to update it:
foreach(array(
"delete" => "Obriši objavu", // from list.php
"edit" => "Uredi objavu", // " "
"update" => "update" // from this file itself (see below)
)
as $test_todo => $var) {
if (array_key_exists($var, $_POST)) {
$id = $_POST[$var];
$todo = $test_todo;
}
}
if (isset($id)) {
switch($todo) {
case "delete":
mysql_query("DELETE FROM posts WHERE id = '{$id}'");
break;
case "edit":
// Get this post.
$query = "SELECT posts.id, title, body, pub_date, user_id, username FROM posts JOIN users ON (posts.user_id = users.id) WHERE posts.id = '{$id}';";
echo '<form action="manage.php" method= "POST">';
// This is how we tell this file what to do, and to what.
echo "<input type=\"hidden\" name=\"update\" value=\"{$id}\">";
// run query, fetch the one record, display info...
echo "</form>";
break;
case "update":
// Build the update query from $_POST.
mysql_query("UPDATE posts SET ...");
}
At first check that your query is correct. Then try to hard-code your query. Also test your query in phpMyAdmin Also you can try to remove the '' from your number variables on every query.
Please, can you give us your error?
There is a possibility also that your database has already been updated. So double check it.
This is how I usually debug. echo the query. Run it in PHPmyadmin, and see the error.
so, in your case.
echo "UPDATE posts SET title= '$edit_title', body= '$edit_body' WHERE id= '$post_id'";
echo that and you will have the query that the script will be trying to run.
Try running it in phpmyadmin and check what the error is.
I have problem in storing checkbox values in mysql db . How can I fix this code to store all checked values?
There are seven different columns in type must be stored in the database when you checked for rows
This part of the code is responsible for fetching data from the database and put it in a table:
while ($row = mysqli_fetch_array($query)) {
print
"<tr> <td><input type='checkbox' name='check[]' value='
".$row['course_id'].",
".$row['course_name'].",
".$row['day'].",
".$row['place'].",
".$row['hour'].",
".$row['type'].",
".$row['instructor_name']."' /></td>
<td>{$row['course_id']}</td>
<td>{$row['course_name']}</td>
<td>{$row['day']}</td>
<td>{$row['place']}</td>
<td>{$row['hour']}</td>
<td>{$row['type']}</td>
<td>{$row['instructor_name']}</td>
</tr>";
}
print "</table>
<input type='submit' name='Submit' value='Submit'>
</form>";
This part of the code responsible for storing the data in databases
if(isset($_POST['check'])){
$returned = $_POST['check'];
$office = array('course_id','course_name','day','place','hour','type','instructor_name');
$values = array();
foreach($office as $selection){
$insert1 ="INSERT INTO initial_registration
(course_id,course_name,day,place,hour,type,instructor_name)
SELECT *
FROM offerd_course";
mysqli_query($insert1) or die(mysqli_error());
}
}
I think your whole setup is not good, here is some code to get you started:
first print all courses
while ($row = mysqli_fetch_array($query)) {
print
"<tr>
<td><input type='checkbox' name='row_checked_".$row['course_id']."' value='1' /></td>
<td>{$row['course_id']}</td>
<td>{$row['course_name']}</td>
<td>{$row['day']}</td>
<td>{$row['place']}</td>
<td>{$row['hour']}</td>
<td>{$row['type']}</td>
<td>{$row['instructor_name']}</td>
</tr>";
}
And then for the inserting part:
again go through all courses to see which courses have been 'checked'
while ($row = mysqli_fetch_array($query)) {
if(isset($_POST['row_checked_'.$row['course_id']]) && $_POST['row_checked_'.$row['course_id']]==1){
//insert query here
}
}
Your insert query is also messed up a bit, Why do you want to insert the whole course into initial registration? You'll rather want to do something like this:
$insert1 ="INSERT INTO initial_registration (course_id,STUDENT) VALUES ($row['course_id'],$some_student_id_value)";
The page is set to show all rows where isthisapproved equals no. This is working how I want by updating isthisapproved to yes. However, after updating isthisapproved from no to yes I don't want it to show anymore... but it is. I'm guessing I have some code in the wrong spot so it isn't "refreshing" the isthisapproved=no query.
<form method='post'>";
$query="SELECT * FROM table WHERE isthisapproved='no'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
echo "<p>$count need approval</p>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$id=$row['id'];
echo "
<table>
<tr>
<td>ID:</td>
<td>$id <input type='hidden' name='id[]' value='$id'></td>
</tr>
<tr>
<td>
<center><input name='submit' type='submit' value='Change To Yes'></form></center>
</td>
</tr>
</table><br>
";}
if($_POST['submit']) {
$update = "UPDATE table SET isthisapproved='yes' WHERE id='$id' LIMIT 1";
if(mysql_query($update)) $count++;
else die("Error in query:<br>$sql<br>");
echo "<p><b>$name approval changed to yes</b></p>";
}
?>
I'd also like to put the notice that the approval worked to be at the top of the page after an update is made instead of at the bottom. I'm not sure how to go about that.
The select query and the update query are using different column names.
$query="SELECT * FROM table WHERE approved='no'";
^^^^^^^^
$update = "UPDATE table SET isthisapproved='yes' WHERE id='$id' LIMIT 1";
^^^^^^^^^^^^^^
Your code is very vulnerable to SQL injection consider using PDO..
Your id is an array so upon submit all of the ids will be sent to your script as it is all contained in one form.
You could wrap it in individual forms and there would also be no need for id to be an array... OR you could place a check box for each user and have the name as id[] then upon submit. you can do this...
foreach($_POST['id'] as $v){
//query goes here. $v is the ID
}
This could however be more efficient and generate a string to be sent as one query to update all users in one go.
First of all you are using "approved" column for select query and "isthisapproved" for update query. So anyway I am assuming it as a typo error. (If not then fix it).
Now pointing out some issue :
Correct your form starting tag and closing tag. Even though it is closing properly. So here form closing tag should be after finishing the table.
After submitting the form you are not receiving the id through $_POST. You are using direct $id which is wrong.
So here you should recieve the id like this and then pass it to update query :
$id = $_POST['id'];
So as said in title I'm trying to use the query variable given from the page which directs to this one and the form data from THIS page to manipulate the database. I can't seem to get it right and I have no idea what I'm doing wrong. The code snippet looks like this:
<?php
$ware_number = $_GET['id'];
Echo "<form action='usernamecheck.php' method='post'>";
Echo 'Username:<br>';
Echo '<input type="text" name="usernamecheck" size="14"><br>';
Echo 'Password:<br>';
Echo '<input type="password" name="passwordcheck" size="14"><br>';
Echo '<input type="submit" value="Send">';
Echo '</form>';
if (isset($_POST['usernamecheck'])) {
$sql2 = "SELECT * FROM `storedata`.`users` WHERE `username` LIKE '$_POST[usernamecheck]'";
$found_user_id = mysql_query($sql2, $conn);
print $found_user_id;
}
if (isset($_POST['usernamecheck'])) {
$sql3 = "INSERT INTO `storedata`.`basket` (user_id, ware_id, number, complete)
VALUES
('$found_user_id', '$ware_number', 1, 0)";
$derp = mysql_query($sql3, $conn);
print $derp;
}
?>
The document itself is usernamecheck.php, and I was just printing to try and locate the error. When i check the basket table nothing has happened, even though no error is displayed. Right now the variable $ware_number is causing errors. What am I doing wrong?
I have also made user_id and ware_id foreign keys in the storedata.basket table, since they are primary keys in their own respective table. This means they can only be specific values, but I'm testing with these values, primarily 1's and 0's...
What if $_GET['id'] is not set? it will fail. Also please read up into correct usage of SQL in PHP. Your code is vulnerable to SQL injection attacks and whatnot.
EDIT:
updated piece of code
if(isset$_GET['id'] && is_numeric($_GET['id']))
{
$ware_number = $_GET['id'];
Echo "<form action='usernamecheck.php?id=" . $_GET['id'] . "' method='post'>";
.....