Get ID from PHP URL and use in a query - php

I've put certain values like a user id into the url e.g /index.php?id=1 in previous PHP files.
I have a HTML form that has an action like this:
<form name="staffResponse" method="post" action="respond_ticket.php?id=<?php echo $_GET['id']; ?>">
Which when you go to respond_ticket.php and simply echo the value for the id and look at the URL it does it successfully. Whats more the data that I am posting to that file is also done without problem. However I want to then write that information to a table but it does not seem to work.
Here is the respond_ticket.php file
<?php
include 'database/db.php';
$id = $_GET['id'];
$staffResponse = $_POST['staffResponse'];
$sql = "INSERT INTO tickets (staffResponse) VALUES ('$staffResponse') WHERE id='$id'";
$result = mysqli_query($connection, $sql);
if ($result === TRUE) {
echo '<p>Response ' . $staffResponse . ', has been added</p>';
}
else {
echo '<p class="warning">Unable to respond</p>';
}
?>
The db.php file has all the necessary information for connection to the database i.e name password etc. It also opens the question there too.
I keep just getting the warning message that I wrote.

you cant do an insert with a where modifier like this. change it to update ;)
UPDATE tickets SET staffResponse = '$staffResponse' WHERE id = '$id'

You are not supposed to use a WHERE clause with INSERT
$sql = "INSERT INTO tickets (staffResponse) VALUES ('$staffResponse')";
You may wish to set your tickets table up with auto increment so you dont need to insert an id if you haven't done that already.

use ON DUPLICATE UPDATE if it helps
INSERT INTO tickets (id,staffResponse) VALUES ('$id','$staffResponse')
ON DUPLICATE KEY UPDATE id=VALUES(id), staffResponse=VALUES(staffResponse)

Related

php sql not deleting row even showing success

