php/mysql UPDATE where id = blah - php

i have a site where you can send greeting messages via php to a mysql server, and an admin login page. In the admin login page, it shows all of the messages with a status either pending, rejected or accepted with the buttons reject and accept next to each message.
Currently, whenever I hit "accept" or "reject" ALL of the messages become rejected or accepted in the database. I'd like to have the buttons call the script with a parameter which is the id of the message they're accepting/rejecting but I honestly don't know the proper syntax. Any help would be greatly appreciated.
$query = "SELECT name, location, message, status FROM messages ORDER by status ";
if ($query_run = mysql_query($query))
{
while ($query_row = mysql_fetch_assoc($query_run))
{
$name = $query_row['name'];
$location = $query_row['location'];
$message = $query_row['message'];
$status = $query_row['status'];
echo '<form method="POST" action="login.php">';
echo 'From: '.$name.'<br>Location: '.$location.'<br>Status: '.$status.'<br>Message: '.$message.'<br><br>';
?>
<input type="submit" value="Approve" name="accept">
<input type="submit" value="Reject" name="reject"></form>
<?php
if (isset($_POST['accept']))
{
echo 'Accepted!';
$updateAccept = "UPDATE messages SET status = 'a'";
mysql_query($updateAccept);
};
if (isset($_POST['reject']))
{
echo 'Rejected!';
$updateAccept = "UPDATE messages SET status = 'r'";
mysql_query($updateAccept);
}

Bind a hidden field with each submit button like this
<form method="POST">
<input type="submit" value="Whatever" name="trigger_update" />
<input type="hidden" name="id_to_be_updated" value="<?php echo 'pass your id here'; ?>" />
</form>
<?php
if(isset($_POST['trigger_update'])) {
//Do sanitization according to your needs
mysqli_query($connection, "UPDATE tbl_name SET column_name = 'whatever' WHERE id = {$_POST['id_to_be_updated']}");
}
?>

You just need to add a WHERE clause in your UPDATE statement:
$updateAccept = "UPDATE messages SET status = 'a' WHERE id = '$id'";

Related

How to update database for the checkbox selected id's and send mail to respective email addresses

I want to send welcome mail to all users whose id gets status 1. I have achieved setting status 1 to those users who are being selected via checkbox but can't figure out how to send email to all who are checked. A suggestion would be helpful.
Here is my code for the same, do let me know what else I need to add for taking 'email' into variable '$check' and send mail.
<td><input type="checkbox" name="all_check[]" <?php echo $disabled ;?> value= "<?php echo $row['id']; ?>"class="checkbox" id="status" ></td>
<input type="hidden" value="<?php echo $row['id']; ?>" name="user_id" id="user_id" >
And, code where I am setting status=1 for the selected users,
<?php
if(!empty($_POST['all_check'])) {
foreach($_POST['all_check'] as $check) {
$update_status= mysql_query("UPDATE tbl_user SET status = '1' WHERE id = $check" );
}
}
?>
Thanks in advance.
Here look at the code may it will be give you some Idea.
if(!empty($_POST['all_check'])) {
foreach($_POST['all_check'] as $check) {
$update_status= mysql_query("UPDATE tbl_user SET status = '1' WHERE id = $check" );
$query=mysql_query("Select email From tbl_user where WHERE id=$check");
if(mysql_num_rows($query)>0){
$row=mysql_fetch_array($query);
mail( $row['email'],"Welcome ","Welcome Message");
}
}
like this you have to pass two different query for updating and selecting operations.

PHP update using input value

I keep getting the following error and can not figure out what is going wrong.
Notice: Undefined index: name in C:\xampp\htdocs\FYP\resProcessing.php on line 99
The error relates to the following line:
$name = $_POST['name'];
The following below is my code:
if ($quick_check != 0){
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row['id'];
$tablenum = $row['tablenum'];
$avail = $row['avail'];
$spots .= 'You just reserved table '.$tid.'.<br />';
$spots .= 'You only have 8 minutes to finish or your reservation will expire and the table will open up to other people.<br />';
}
$availNow = $avail - $num;
$sql = "UPDATE available SET avail='$availNow' WHERE id='$id' LIMIT 1";
$query = mysqli_query($connect, $sql);
$sql = "INSERT INTO reserves(tablenumber,numseats,restime) VALUES ('$tablenum','$num',now())";
$query = mysqli_query($connect, $sql);
$reserveID = mysqli_insert_id($connect);
$spots .= '<form name="confirmform" id="confirmform" method="post" onSubmit="return false;">';
$spots .= 'Full Name: <input type="text" name="name" id="name" required autofocus placeholder="Your Name" pattern="[a-zA-Z]+{3,}" title="Please enter your full name."></br>';
// hidden field holds the table name
$spots .= '<input id="tableNumber" type="hidden" value="'.$tablenum.'">';
// hidden field holds the number of seats
$spots .= '<input id="numSeats" type="hidden" value="'.$num.'">';
// hidden field holds the reserve insert id
$spots .= '<input id="reserveID" type="hidden" value="'.$reserveID.'">';
// On submit call js function
$spots .= '<button id="confirmbtn" onClick="confirmSeats();updateInfo();">Make Reservations</button></br>';
$name = $_POST['name'];
$sql = "UPDATE available SET name='$name' WHERE id='$id' LIMIT 1";
$query = mysqli_query($connect, $sql);
$spots .= '</form>';
$spots .= '<button id="cancelbtn" onClick="cancelReserve('.$reserveID.')">Cancel Reservation</button>';
} else {
$spots .= "Sorry, someone just reserved those. Try another table";
$reserveID = "open";
}
echo "$spots|$reserveID";
exit();
}
I would really appreciate if anybody could help. Thanks!
The reason is that the POST request does not contain name parameter.
Or HTTP request type is not POST in your case.
Try $name = $_REQUEST['name']; — it would account for GET variables (and cookies) as well.
If it doesn't help, fix your client (be it HTML form, JavaScript or something else).
You may also check if POST variable is defined before trying to access it, e.g.:
if (isset($_POST['name']))
{
$name = $_POST['name'];
}
else
{
echo "Name is required";
// ...
}
Info:
It sounds like $_POST['name'] is not defined. You should verify whether or not it is and if it isn't you should have some logic to handle that case. You can use PHP isset() to check to see if $_POST['name'] "is set".
Warning:
Others may suggest using $_REQUEST, in case your variable is possibly set on $_GET as well, but you should understand how a RESTful API works before simply falling back to using $_REQUEST as there may be business logic and/or security considerations that can be affected.
Bonus:
You may also want to take a look at some PHP frameworks such as Laravel.

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: Delete || Confirm delete

I am having a problem.
I am creating a script that allows a person to select a record by it's primary ID and then delete the row by clicking a confirmation button.
This is the code with the form:
"confirmdelete.php"
<?php
include("dbinfo.php");
$sel_record = $_POST[sel_record];
//SQL statement to select info where the ID is the same as what was just passed in
$sql = "SELECT * FROM contacts WHERE id = '$sel_record'";
//execute SELECT statement to get the result
$result = mysql_query($sql, $db) or die (mysql_error());//search dat db
if (!$result){// if a problem
echo 'something has gone wrong!';
}
else{
//loop through and get dem records
while($record = mysql_fetch_array($result)){
//assign values of fields to var names
$id = $record['ID'];
$email = $record['email'];
$first = $record['first'];
$last = $record['last'];
$status = $record['status'];
$image = $record['image'];
$filename = "images/$image";
}
$pageTitle = "Delete a Monkey";
include('header.php');
echo <<<HERE
Are you sure you want to delete this record?<br/>
It will be permanently removed:</br>
<img src="$filename" />
<ul>
<li>ID: $id</li>
<li>Name: $first $last</li>
<li>E-mail: $email</li>
<li>Status: $status</li>
</ul>
<p><br/>
<form method="post" action="reallydelete.php">
<input type="hidden" name="id" value="$id">
<input type="submit" name="reallydelete" value="really truly delete"/>
<input type="button" name="cancel" value="cancel" onClick="location.href='index.php'" /></a>
</p></form>
HERE;
}//close else
//when button is clicked takes user back to index
?>
and here is the reallydelete.php code it calls upon
<?php
include ("dbinfo.php");
$id = $_POST[id];//get value from confirmdelete.php and assign to ID
$sql = "SELECT * FROM contacts WHERE id = '$id'";//where primary key is equal to $id (or what was passed in)
$result=mysql_query($sql) or die (mysql_error());
//get values from DB and display from db before deleting it
while ($row=mysql_fetch_array($result)){
$id = $row["id"];
$email = $row["email"];
$first= $row["first"];
$last = $row["last"];
$status = $row["status"];
include ("header.php");
//displays here
echo "<p>$id, $first, $last, $email, $status has been deleted permanently</p>";
}
$sql="DELETE FROM contacts WHERE id = '$id'";
//actually deletes
$result = mysql_query($sql) or die (mysql_error());
?>
The problem is that it never actually ends up going into the "while" loop
The connection is absolutely fine.
Any help would be much appreciated.
1: It should not be $_POST[id]; it should be $_POST['id'];
Try after changing this.
if it does not still work try a var_dump() to your results to see if it is returning any rows.
if it is empty or no rows than it is absolutely normal that it is not working.
and make sure id is reaching to your php page properly.
Ok as you are just starting, take care of these syntax, and later try switching to PDO or mysqli_* instead of mysql..
Two major syntax error in your code:
Parameters must be written in ''
E.g:
$_POST['id'] and not $_POST[id]
Secondly you must use the connecting dots for echoing variables:
E.g:
echo "Nane:".$nane; or echo $name; but not echo "Name: $name";
Similarly in mysql_query
E.g:
$sql = "SELECT * FROM table_name WHERE id="'.$id.'";
I hope you get it..take care of these stuff..

PHP mySQL Update page

I'm trying to make a simple product page (no login or anything like that) in php and mysql.
So far, everything shows up on my products page fine, I can delete/add just fine from my admin page. From there I'm trying to figure out how to create an edit function.
So I made a form that populates from the mysql table based on the productid for convenience (edit2.php?id=X) which then posts to edit.php and hopefully updates the database.
So far, reusing the old code isn't working, somehow I was hoping it would be that simple.
This is my add product (which works) :
<?php
session_start();
if(isset($_POST) && isset($_POST['hp']) && empty($_POST['hp'])) {
if(
isset($_SESSION['token']) &&
$_SESSION['token'] == $_POST['token']
) {
mysql_connect('localhost', 'test_admin', 'test');
mysql_select_db('test_product');
$data = array_map('mysql_real_escape_string', $_POST);
$query = "
INSERT INTO products (
product_name, price, description, image
) VALUES (
'{$data['product_name']}',
'{$data['price']}',
'{$data['description']}',
'{$data['image']}'
)
";
if(mysql_query($query)) {
echo '<p>Your information was successfully saved.</p>';
unset($_SESSION['token']);
} else {
echo '<p>There was an error storing your data, please try again later.</p>';
}
} else {
echo '<p>Your data has already been saved.</p>';
}
} else {
echo '<p>Error.<br />Please try again later.</p>';
}
?>
This is my update (which just throws out a syntax error or 'error storing your data' :
<?php
mysql_connect('localhost', 'test_admin', 'test');
mysql_select_db('lbriedis_product');
$data = array_map('mysql_real_escape_string', $_POST);
$query = "UPDATE products WHERE id = ".$pageid." (
product_name, price, description, image
) VALUES (
'{$data['product_name']}',
'{$data['price']}',
'{$data['description']}',
'{$data['image']}'
)
";
if(mysql_query($query)) {
echo '<p>Your information was successfully saved.</p>';
unset($_SESSION['token']);
} else {
echo '<p>There was an error storing your data, please try again later.</p>';
echo mysql_error(); //Used for development and testing only
}
?>
I get session errors when I attempt to use session validation probably because I start a session on my admin page (add product form is on admin.php, edit and delete are links) ?
Nevertheless, I removed the session checks for the moment as I'm struggling more so with the update part.
Also I'm not sure of the best way to pass $pageid to the update query for 'update where id = $pageid. I have a hidden field with the value (see edit form), how do I reference this correctly?
Edit form (values display correctly so where id = $pageid is working here:
<?php
$dol = "$";
$pageid = (int)$_GET['id'];
mysql_connect('localhost', 'lbriedis_admin', 'xxxxxx123');
mysql_select_db('lbriedis_product');
$result = mysql_query("SELECT * FROM products WHERE id = ".$pageid."");
if($result){
$data = mysql_fetch_assoc($result);
}
?>
<form id="inputForm" method="post" action="edit.php">
<fieldset>
<label>Pool name:</label>
<?php
echo '<input type="text" name="product_name" value="'.$data['pool_name'].'" />';
?>
<label>Price:</label> <br>
<?php
echo '$ <input type="text" name="price" value="'.$data['price'].'" />';
?> <br />
<label>Description:</label>
<?php
echo '<textarea name="description">'.$data['description'].'</textarea>';
?>
<label>Image:</label></label>
<?php
echo '<input type="text" name="image" value="'.$data['image'].'" />';
?>
<input type="hidden" name="token" value="<?php echo $_SESSION['token']; ?>" />
<input type="text" id="hp" name="hp" />
<?php
echo '$ <input type="hidden" name="$pageid" value="'.$pageid.'" />';
?>
<br>
<input type="submit" name="submit" value="Update" />
</fieldset>
</form>
your update query have incorrect sintax
$query = "UPDATE products WHERE id = ".$pageid." (
product_name, price, description, image
) VALUES (
'{$data['product_name']}',
'{$data['price']}',
'{$data['description']}',
'{$data['image']}'
)
correct sintax should be
$query="UPDATE products SET
product_name = '".$data['product_name']."',
price ='".$data['price']."',
description = '".$data['description']."',
image = '".$data['image']."'
WHERE id = '".$pageid."'
change this
name="$pageid"
to
name="pageid"
and access it like this
$data = array_map('mysql_real_escape_string', $_POST);
$query = "UPDATE products WHERE id = {$data['pageid']} (
the problem was $pageid was not accessible in edit.php. And you have assigned $pageid to name attribute , which will be different fot each product.
Change the query to this
$query="UPDATE products SET
product_name = '{$data['product_name']}',
price ='{$data['price']}',
description = '{$data['description']}',
image = '{$data['image']}'
WHERE id = '{$data['pageid']}'
replace your update query with the below:-
$query = "UPDATE products
set product_name=$data['product_name'],
price = $data['price'],
description = $data['description'] ,
image = $data['image']
where id =". $pageid ;

Categories