I have a edit profile page in my social media website.
When users click submit on the form. I run an update query to obviously update the users field in the database.
How can I optimize this scenario to include the logging of which particular fields are updated?
So for e.g.
One scenario could be:
Chris updated his profile picture.
Another scenario would be:
Chris updated his profile, inc:
Email
Username
Address
Address 2
Can anyone offer a solution to this?
I feel there is no need for code as all it is, is an update query.
Thanks
When writing out the form, save the current states in the $_SESSION-variable. The check the submitted forms and compare with the data in the $_SESSION-variable. Then only make an update on the forms that have changed.
if($_SESSION['name'] != $myform['name']) { $sql[] = "name = '{$myform['name']}'"; }
if($_SESSION['img'] != $myform['img']) { $sql[] = "img = '{$myform['img']}'"; }
$sqlstring = "UPDATE mytable SET " . implode(",",$sql);
// run the sql
EDIT: to implement logging:
// populate the variables (name, img) from the db/session with the highest revision number.
// ie SELECT * FROM mytable where userid = $userid ORDER BY revision DESC LIMIT 1
$revision = $_SESSION['revision'] + 1;
$sql = "INSERT INTO mytable SET img = '$img', name='$name', revision='$revision'";
Did you put all that information in a $_SESSION or something? If so, you can unset the session and declare it again, with the new info.
You can use custom setters / getters to do this. Check the code below.
You can also add additional checks to make sure the values have changed, or use magic methods to make things more dynamic.
class MyObject
{
protected $modifiedFields = array();
public function setField($value) {
if (!in_array('field', $this->modifiedFields)) {
$this->modifiedFields[] = 'field';
}
}
}
If you have the modified fields, you can just run the update query to contain only these fields.
Related
So I have a backoffice called biblioteca.php where I have some requests and I can validate them trough a button called "Validar". That button redirects to a page like this: http://localhost/pap_16gpsi21/validacao.php?nproposta=87 where I can fill the form and submit.
What I want is to validate the request related to that url.
Example:
I've a request and his number is 90, I click on "Validar", then redirects me to a page like this http://localhost/pap_16gpsi21/validacao.php?nproposta=90, I fill the form and click submit. Then it updates the request number 90 in the database ($updateEstado = "UPDATE propostas SET validacao='Validado'";)
biblioteca.php
$selectProp = "SELECT nproposta, prioridade,disponibilidade,validacao,
autorizacao,aquisicao,registo,biblioteca,docente
FROM propostas
ORDER BY nproposta DESC";
$resultado = mysqli_query($ligaBD, $selectProp);
if (mysqli_num_rows($resultado) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($resultado)) {
<td><a class="btn btn-default" href="./validacao.php?nproposta=<?= $row["nproposta"] ?>">Validar</a></td>
valida.php
// gets nproposta from propostas
$npropostaLinha = "SELECT nproposta FROM propostas";
$resultado=mysqli_query($ligaBD, $npropostaLinha);
$nproposta = "";
printf($npropostaLinha);
$row = mysqli_fetch_array($resultado,MYSQLI_NUM);
printf("==> ");
print_r($row[0]);
$nproposta = $row[0];
$insertValidacao = "INSERT INTO validacao
(nproposta,nome_validacao,nif_validacao,
email_validacao,preco_validacao)
VALUES ($nproposta,'$nome_validacao','$nif_validacao',
'$email_validacao','$preco_validacao')";
$updateEstado = "UPDATE propostas SET validacao='Validado'";
$resultado = mysqli_query($ligaBD, $insertValidacao);
$resultado = mysqli_query($ligaBD, $updateEstado);
The problem is that if I have 3 requests (90,91,92) and I decide to validate just the number 91 it updates the first which is the number 90.
Also I know this isnt the safest method but this is just a test.
Hopefully, I explained explicitly. Sorry for any grammatical mistakes. Thank you
You need a couple of changes in your code as there are a few logical mistakes that I think you want to avoid.
You need to target a variable to specify from your SELECT that you desire a specific proposta;
You need, when updating, to specify which row, otherwise you will update every single record in your DB;
For such, go to your valida.php and add the following:
At the very top, check you have the variable ready
if (!isset($_POST['nproposta']) || empty($_POST['nproposta'])) {
//Do here what you desire to stop the script from running. Redirect back if you wish;
echo "No proposal id was found";
die;
}
$nPropostaID = $_POST['nproposta'];
Once you have your ID to target the row in your DB, update your query to consider it;
UPDATE propostas SET validacao='Validado' WHERE nproposta = $nPropostaID
Go to your form view and add below line within the form
<input type='hidden' value="<?php echo $_GET['nproposta']?>" name="nproposta">
NOTE: Because you mentioned you are aware of the SQL injections and this is a test I won't go with those, but always good to remember to be careful with them :) My proposal for the queries is just to get you going and in no way good for a script!
I am currently constructing a component in Joomla and I have to get the values of the form field that user submitted. After that, I have to insert the values into database. The problem is that I just able to insert the $inventory_id but I can't get the value of the form field. Thank you.
<?php
$input = JFactory::getApplication()->input;
$formData = new JRegistry($input->get('jform', '', 'array'));
$name = $formData->get('inventory_name', 'test');
$leadtime = $formData->get('leadtime', null);
$max_lead = $formData->get('max_lead', null);
$daily_usage = $formData->get('daily_usage', null);
$max_usage = $formData->get('max_usage', null);
//formula to calculate reorder point
$lead_time_demand = $leadtime * $daily_usage;
$safety_stock = ($max_usage * $max_lead) - ($daily_usage * $leadtime);
$reorder_point = $lead_time_demand + $safety_stock;
if (empty($this->item->id)){ //For new added item
$inventory_id = $row['AUTO_INCREMENT'];
$sql_new = "INSERT INTO wer_reorder_point_list (inventory_id, inventory_name, reorder_point)
VALUES ('$inventory_id', '$name', '$reorder_point');";
mysqli_query($con,$sql_new);
}
?>
You never declare $row in this code, so what is $inventory_id = $row['AUTO_INCREMENT']; supposed to do?
If your database is configured to autoincrement inventory_id, then you don't need that column in the insert statement. So you could do this:
$sql_new = "INSERT INTO wer_reorder_point_list (inventory_name, reorder_point)
VALUES ('$name', '$reorder_point');";
and it will automatically fill that column with the next integer.
By the way, you should also use prepared statements, especially since you have user input, which could be a security problem.
You don't insert an autoincremented id directly using the form data, you let the database take care of that. If you tried to insert it you could easily end up with a race condition given that in a web application such as Joomla there could be many users attempting to insert new lines with the same id at the same time. This is why your form does not contain an inventory_id value.
If you want to pass a hidden ( from the user) value to the POST you need to include a hidden field with that value in your form. However, as stated in the first paragraph, you would not use that for a unique ID.
I have a page that brings up a users information and the fields can be modified and updated through a form. Except I'm having some issues with having my form update the database. When I change the update query by hardcoding it works perfectly fine. Except when I pass the value through POST it doesn't work at all.
if (isset($_POST['new']))
{
$result1 = pg_query($db,
"UPDATE supplies.user SET
id = '$_POST[id_updated]',
name = '$_POST[name_updated]',
department = '$_POST[department_updated]',
email = '$_POST[email_updated]',
access = '$_POST[access_updated]'
where id = '$_POST[id_updated]'");
if (!$result1)
{
echo "Update failed!!";
} else
{
echo "Update successful;";
}
I did a vardump as an example early to see the values coming through and got the appropriate values but I'm surprised that I get an error that the update fails since technically the values are the same just not being hardcoded..
UPDATE supplies.user SET name = 'Drake Bell', department = 'bobdole',
email = 'blah#blah.com', access = 'N' where id = 1
I also based the form on this link here for guidance since I couldn't find much about PostGres Online
Guide
Try dumping the query after the interpolation should have happened and see what query you're sending to postgres.
Better yet, use a prepared statement and you don't have to do variable interpolation at all!
Do not EVER use data coming from external sources to build an SQL query without proper escaping and/or checking. You're opening the door to SQL injections.
You should use PDO, or at the very least pg_query_params instead of pg_query (did you not see the big red box in the manual page of pg_query?):
$result1 = pg_query($db,
"UPDATE supplies.user SET
id = $1,
name = $2,
department = $3,
email = $4,
access = $5
WHERE id = $6",
array(
$_POST[id_updated],
$_POST[name_updated],
$_POST[department_updated],
$_POST[email_updated],
$_POST[access_updated],
$_POST[id_updated]));
Also, when something goes wrong, log the error (pg_last_error()).
By the way, UPDATE whatever SET id = some_id WHERE id = some_id is either not really useful or not what you want to do.
in my database i have some tables, i have one for the image path, and one for the image width, they have a standard value of NULL, and a null value (the checkbox and the dropdown box is both NULL)
When i enter a new path or width it does not change, but my other does, this is my code.
require_once("../Packages/Connection.php");
$text = mysql_real_escape_string($_POST["articleText"]);
$method = $_POST['method'];
$articleId = $_POST['articleId'];
$imagePath = $_POST['imagePath'];
$imageWidth = $_POST['imageWidth'];
if($method == "update")
{
mysql_query("UPDATE Articles SET text='$text' WHERE id='$articleId'") or die(mysql_error());
}
elseif($method == "delete")
{
mysql_query("DELETE FROM Articles WHERE id=".$articleId."");
};
if($_POST["articleGroup"]=="News")
{
mysql_query("INSERT INTO Articles VALUES(NULL,'".$_POST["articleGroup"]."','".time()."','".$text."', NULL, NULL, NULL)") or die(mysql_error());
}
else
{
mysql_query("INSERT INTO Articles VALUES (NULL,'".$_POST["articleGroup"]."','NULL','".$text."','NULL','".$imagePath."','".$imageWidth."')") or die(mysql_error());
}
Thanks in advance
There's no UPDATE for the other two fields.
UPDATE Articles SET text='$text' WHERE id='$articleId'
should include updating (add to the SET clause) the other fields.
As others have said, you should sanitize other fields as well (and probably move from the deprecated extension - update PHP if necessary) otherwise any sanitizing you are doing is pointless as an attacked can use the other fields
you need to add the other two attributes to your update command. It would be helpful to know your mysql table schema, but guessing the column names, I get:
mysql_query("UPDATE Articles SET text='".$text."', width='".$imageWidth."', path='".$imageWidth."' WHERE id='".$articleId."'");
Also, as the commenters pointed out, you really need to sanitize your input values. Any REQUEST variable needs to be checked/sanitized. You can read more about this here
I already have an script where it will allow a user whom is logged in to comment on other users. One field for the usercommenting "men_id" and another field for the user being commented on commented_men_id. Well I save it in a comment table and to pull it I make a while I make a select to get the comment of men_id while getting the comment I do another while loop inside the while loop to get the user name and id to return it in the comment. Now the next step is to let other user to comment on top of the comment that is already there. I was wondering if I have to make another table or just create another table to get the comments on another comments. I was also wondering in terms of the php script will I have to create another while loop inside the second while loop to pull the subcomments?
So far I have the next structure
$sql1 = "SELECT id, mem_id, commented_id, comment
FROM comments
WHERE commented_id = '$id'";
while($row=msql_fetch_array($sql)) {
$id_coment = $row['id'];
$mem_id = $row['mem_id'];
$comment = $row['comment'];
$sql_member_data = msql_query("SELECT id, member_name FROM users WHERE id ='$id_coment'");
while($row2=msql_fetchj_array($sql_member_data)) {
$user_id =$row2['id'];
$user_name =$row2['member_name'];
echo '<div>'.$user_name.'</div>';
echo '<div>'.$comment.'</div>';
}
}
I advise might not be the best code but it is posting the comment, Now how can I get a comment within the comment generated by this script.
Thank you guys.
If you truly want a something like Facebook's commenting system, you are going to have to do a lot more than that. I made my own little system and it's nicely styled with some really awesome jQuery effects.
Here's what you are going to need
Section to get all your comments (which you have -- check for syntax errors)
Form and script to post your comments
And you will probally need to use jQuery and AJAX for the commenting and some more jQuery to auto-refresh like facebook does.
That's my take on it. No one else hate on me for this, just trying to give some input on it.
<?php
// Connect to database here
// Search and start loop to get all comments
$sql_comments = mysql_query("SELECT * FROM comments WHERE type='main'");
while($rows_comment=mysql_fetch_array($sql_comments)){
// Get comment information
$main_comment_id = "".$rows_comment['id']."";
$main_comment_mem_id = "".$rows_comment['mem_id']."";
$main_commented_id = "".$rows_comment['commented_id']."";
$main_comment = "".$rows_comment['comment']."";
// Get user information
$sql_member_data = msql_query("SELECT * FROM users WHERE id ='$main_comment_mem_id'");
while($row2=msql_fetchj_array($sql_member_data)) {
$user_id = "".$row2['id']."";
$user_name = "".$row2['member_name']."";
}
// Display comment
echo "<b>$user_name</b><br>$main_comment";
// Search for any sub-comments
$sql_subcomments = "SELECT * FROM comments WHERE sub_commented_id='$main_comment_id' AND type='sub'";
while($row_subcomment=msql_fetchj_array($sql_subcomments)) {
// Get sub comment information
$subcomment_id = "".$row_subcomment['id']."";
$sucomment_mem_id = "".$row_subcomment['mem_id']."";
$subcomment_comment = "".$row_subcomment['comment']."";
// Get sub commenter information
$sql_member_data_sub = msql_query("SELECT * FROM users WHERE id ='$subcomment_mem_id'");
while($row2_sub=msql_fetchj_array($sql_member_data_sub)) {
$user_id_sub = "".$row2_sub['id']."";
$user_name_sub = "".$row2_sub['member_name']."";
}
// Echo sub comment
echo "<div style='margin-left: 20px;'><b>$user_name_sub</b><br>$subcomment_comment</div>";
}
}
?>