I am trying to delete a row using a href, it's not showing the error but it's not delete the row from my table either. Not sure what i'm doing wrong.
delete.php
require_once "db.php";
$id = $_GET['id'];
$sql = "DELETE FROM books WHERE isbn = ". $id;
if (mysqli_query($db, $sql)){
echo "Success";
}else{
echo "Error";
}
main.php
if($resultSet->num_rows > 0){
while($rows = $resultSet->fetch_assoc()){
$au = $rows['author'];
$bt = $rows['booktitle'];
$rev = $rows['reserved'];
echo"<tr><td>$au</td><td>$bt</td><td>$rev</td><td><a href='delete.php?id=".$rows['isbn']."'>Delete</a></td></tr>\n";
}
echo"</table>";
}
I used a back quote (`) around the field name and it is OK now.
Example:
DELETE FROM table WHERE `field_name` = something
It seems like if you're getting the success message then the query ran successfully, which means that the database connection established OK so we can rule that out.
I think that your query is running but not finding any match on the ISBN so the record isn't getting deleted. I would try echoing out the actual SQL query just before execution so you can then copy it, connect to the database and then paste that query in to run yourself. Maybe change it to a SELECT statement first so you can see if it actually gets the row for deletion. If not then a row with that ISBN either doesn't exist or you've got something strange like an extraneous space/other weird character in the ID somewhere.

Editing a form with PHP and MySQL: Best way to obtain an ID

I have a MYSQL table with edit and delete links on each row. The edit link goes to edit_patient.php which has a form (actually, a copy of the form originally used to insert patient into the database). After few tries, the script is working although I guess it could be improved (indeed, I get a notice of "Undefined index: id" when I submit the edits. The ID is passed to the edit_patient.php file through a GET procedure. Relevant code as follows:
// Check for a valid user ID, through GET or POST:
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) { // From view_patient.php
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) ) { // Form submission.
$id = $_POST['id'];
} else { // No valid ID, kill the script.
echo '<p>Sorry, it is not possible to update patient info at this time</p>';
include ('../elements/layouts/footer.php');
exit();
}
And, after some clean up and check on submitted values:
if($action['result'] != 'error'){
// Make the query:
$q = "UPDATE `demographics`
SET lastname='$lastname', firstname='$firstname', clinic='$clinic', sex='$sex', dob='$dob', age='$age',
disease_1='$disease_1', disease_2='$disease_2', disease_3='$disease_3', address='$address', city='$city', country='$country',
zip='$zip', phone_1='$phone_1', phone_2='$phone_2', phone_3='$phone_3', email_1='$email_1', email_2='$email_2',
physician='$physician', notes='$notes'
WHERE dem_id=$id
LIMIT 1";
$r = #mysqli_query ($db_connect, $q);
if (mysqli_affected_rows($db_connect) == 1) { // If it ran OK.
// Tell the user we have edited patient data successfully
$action['result'] = 'success';
array_push($text,'Patient data have been updated on databank');
}else{
$action['result'] = 'error';
array_push($text,'Patient data could not be changed on databank. Reason: ' .
'<p>' . mysqli_error($db_connect) . '<br /><br />Query: ' . $r . '</p>');
} // End of if (empty($errors)) IF.
} // End of if (empty rows))
Ok, so far so good. Now, in order to show already inserted data, I run another query:
// Retrieve the user's information:
$q = "SELECT lastname, firstname, clinic, sex, dob, age, disease_1, disease_2, disease_3, address, city, country, zip, phone_1,
phone_2, phone_3, email_1, email_2, physician, notes
FROM `demographics`
WHERE dem_id='".$_GET['id']."'";
$r = #mysqli_query ($db_connect, $q);
if (mysqli_num_rows($r) == 1) { // Valid user ID, show the form.
// Get the user's information:
$row = mysqli_fetch_assoc ($r);
// Create the form:
Here, the critical row I do not understand is WHERE dem_id='".$_GET['id']."'"; --> If I it leave as it is, the script runs almost Ok but then I get a notice of undefined index id.
However, when I replace with WHERE dem_id=$id"; as in the first query, the script gives a fatal error of undefined variable: id.
Finally, to submit the form I use the following command:
" /> that is working Ok, but it is not working when I use:
" />
Can anyone help me to understand why, and how to correct the issue, I'd rather prefer to be able to use simply $id (I believe is straight forward and simple) but for some reason is not working as expected. Finally, I would like to be able to report in the form to be edited also data inserted with radio buttons and drop-down (select) menus. Any advice on that would be greatly appreciated !
Please make sure that your specific record has been updated after the submit button in your edit_patient.php ? If it works and after next which page is display ..? Is it is Display.php (i.e. all record display page ) ? Please be specify first and i really help you to solve your query.

MYSQL Tables Picky About Fields?

I am having issues with php and mysql once again. I have a database setup with the table users and I want to make a SELECT COUNT(*) FROM users WHERE {value1} {value2} etc...but the problem is that the 3 fields I want to compare are not in order in the table and when trying the SELECT query, the result vairable($result) is NOT returned properly(!$result). Is there a way to check multiple fields in a mysql table that have fields in between them? Here is an example of what I want to accomplish:
A mysql table called users contains these fields: a,b,c,d,e,f,g,h,i,j,k,l and m.
I want to make a SELECT COUNT(*) FROMusersWHERE a='$_SESSION[user]' and d='$_SESSION[actcode]' and j='$_SESSION[email]' but the statement in quotes is my query and it always executes the if (!$result) { error("An error has occurred in processing your request.");} statement. What am I doing wrong? On the contrary, whenever I try the statement using only one field, ex a, the code works fine! This is an annoying problem that I cannot seem to solve! I have posted the code below, also note that the error function is a custom function I made and is working perfectly normal.
<?php
include "includefunctions.php";
$result = dbConnect("program");
if (!$result){
error("The database is unable to process your request at this time. Please try again later.");
} else {
ob_start();
session_start();
if (empty($_SESSION['user']) or empty($_SESSION['password']) or empty($_SESSION['activationcode']) or empty($_SESSION['email'])){
error("This information is either corrupted or was not submited through the proper protocol. Please check the link and try again!");
} elseif ($_SESSION['password'] != "password"){
error("This information is either corrupted or was not submited through the proper protocol. Please check the link and try again!");
} else {
$sql = "SELECT * FROM `users` WHERE `username`='$_SESSION[user]' and `activationcode`='$_SESSION[activationcode]' and `email`='$_SESSION[email]'";/*DOES NOT MATTER WHAT ORDER THESE ARE IN, IT STILL DOES NOT WORK!*/
$result = mysql_query($sql);
if (!$result) {
error("A database error has occurred in processing your request. Please try again in a few moments.");/*THIS IS THE ERROR THAT WONT GO AWAY!*/
} elseif (mysql_result($result,0,0)==1){/*MUST EQUAL 1 OR ACCOUNT IS INVALID!*/
echo "Acount activated!";
} else {
error("Account not activated.");
}
}
}
ob_end_flush();
session_destroy();
?>
Try enclosing your $_SESSION variables in curly brackets {} and add or die(mysql_error()) to the end of your query -
$sql = "SELECT * FROM `users` WHERE `username`='{$_SESSION['user']}' and `activationcode`='{$_SESSION['activationcode']}' and `email`='{$_SESSION['email']}'";/*DOES NOT MATTER WHAT ORDER THESE ARE IN, IT STILL DOES NOT WORK!*/
$result = mysql_query($sql) or die(mysql_error());
store your session value in another varibles then make query , i think
it's work proper
$usr=$_SESSION['user'];
$acod=$_SESSION['activationcode'];
$eml=$_SESSION['email'];
$sql = "SELECT * FROM `users` WHERE `username`='$usr' and `activationcode`='$acod' and `email`='$eml'";
$result = mysql_query($sql) or die(mysql_error());

Delete a post based upon an id variable - different user sessions

SOLVED
I have a problem that has been tearing me apart for the last two weeks.
I want to be able to delete a post in my table based upon a given variable. Because of the different user content it's pretty difficult to delete a post that belongs to that certain user.
What I really want to know is how to get that certain ID from $rad on the admin.php to the delete query on perform_remove_time.php. Should I use GET or POST or any other method? I will have "input sanitize" with real_escape_string later on and I'm also aware of mysqli vs mysql. My code isn't pretty please bear with me.
From perform_remove_time.php
<?
$user_id = $_SESSION['user_id'];
$time_id = ($_GET['time_id']);
$sql = "DELETE FROM time WHERE time_id = '$time_id' AND user_id = '$user_id'";
$result = mysql_query($sql);
if($result) {
echo "<h3>Time deleted!</h3>";
header("location:admin.php");
} else {
echo "Something is wrong!";
}
?>
This is where the posts is fetched and displayed - admin.php
$user_id = $_SESSION['user_id'];
$time_id = ($_GET['time_id']);
$sql = "SELECT * FROM time WHERE user_id = '$user_id' ORDER BY time_id DESC";
$result = mysql_db_query("database","$sql") or die (mysql_error());
while ($rad=mysql_fetch_array($result)) {
?>
<?='Work session: '.$rad["time_id"]?> | Time on projekt: <?=$rad["hours"]?> | Delete work session
Also from admin.php further up on the page
if (!isset($_SESSION['user'])) {
header("Location:default.php");
die();
}
From my observation, your delete link in 'admin.php' would not get you to 'perform_remove_time.php' with the right GET parameter (time_id) for your delete code to work.
So i made a little modification to your delete link:
<? echo "<a href='perform_remove_time.php?time_id=".$rad['time_id']."'> | Delete work session</a>"; ?>
That modification would enable your delete link get to 'perform_remove_time.php' with the right GET parameter for it to work
Update
The code snippet from perform_remove_time.php looks fine to me, and would work as long as $time_id and $user_id contains valid values and also if your sql statement is correct. Now, from the code snippet you posted, I discovered that in perform_remove_time.php $time_id would contain nothing because there was no time_id GET parameter in your delete link code | Delete work session, the GET Parameter there is id, so I simply changed id to time_id to get things working.
new delete link code
<? echo "<a href='perform_remove_time.php?time_id=".$rad['time_id']."'> | Delete work session</a>"; ?>

Edit mysql database from "GET" index.php?id=XX

I'm currently learning PHP. I've code a simple bucketlist script with a admin panel, sessions etc just to see if I can do it.
The last page I am coding is the "edit.php" & "editone.php" I have a table which returns all data within the database "ID, Goal & Rating" my fourth column returns "EDIT" as a link which will link off to: editone.php?id=xx
editone.php currently is not a page. For the life of me I cannot figure out how I code the editone so I can grab the data and UPDATE mysql. I'm almost there just cannot piece together the puzzle.
Here's the core of my code for the edit page.
<?php
while ($query_row = mysql_fetch_array($query))
{
echo "<tr>";
echo "<td>".$query_row['id']."</td><td>". $query_row['goals']."</td><td><span class='label label-inverse'>". $query_row['rating']."</span></td><td><a href='editone.php?id=".$query_row['id']."'>Edit</a></td>";
echo "<tr>";
}
?>
Any assistance would be really appreciated.
Send all the parameters through POST method to editone page. I mean in your edit page, you are getting all the variables from database. You can show them in a form having a submit button and of type "POST". So now when someone submits, it goes to editone.php page.
Get all the variables first through $_POST method. Then write a update query.
$sql = "UPDATE tablename SET goals = '$goal', rating='$rating' WHERE id = $id";
make sure to escape your post variables as said in the comment.
This is how should be your PDO Update statement.
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$goals = 'Some goals';
$rating = 'whatever rating';
$id = 3;
// query
$sql = "UPDATE tablename
SET goals=?, rating=?
WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($goals,$rating,$id));
If I understood you correctly, what you want is a page that first displays a single row (so it can be edited) and then saves it once you're done. So you start out by writing the HTML form with no data in it.
Next, you read the ID from the query string:
<?php
$rowId = $_GET['id'];
and then query for the data:
// database connection example borrowed from Abhishek
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sql = "SELECT goals, rating FROM tablename WHERE id = ?";
$query = $conn->prepare($sql);
$query->execute(array($rowId));
$row = $query->fetch();
Now, you can use the data to populate your form. This gets you about halfway there. :-)
You'll want the actual save to be in response to a POST request, not GET. There's a long and somewhat complicated explanation on why that is, but the simplified version is that you use POST whenever you're making changes for the user, and GET when you're just reading data -- there's a bunch of browser and proxy behavior and whatnot tied to these assumptions, so it's a good idea to start doing things the right way early on.
When you process the POST request -- you can do it on the same page -- you'll have the updated form values for grabs, and you can use them to update your database:
// This can be a hidden field on the form...
$rowId = $_POST['id'];
$goals = $_POST['goals'];
$rating = $_POST['rating'];
// database connection example borrowed from Abhishek
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sql = "UPDATE tablename SET goals = ?, rating = ? WHERE id = ?";
$query = $conn->prepare($sql);
$query->execute(array($goals, $rating, $rowId));
After this, your database should be updated. To finish things off, you'll probably want to redirect back to the page to make sure the form can't be double-submitted accidentally.
I haven't covered quite everything here, a bit on purpose. It's more fun when there are some blanks to fill in. :-)
You probably want your second <tr> to be </tr>.
The most common solution is to use an html form. The input values of this form are a select with the id in query string. When a submit button is pressed to save this, make a update. But I want share with you a good and complete web 2.0 example.

Categories