PHP Standard value is NULL and won't update - php

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

Related

How to get the value of item POST in JForm after submit?

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.

Logging profile updates in PHP

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.

PHP - Update each row in MySQL table from a web form

I populate a web form with rows of data. Some of the fields I need to be updatable so I put the value into a text field. MySQL query is:
SELECT * FROM results WHERE EventID = %s AND CompNo = %s", GetSQLValueString($colname_rsResults, "int"),GetSQLValueString($colname2_rsResults, "int"));
EventID and CompNo are passed in the URL.
Let's say the result is 50 rows. I want to be able to update the Name field (eg, make correction to the spelling), click a button and have the code update the database with any new values. It doesn't matter that most of the values will not change as this is a very infrequent operation.
I used to be able to do this in ASP but I can't seem to do in PHP.
This is the code I am using and I think it is completely wrong!!
if ((isset($_POST["JM_update"])) && ($_POST["JM_update"] == "form1")) {
$i = 0;
$j = $totalRows_rsResults;
while($i < $j)
$resultID=$_GET['ResultID'];
$vDelete=$_GET['Del'];
if ($vDelete == 1) {
$delSQL = sprintf("DELETE FROM Results WHERE ResultID=$resultID");
mysql_query($delSQL,$connFeisResults);
} else {
$name=$_GET['Name'];
$qual=$_GET['Qual'];
$updateSQL = sprintf("UPDATE results SET Name = ".$name{$i}.", Qual = ".$qual[$i]." WHERE ResultID=$resultID");
mysql_query($updateSQL, $connFeisResults);
$i++;
}
}
There is also a checkbox at the end of each row to check if I need that record deleted. That doesn't work either!!
I am using Dreamweaver CS6 and trying to adapt the update behaviours etc.
Any thoughts? Many thanks in advance.
It looks like you're missing an opening brace after your while statement.
--UPDATED
Also, check your sprintf statements -- they look wrong, and they look like they're writing the raw '$resultID' to the SQL String, instead of the value within it.
See how to do it here: http://www.talkphp.com/general/1062-securing-your-mysql-queries-sprintf.html

How do I take a php variable that has an sql query inside it and add it to an existing sql query using $db->updatePhoneNumbers()?

I am trying to make a database of Users. One user can have an indefinite number of phone numbers. So in the form I’ve created a js function that will give me new input fields and they put the information into a nestled array.
I am doing a double foreach loop to go through my array, and add SQL queries to it based on if the id already exists and just needs to be updated or if it's entirely new and needs to be inserted. I add these SQL queries to a variable $phoneSql . When I echo that variable, it does contain a valid SQL query which works if I try it directly in phpMyAdmin.
This is the foreach loop code:
$phoneSql = 'SELECT id FROM user WHERE id = '.$id.' INTO #id;';
foreach($_POST['phone'] as $key => $value) {
foreach($_POST['user'][$key] as $id => $number) {
if($id == 0 && !$number == ''){
$phoneSql .= 'INSERT INTO phone_number (id, user_id, number) VALUES (NULL, #id, "'.$number.'");';
} else if (!$number == '') {
$phoneSql .= 'UPDATE phone_numbers SET user_id = #id, number = "'.$number.'" WHERE id = '.$id.';';
}
}
}
I have one edit.php page with the form, which posts to update.php where I have the foreach loop from above and following code:
$db->updatePhoneNumber($phoneSql);
It also gets the $id from the user I’m editing at the moment. Then it gets sent to db.php and into this function:
public function updatePhoneNumbers($phoneSql) {
$ phoneSql = $ phoneSql;
$sth = $this->dbh->prepare($phoneSql);
$sth->execute();
if ($sth->execute()) {
return true;
} else {
return false;
}
}
But this is not working. Can I add a variable with sql queries into a function like that or do I have to do it some other way? I’m quite new to this so I’m not sure how to proceed. I’ve tried searching for a solution but haven’t found any. I’m thankful for any advice.
What you should be doing is using an INSERT ... ON DUPLICATE KEY UPDATE ... construct, saving you a lot of that logic.
e.g.
INSERT INTO phone_number (id, user_id, number) VALUES (...)
ON DUPLICATE KEY UPDATE user_id=VALUES(user_id), number=VALUES(number)
With this, no need to select, test, then insert/update. You just insert, and MySQL will transparently convert it into an update if a duplicate key error occurs.

