Updating a single record Via ID = ID - php

I've ran into a wall at the moment, This code brings up a table with a button on the end of each record. Once pressed this then does a function to UPDATE the Health record by -5.
This works great for the job but it effects all rows, I've tried to get it to only touched one record via the ID but no luck! if you can help that would be great!
the php
$sql="SELECT `id` , `FirstName` , `Health` FROM ajax_demo WHERE `id` = `id` LIMIT 0 , 30";
$result = mysql_query($sql);
if(isset($_REQUEST['submit']))
{
counterminus();
}
function counterminus()
{
$cmeter = $cmeter - 1;
$id = $_POST["id"];
$FirstName = $_POST["FirstName"];
mysql_query("UPDATE ajax_demo SET `Health` = `Health` - `Damage` WHERE id = {$id}");
Header("location:oo_test.php");
}
This is the php / form
<?php
echo
"<table border='1'>
<tr>
<th>id</th>
<th>Firstname</th>
<th>health</th>
</tr>";
while($row = mysql_fetch_row($result)) {
echo '<tr>';
foreach($row as $cell) {
echo "\n<td>$cell</td>";
}
echo '<td><form id="theForm" action="" method="POST" >
<input type="submit" name="submit" id="submit" value="Attack" />
<input type="hidden" name="'.$row[1].'" /></form></td></tr>';
echo "\n\n";
}?>

This is vunerable to attack through the $_POST['id'] variable. Use mysql_real_escape_string, or better, prepared queries through PDO or MySQLi, anyway this is orthogonal to the issue you are having, it's just a good idea to be aware of it.
You're never actually submitting a HTML form field with the name id. In addition, in your HTML, $row will be NULL outside of your while loop, so will be undefined in the first place. This will mean that the name of your hidden field will be blank, and that your SQL is saying UPDATE WHERE id=, which is invalid and will cause an error.
To fix, you need to submit a form field with the name "id" such that $_POST['id'] actually contains a value.

Why did you write {id} instead of $id ?
Plus your code is totally unsafe and could be easily altered and hacked.
You should try PDO instead of mysql_query which is also depreciated.
http://php.net/PDO

Related

delete row php&mysql dynamique link

I want to make a link to delete a record from database using dynamic links with php however i couldn't figure it out
this is my code :
<?php
$query = "SELECT * FROM posts ";
$result = mysqli_query($connect, $query);
?>
<table>
<tr style="background: #afafaf;">
<th>Id</th>
<th>Title</th>
<th>Action</th>
</tr>
<?php
while($rows = mysqli_fetch_assoc($result)){
echo "<tr>";
echo "<td class=\"center\">".$rows['id']."</td>";
echo "<td>".$rows['title']."</td>";
echo "<td> delete</td>";
echo "</tr>";
}
?>
</table>
the output link would be like .../delete.php?id=X
can anyone help me write the code for delete.php ?
Have the below code in your page. This first checks if $_GET['id'] is set. It will only run if it is, that way you don't get Undefined Index error.
<?php
if (isset($_GET['id'])) {
$deleteId = htmlspecialchars($_GET['id'], ENT_QUOTES);
$delete = "DELETE FROM `posts` WHERE `id` = " . $deleteId;
}
?>
I also used htmlspecialchars to sanitize the user input. You could run some validation using ctype_digit to ensure that the input is actually an integer.
I suggest using prepared statement in MySQLi to prevent SQL injection.
Edit 1
Example with ctype_digit. This checks if the id is set and if it is a number, technically you could just use ctype_digit because if id is empty then ctype will return false as var_dump(ctype_digit("")); will return false, with that logic in mind, the value must be set for ctype_digit to work and it must be an integer.
<?php
if (ctype_digit($_GET['id'])) {
$deleteId = htmlspecialchars($_GET['id'], ENT_QUOTES);
$delete = "DELETE FROM `posts` WHERE `id` = " . $deleteId;
}
?>
That would be something like this:
$deleteId = $_GET['id'];
$sql = "DELETE FROM posts WHERE id = ".$deleteId;
Remember to escape your variables before sending them off to the MySQL server.

