Ok..I know how to get a data record from a MySql table...and I want to change data in that record and update the table.
My question is...can you actually manipulate that data from the result row, and subsequently use those in the update statement?
For example.
Let's say the table rows have 2 fields: Name, YearlyEarn.
And once a month I want to add that month's income to the YearlyEarn field for each person.
Assume we already did the Select statement for someone who's name is in $CurrentName.
And we then get their record.
$DataRow = mysql_fetch_array($result):
Can you do this:
$DataRow["YearlyEarn"] = $DataRow["YearlyEarn"] + $MonthEarn;
$query = "UPDATE EarnTable SET YearlyEarn = '$DataRow["YearlyEarn"]'
`WHERE Name = '$CurrentName'" ;
$UpdResult = mysql_query($query) or die(mysql_error());
OR.....should I put the data into intermediate fields, manipulate it..and then use those fields in the update statement?
You should use prepared statements, like PDO. The mysql_* is outdated. But if not doing so, you should consider changing your query from:
$query = "UPDATE EarnTable SET YearlyEarn = '$DataRow["YearlyEarn"]'`WHERE Name = '$CurrentName'" ;
to:
$query = "UPDATE EarnTable SET YearlyEarn = `" . $DataRow['YearlyEarn'] . "` WHERE Name = `$CurrentName`" ;
Yes, you can:
UPDATE EarnTable
SET YearlyEarn = YearlyEarn + 123
WHERE Name = 'abc'
You can use:
$query = "UPDATE EarnTable SET YearlyEarn = '$DataRow[YearlyEarn]' WHERE Name = '$CurrentName'" ;
When you're interpolating an array reference, the key is automatically quoted.
or:
$query = "UPDATE EarnTable SET YearlyEarn = '{$DataRow["YearlyEarn"]}' WHERE Name = '$CurrentName'" ;
Inside {...}, you can put any variable expression and it will be evaluated and interpolated.
Related
I've tried aLL of the below yet I can't seem to get it working
$sql="UPDATE filename SET weekday = {$_GET[wkd]} WHERE id = 2";
$sql="UPDATE filename SET weekday = '$_GET[wkd]' WHERE id = 2";
$sql="UPDATE filename SET weekday = '"{$_GET[wkd]}"' WHERE id = 2";
$sql="UPDATE filename SET weekday = '."{$_GET[wkd]}".' WHERE id = 2";
What is the correct way?
Thanks
The proper way? Assuming $link is your mysqli_connect
$wkd = mysqli_real_escape_string($link, $_GET['wkd']);
$sql = "UPDATE filename SET weekday = '" . $wkd . "' WHERE id = 2";
http://de1.php.net/manual/en/mysqli.real-escape-string.php
This:
$sql="UPDATE filename SET weekday = '" . $_GET['wkd'] . "' WHERE id = 2";
FYI, this is very bad coding practice, you should validate $_GET before add to sql.
Alright. If weekday accepts string values, then the value needs to be surrounded with quotes, ie:
$sql="UPDATE filename SET weekday = '" . $_GET['wkd'] . "' WHERE id = 2";
This is also equivalent to:
$sql="UPDATE filename SET weekday = '{$_GET['wkd']}' WHERE id = 2";
The first concatenates the string together, the second simply inserts the variable directly into the string.
For $_GET['wkd'] = "tuesday";, bot of those queries output this:
UPDATE filename SET weekday = 'tuesday' WHERE id = 2
If weekday only accepts numeric values, then there is no need to surround the value with quotes (but you still can):
$sql="UPDATE filename SET weekday = " . $_GET['wkd'] . " WHERE id = 2";
Which like the first, is equivalent to:
$sql="UPDATE filename SET weekday = {$_GET['wkd']} WHERE id = 2";
Which for $_GET['wkd'] = 1, will have both queries output:
UPDATE filename SET weekday = 1 WHERE id = 2
Point is - there is no one correct syntax, they'd all work.
However, what you really want to be doing is using pdo or mysqli with prepared statements and parameter binding, like so:
$pdo = new PDO('... connection string ... ');
$stmt = $pdo->prepare("UPDATE filename SET weekday = ? WHERE id = ?");
$stmt->execute(array($_GET['wkd'], 2));
This will bind the value of $_GET['wkd'] to the first ? in the prepared statement, and the literal 2 to the value of the second `?'. If you find yourself using lots of question marks, or losing track of the order, you can also use named placeholders like this:
$pdo = new PDO('... connection string ... ');
$stmt = $pdo->prepare("UPDATE filename SET weekday = :weekday WHERE id = :id");
$stmt->execute(array(
'weekday' => $_GET['wkd'],
'id' => 2
));
In that example i've named the placeholders the same as the fields - this isn't necessary but it is obviously more readable than naming the placeholders :asdfasdf and :lmnop (in which case the array being passed to the execute function would be ('asdfasdf' => $_GET['wkd'], 'id' => 2)
Why use the parameter binding? Its your best defense against SQL Injection
I am trying to update a record in my database with values pulled from an exploded array
$arr2 = explode(",",$_POST['hidden-tags']);
//echo $arr2[0];
//insert new rows into blog post
mysql_select_db($db, $db);
$insertq = mysql_query("UPDATE blog SET tags1 = $arr2[0],tags2 = $arr2[1],tags3 = $arr2[2], tags4 = $arr2[3], tags5 = $arr2[4] WHERE idblog = '$id' ",$dbconnet);
If I echo the values from my array one at a time it works great. Once I try to put them in the db the row turns up empty. Whats more the user may not of entered 5 items they may only have entered 1 but I dont think thats really the problem. To be honest I cant see why its currently failing at all.
I know I can save all values in one field but it will be easier as separate fieldsfor when I pull back and query later on.
if the data types of the columns are string, values must be wrap with single quotes as they are string literals. eg,
$insertq = mysql_query("UPDATE blog SET tags1 = '". $arr2[0] . "',....");
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
$insertq = mysql_query("UPDATE blog SET tags1 = $arr2[0],tags2 = $arr2[1],tags3 = $arr2[2], tags4 = $arr2[3], tags5 = $arr2[4] WHERE idblog = '$id' ",$dbconnet);
should be:
$insertq = mysql_query("UPDATE blog SET tags1 = '".$arr2[0]."',tags2 = '".$arr2[1]."',tags3 = '".$arr2[2]."', tags4 = '".$arr2[3]."', tags5 = '".$arr2[4]."' WHERE idblog = '".$id."' ,$dbconnet);
or the whole query is going to consider the variables names as part of the string
EDITED: i had the quotes inverted.
It should be like this :
$insertq = mysql_query("UPDATE blog SET tags1 = "'.$arr2[0].'",tags2 = "'.$arr2[1].'",tags3 = "'.$arr2[2].'", tags4 = "'.$arr2[3].'", tags5 = "'.$arr2[4].'" WHERE idblog = "'.$id.'" ",$dbconnet);
I think you might need to look at the datatypes of your table. If you are using varchar or text as data-types then single colon will be necessary.
$insertq = mysql_query("UPDATE blog SET tags1 =' $arr2[0]',tags2 = '$arr2[1]',tags3 = '$arr2[2]', tags4 = '$arr2[3]', tags5 = '$arr2[4]' WHERE idblog = '$id' ",$dbconnet);
Also if the idblog is integer then donot use single quotes.
hope this helps
I'm updating a MySQL table with posted PHP data.
I first gather the posted data, and put them in appropriate variables. Together with the necessary if/else checks.
Then, I only have to write my query once.
But now I have an if/else to check wether to update a specific field or not. How can I store a "do-not-update" value inside the corresponding variable?
Because otherwise I have to put an if/else check around the whole query, just for one field.
I just want to be as efficient as possible. :)
My query is as follows:
$updateTable = mysql_query("UPDATE myTable SET field1 = '$field1', field2 = '$field2'");
wherever you are get $_POST into variables, do this,
if( $field2 === 'xyz' ) { //if value is 'xyz', do not update
$sql = '';
} else
$sql = ", field2 = '$field2'";
Then in the query,
$updateTable = mysql_query("UPDATE myTable SET field1 = '$field1' $sql");
Edit: if using 1/0 (true or false),
if( $field2 == true ) { //if value is true, do not update
$sql = '';
} else
$sql = ", field2 = '$field2'";
You will need to build up your query, storing it in a PHP string, for example:
$sql = "UPDATE `table` SET ";
if ($_POST['foo']!=='') {
$sql .= " `foo`='".mysql_real_escape_string($_POST['foo'])."',";
}
if ($_POST['bar']!=='') {
$sql .= " `bar`='".mysql_real_escape_string($_POST['bar'])."',";
}
$sql = rtrim($sql,',');
$sql .= " WHERE `id`='".mysql_real_escape_string($_POST['id'])."'"
Then execute your string as the query.
If you are asking whether the field should be updated, you can do one of two things:
1) Specify a criteria that ensures field1 and field2 are only updated if the rows match the criteria. If the criteria does not match, the record will not be updated. This is the most common way.
UPDATE myTable ...
WHERE criteria1 = 1 AND criteria2 = 'Red'
2) Run a query before the UPDATE to see whether to perform an update.
I'm not exactly sure what you are asking for, but perhaps this answers your question:
$updateTable = mysql_query("
UPDATE myTable SET
field1 = IF('$field1'>'','$field1', field1),
field2 = IF('$field2'>'','$field2', field2)
");
Of course, you are opening yourself up to SQL injection with the code, as written.
Lets assume you have gathered the fields to update in an array $fields like this :
array (
'filed1' => 'value' ,
'field2' => ''value
)
Now you need to generate the query, you can do this by looping in the array:
$sql = "UPDATE mytable ";
$sql .= $fields ? "SET " : "" ;
foreach ($fields as $key=>$value) {
$sql.= $value ? "$key = '$value' , " : '' ;
}
//you need to omit the trailing ','
$sql[strlen($sql) -1 ] = "";
Tips :
Do sanitize all user input using mysqli_real_escape_string or something better than that.
Happy coding :)
I need to copy the value in a column named TEAM from one row into another row. Both rows need to have the same team name. This is my query that doesn't work:
$query = "UPDATE profiles SET team = (SELECT team FROM profiles WHERE id = '$coach_id') WHERE id = '$player_id'";
I have tried removing single quotes, removing "FROM profiles", changing value to table.value, tried to give a newdata.clan alias, and I have even tried changing the values to integers instead of parameters. Nothing works, and this is what I get:
Error: You have an error in your SQL
syntax; check the manual that
corresponds to your MySQL server
version for the right syntax to use
near 'WHERE id = '') WHERE id = ''' at
line 3
$query1 = "SELECT team FROM profiles WHERE id = '$coach_id'";
/* get the value of the first query and assign it to a variable like $team_name */
$query2 = "UPDATE profiles SET team = '$team_name' WHERE id = '$player_id'";
Also, you should surround your PHP variables in curly braces:
$query = "UPDATE profiles SET team = \"(SELECT team FROM profiles WHERE id = '{$coach_id}')\" WHERE id = '{$player_id}'";
From the MySQL manual:
"Currently, you cannot update a table
and select from the same table in a
subquery."
Source: http://dev.mysql.com/doc/refman/5.0/en/update.html
Use the method that FinalForm wrote:
<?
$coach_id = 2;
$player_id = 1;
$query1 = "SELECT team FROM profiles WHERE id = '$coach_id'";
$rs = mysql_query($query1);
if ($row = mysql_fetch_array($rs)) {
$team_name = $row['team'];
$query2 = "UPDATE profiles SET team = '$team_name' WHERE id = '$player_id'";
mysql_query($query2);
// Done, updated if there is an id = 1
} else {
// No id with id = 2
}
?>
I have a query that looks like this:
$sql = "UPDATE tbl SET amt_field='amt_field+1' WHERE username='" .mysql_real_escape_string($_SESSION['username']). "'";
mysql_select_db('db',$con);
mysql_query($sql,$con);
I want to increment the value as easily as possible.
I have tried:
"UPDATE tbl SET amt_field='amt_field+1' WHERE
"UPDATE tbl SET amt_field='amt_field' + 1 WHERE
"UPDATE tbl SET amt_field='amt_field++' WHERE
I don't get error messages, but the value in my db does not increase either.
UPDATE tbl SET amt_field = amt_field + 1 WHERE ...
If you use the single quotes ', you're telling the enclosed value to be interpreted as a string You were probably thinking about the tick marks. This is also valid:
UPDATE tbl SET `amt_field` = `amt_field` + 1 WHERE ...
This must be used when the column (or table etc.) has a reserved name.
Hello did you initialize a new session. Below worked perfectly for me.
public static function insert_search($pdo)
{
#session_start();
$ip = $_SERVER['REMOTE_ADDR'];
$username = $_SESSION['username'];
//$username = self::username();
$date = date('Y-m-d');
//Adding the total searches for the logged in user
$query = $pdo->query("UPDATE `users` SET `total_searches` = `total_searches` +1 WHERE username = '$username'");
}
/* What you could potentially do is the following.
Make sure if you're doing it the procedural way
you put #session_start(); at the top of the page */
#session_start();
$sql = "UPDATE tbl SET amt_field ='amt_field' +1 WHERE username ='" .mysql_real_escape_string($_SESSION['username']). "'";
mysql_select_db('db',$con);
mysql_query($sql,$con);