Referencing the next iteration before it happens in PHP

I have a table in MySQL with "text", "date_posted", and "user". I currently query all text from user=Andy, and call those questions. All of the other text fields from other users are answers to the most recent question.
What I want is to associate those answers with the most recent question, with a loop similar to "for each text where user=Andy, find the text where user!=Andy until date>the next user=Andy (question)"
This seems awfully contrived, and I'm wondering if it can be done roughly as I've outlined, or if I can save myself some trouble in how I'm storing the data or something.
Thanks for any advice.
EDIT: I've added in the insert queries I've been using.
$url = "http://search.twitter.com/search.json?q=&ands=&phrase=&ors=&nots=RT%2C+%40&tag=andyasks&lang=all&from=amcafee&to=&ref=&near=&within=1000&units=mi&since=&until=&tude%5B%5D=%3F&rpp=50)";
$contents = file_get_contents($url);
$decode = json_decode($contents, true);
foreach($decode['results'] as $current) {
$query = "INSERT IGNORE INTO andyasks (questions, date, user) VALUES ('$current[text]','$current[created_at]','Andy')";
mysql_query($query);
}
$url2 = "http://search.twitter.com/search.json?q=&ands=&phrase=&ors=&nots=RT&tag=andyasks&lang=all&from=&to=amcafee&ref=&near=&within=15&units=mi&since=&until=&rpp=50";
$contents2 = file_get_contents($url2);
$decode2 = json_decode($contents2, true);
foreach($decode2['results'] as $current2) {
$query2 = "INSERT IGNORE INTO andyasks (questions, date, user) VALUES ('$current2[text]','$current2[created_at]','$current2[from_user]')";
mysql_query($query2);
}
And then on the SELECT side, this is where I am currently:
$results = mysql_query("SELECT * FROM andyasks");
$answers = mysql_query("SELECT * FROM andyasks WHERE 'user' != 'Andy'");
while($row = mysql_fetch_array($results))
{
if ($row['user'] == 'Andy') {
print(preg_replace($pattern, $replace, "<p>".$row["questions"]."</p>"));
}
}
while($row = mysql_fetch_array($answers))
{
print(preg_replace('/#amcafee/', '', "<p>".$row["questions"]."</p>"));
}
What you have in mind could, I believe, be done with subtle use of JOIN or nested SELECT, ORDER BY, LIMIT, etc, but, as you surmise, it would be "awfully contrived" and likely pretty slow.
As you suspect, you would save yourself a lot of trouble at SELECT time if you added a column to the table, which, for answers, has the primary key of the question they're answering (that could be easily obtained at INSERT time, since it's the latest entry with user equal Alex). Then the retrieval would be easier!
If you can alter your schema this way, but need help with the SQL, pls comment or edit your answer to indicate that and I'll be happy to follow up (similarly, I'd be happy to follow up if you're stuck with this schema and need the "awfully contrived" SQL -- I just don't know which of the two possibilities applies!-).
Edit: since the schema's changed, the INSERT could be (using form :name to indicate parameters you should bind):
INSERT IGNORE INTO andyasks
(questions, date, user, answering)
SELECT :text, :created_at, :from_user,
IF(:from_user='Andy', NULL, aa.id)
FROM andyasks AS aa
WHERE user='Andy'
ORDER BY date DESC
LIMIT 1
i.e.: use INSERT INTO ... SELECT' to do a query-within-insertion, which picks the latest post by Andy. I'm assuming you do also have a primary keyid` that's auto-increment, which is the normal arrangement of things.
Later to get all answers to a given question, you only need to select rows whose answering attribute equals that question's id.
If I understand you correctly you want something like:
$myArr = array("bob","joe","jennifer","mary");
while ($something = next($myArr)) {
if ($nextone = next($myArr)) {
//do Something
prev($myArr)
}
}
see http://jp2.php.net/next as well as the sections on prev, reset and current

Categories