How to submit the multiple rows form data with a single submit in PHP

Here is my code.
I made a form with multiple rows which will be updated in a single submit.
I searched in forums, but didn't find the exact answer.
<form method='POST' action='demo24.php'>
<table width="500px" height="500px">
<tr><th>SETNAME</th><th>POST</th></tr>
<?php
$query = "SELECT name,setid FROM `set` LIMIT 0 ,10";
$result = mysql_query($query) or die(mysql_error()."[".$query."]");
while($row = mysql_fetch_array($result))
{
$output .='<tr><td><input type="text" value="'.$row['name'].' '.$row['setid'].'" name="name'.$row['setid'].'">'.$row['name'].'</td><td><input type="checkbox" value="'.$row['setid'].'" name="setid"></td></tr>';
}
echo $output;
?>
</td><td><input type='submit' value='submit' name='submit'/></td></tr>
</table>
</form>
Note that you can use something like name[] in multiple input fields to send an array to the server:
<input type="text" name="row[]" />
<input type="text" name="row[]" />
On the server side $_POST['row'] will look like this:
Array (
[0] => first_input,
[1] => second_input
)
You can do this for all fields (id, row, etc.) and then loop through $_POST['id'] etc. to get all entries back together. Be sure to validate enough, i.e. make sure that those fields are indeed arrays, that all are of the same size, etc.
The MySQL family of PHP is deprecated and support thereof will disappear. Please look into PDO or MySQLi to execute SQL code instead.
If your form method as 'post' then you can use this code :
if(isset($_POST['submit']))
{
$query = "SELECT name,setid FROM `set` LIMIT 0 ,10";
$result = mysql_query($query) or die(mysql_error()."[".$query."]");
while($row = mysql_fetch_array($result))
{
$id = $row['setid'];
$name = $_POST['name'.$id];
//here will be you update code. set value will be $name and update where setid = $id
}
}

Set amounts in database using php + form

In my database users have a balance, im trying to set up a form that allows them to transfer amounts to each other. So for the from user it would - out of their current balance and update it to the new balance ( existing - amount transferred ) and for the receiver it would update ( existing + amount received ).
Heres my code below but its not updating any of the information:
<?php
if (isset($_POST['submit'])) {
$fromuser = $_POST['fromuser'];
$touser = $_POST['touser'];
$amount = $_POST['amount'];
$balanceto = mysql_query("SELECT `money` FROM `users` WHERE username = '$touser'");
$res1 = mysql_fetch_array($balanceto);
$balancefrom = mysql_query("SELECT `money` FROM `users` WHERE username = '$fromuser'");
$res2 = mysql_fetch_array($balancefrom);
$newmoney1 = ($res1['money'] + $_POST['amount']);
$newmoney2 = ($res2['money'] - $_POST['amount']);
$result1 = mysql_query("UPDATE `users` SET `money`='$newmoney1' WHERE username = '$touser'");
$result2 = mysql_query("UPDATE `users` SET `money`='$newmoney2' WHERE username = '$fromuser'");
}
?>
<form class="reg-page" role="form" action="" method="post">
<center>
Please note: Transfering funds is done at your own risk, please make sure you transfer the funds to the right person.<br><br>
<?php
$query = "SELECT username FROM users";
$result = mysql_query($query) or die(mysql_error());
$dropdown = "<div class='row'><div class='col-sm-6'><label>Transfer $ To<span class='color-red'> *</span></label><select name='touser' class='form-control margin-bottom-20'>";
while($row = mysql_fetch_assoc($result)) {
$dropdown .= "\r\n<option value='{$row['username']}'>{$row['username']}</option>";
}
$dropdown .= "\r\n</select></div><div class='col-sm-6'>
<label>Amount $<span class='color-red'> *</span></label>
<input type='text' name='amount' class='form-control margin-bottom-20'>
</div></div>";
echo $dropdown;
?>
<input type="hidden" value="<?php echo $user_data['username']; ?>" name="fromuser">
<button type="submit" class="btn-u">Transfer</button>
</center>
</form>
All help much appreciated.
$_POST does not contain submit because you never put a NAME tag on the submit button.
Instead of:
<button type="submit" class="btn-u">Transfer</button>
You need:
<button type="submit" class="btn-u" name="submit">Transfer</button>
See here:
How do I post button value to PHP?
On further reflection it's probably a good idea to talk about some of the problems here, let's start with this one:
$balanceto = mysql_query("SELECT `money` FROM `users` WHERE username = '$touser'");
$res1 = mysql_fetch_array($balanceto);
$balancefrom = mysql_query("SELECT `money` FROM `users` WHERE username = '$fromuser'");
$res2 = mysql_fetch_array($balancefrom);
This is duplicated code, you can move this into a function to avoid copying and pasting, which is good practice, and you can use that function in other places in your code when you need to get the balance. Formatting the structure correctly helps in the event that your table changes, and you need to update the SQL. Without this in a single place, you are going to climb all over your code to find all the changes and update them.
<input type="hidden" value="<?php echo $user_data['username']; ?>" name="fromuser">
This is very bad practice, as it makes it easy for someone to slip an extra variable into the header and submit whatever user they want to your code, transferring money out of any other account that they want. Since this page already has access to this variable:
$user_data['username']
You should be using this in the IF statement at the top, instead of submitting it along with the form.
<input type='text' name='amount' class='form-control margin-bottom-20'>
This is another problem. You are asking for an amount, but creating a text field. A better example of this would be:
<input type='number' name='amount' class='form-control margin-bottom-20'>
Again though, these are easily modifiable post values, you have to make sure to check again on the server to make sure you didn't get fooled:
if(!(isNumeric($_POST['amount']) || $_POST['amount'] == 0 || $_POST['amount'] == ''))
The code above checks to make sure you have a numeric value, and that it is not 0 or blank, both of which would be invalid inputs. If either of those values is submitted, then it errors out and sends the user back to the form without processing the update.
Later on in your code, you start a PHP Tag to create the drop down:
<?php
$query = "SELECT username FROM users";
$result = mysql_query($query) or die(mysql_error());
$dropdown = "<div class='row'><div class='col-sm-6'><label>Transfer $ To<span class='color-red'> *</span></label><select name='touser' class='form-control margin-bottom-20'>";
Assigning all of this to the $dropdown variable is completely wasted if you aren't going to use that drop down again (and it seems you are not). I can see that you wrapped it in PHP so you can loop over the options to print them out, but you can do that just as easily with a smaller PHP tag with a loop inside it, like this:
<select name='touser' class='form-control margin-bottom-20'>
<option value="null">Not Selected</option>
<?php
// Loop over all our usernames...
while($row = mysql_fetch_assoc($result)) {
// If we're not the current user...
if($row['username'] != $user_data['username']) {
// Add a drop down option!
echo "<option value='" . $row['username'] . "'>" . $row['username'] . "</option>";
}
}
?>
</select>
Note that this option ALSO includes a default "null" value for the select menu, and filters out the existing user (you can't transfer money to yourself, at least in this example). The null value is necessary because without it your code would automatically select the first user on the drop down list.
This would be my implementation of the same set of code here:
<?php
// If our submit is set...
if (isset($_POST['submit'])) {
// Get the balance for the from user
$fromBalance = getBalance($user_data['username']);
// Get the balance for the to user
$toBalance = getBalance($_POST['touser']);
// Get our new amounts, but don't do anything yet!
$newmoney1 = $toBalance + $_POST['amount'];
$newmoney2 = $fromBalance - $_POST['amount'];
// Check to make sure we have a valid amount
if(!(isNumeric($_POST['amount']) || $_POST['amount'] == 0 || $_POST['amount'] == '')) {
// Or error out!
echo 'ERROR: Bad amount Specified!';
// Check to make sure we have two valid users
} elseif($user_data['username'] == $_POST['touser']) {
// Or error out!
echo 'ERROR: Cannot transfer money to yourself!';
// Check to make sure sufficient funds are available
} elseif($newmoney2 < 0) {
// Or error out!
echo 'ERROR: Insufficient funds!';
// Check for default user selection...
} elseif($_POST['touser'] === 'null') {
// Or Error Out
echo 'ERROR: No username selected!';
// Otherwise we are good...
} else {
// So we call our update functions.
updateMoney($user_data['username'], $newmoney2);
updateMoney($_POST['touser'], $newmoney1);
// Send a success message
echo 'Transfer completed successfully, thank you!<br /><br />';
}
}
/** updateMoney()
*
* This function will take a user name and an amount and update their balance.
* Created to re-use code instead of copy and paste.
*
* #arg $user string
* #arg $amount integer
*/
function updateMoney($user, $amount) {
// Update our database table for this user with this amount
$result1 = mysql_query("UPDATE `users` SET `money`='$amount' WHERE username = '$user'");
}
/** getBalance()
*
* This function will return a balance for a given username.
* Created to re-use code instead of copy and paste.
*
* #arg $user string
* #return $amount integer
*/
function getBalance($user) {
// Execute query to get the result
$result1 = mysql_query("UPDATE `users` SET `money`='$amount' WHERE username = '$user'");
// Assign the result to a value
$res1 = mysql_fetch_array($balanceto);
// Return only the value we care about
return $res1['money'];
}
// Set our query for getting usernames from the DB
$query = "SELECT username FROM users";
// Get the usernames!
$result = mysql_query($query) or die(mysql_error());
?>
<form class="reg-page" role="form" action="" method="post">
<center>
Please note: Transfering funds is done at your own risk, please make sure you transfer the funds to the right person.
<br>
<br>
<div class='row'>
<div class='col-sm-6'>
<label>Transfer $ To<span class='color-red'> *</span></label>
<select name='touser' class='form-control margin-bottom-20'>
<option value="null">Not Selected</option>
<?php
// Loop over all our usernames...
while($row = mysql_fetch_assoc($result)) {
// If we're not the current user...
if($row['username'] != $user_data['username']) {
// Add a drop down option!
echo "<option value='" . $row['username'] . "'>" . $row['username'] . "</option>";
}
}
?>
</select>
</div>
<div class='col-sm-6'>
<label>Amount $<span class='color-red'> *</span></label>
<input type='number' name='amount' class='form-control margin-bottom-20'>
</div>
</div>
<button type="submit" class="btn-u" name="submit">Transfer</button>
</center>
</form>
But you STILL need to go fix the code so that you are NOT using MySQL and switch to MySQLi or PDO so that you can do prepared statements and actually protect yourself from MySQL injection attacks.
See here for more details:
https://wikis.oracle.com/display/mysql/Converting+to+MySQLi
You have posting the form with nameless button and trying to access via $_POST['submit']
<button type="submit" class="btn-u">Transfer</button>
name is missing. Add and try
<button type="submit" name="submit" class="btn-u">Transfer</button>
I think the button is missing tag 'name'. Try add this on your button:
<button type="submit" class="btn-u" name='submit'>Transfer</button>
To optimize your script I suggest do this:
if (isset($_POST['submit'])) {
$fromuser = $_POST['fromuser'];
$touser = $_POST['touser'];
$amount = $_POST['amount'];
$result1 = mysql_query("UPDATE `users` SET `money`= `money` + '$amount' WHERE username = '$touser'");
$result2 = mysql_query("UPDATE `users` SET `money`= `money` - '$amount' WHERE username = '$fromuser'");
}
So, you will eliminate two steps of processing and two hits on database.
start transaction
INSERT INTO power (sender, receiver, amount) VALUES ('$sender', '$receiver', '$amount')
UPDATE users SET power=power-$amount WHERE user_id='$sender'
UPDATE users SET power=power+$amount WHERE user_id='$receiver'
Submit button missing the name tag. use Transfer
Nothing glaringly wrong with the code, I'm assuming this is fake money.
Probably a malformed sql statement, try echoing the attempted sql before hand.
make sure all the queries work for a test example.

PHP Updating row in record to yes instead of no but it still shows even though code is for where X = no only

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'];

Trying to use query variable and form data to change tables in database

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'>";
.....

Categories