I am trying to write a MySQL query (in PHP) that will update a set of fieldnames contained within an (imploded) array with a set of values contained within another (imploded) array.
What I have right now is this:
$edit= mysql_query ("UPDATE tablename SET `".$EXPfields."` = '".$EXPvalues."'
WHERE ID = '$ID'");
But for $EXPfields = EXP1, ?EXP2?, ?EXP3
and $EXPvalues = Communications', 'Electronics', 'Engineering
(both imploded arrays, ? is actually a backtick: `)
I get the following error message:
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 ' ?EXP2?, ?EXP3? = 'Communications', 'Electronics', 'Engineering' ' at line 2
(again, ? is actually a backtick `)
I've been playing around with this for ages, but I can't see where I have gone wrong, help pls! Thanks!
Update queries have the following syntax:
UPDATE table
SET column = expression
WHERE predicates;
You could loop through the array of fields and create a new array containing both column names and values. For example:
$update_sql = '';
for($i = 0; $i < count($EXPfields); ++i)
{
$update_sql = "`" . $EXPfields[$i] . "` = '" . $EXPvalues[$i] . "', ";
}
$update_sql = substr($update_sql, 0, -2);
$edit = mysql_query("
UPDATE
tablename
SET
" . $update_sql . "
WHERE
ID = '$ID'");
UPDATE table
SET
field1 = expression1,
field2 = expression2,
field3 = expression3
WHERE ...
You need to do comma separated field=value pairs. eg:
$query = UPDATE ?tablename? SET ?field1?='value1', ?field2?='value2' WHERE (?field3?='value3')
Related
I'm trying to update my table named 'FA1' through a webpage.
The code used for this is:
foreach($columns as $item)
{
$sqlAtt = " update ". $class ." set ". $item ." = 'P' where `date` = '". $date ."' ";
$resultAtt = mysqli_query($GLOBALS['con'],$sqlAtt);
if (!$resultAtt) {
printf("Error: %s\n", mysqli_error($GLOBALS['con']));
exit();
}
}
$columns are the column names of the table. $class is the table name and $date has today's date.
While updating through SQL command executing space inside the database the result is,
1 row affected. (Query took 0.0002 seconds.)
update FA1 set FA14 = 'P' where `date` = '2017-05-22'
while updating through the webpage what I got is:
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 '= 'P' where `date` = '2017-05-22'' at line 1
If I output $sqlAtt :
update FA1 set FA14
= 'P' where `date` = '2017-05-22' update FA1 set FA11
= 'P' where `date` = '2017-05-22
It seems you have some type of a line break when creating your $columns array which breaks your query, I'd look into that first.
However, UPDATE lets you change multiple columns in one query in a "column=value" comma separated style. By doing it this way, your performance will increase as you'd only be running one single query as opposed to the multiple queries youre currently running (one per iteration). This is the format you should aim for:
UPDATE tbl SET
col1 = 'P',
col2 = 'P'
Do it in this manner:
foreach ($columns as $item) {
$sets[] = trim($item) ." = 'P'";
}
$query = "UPDATE $class SET " . implode(',', $sets) . " WHERE `date` = '$date' ";
$resultAtt = mysqli_query($GLOBALS['con'], $query);
if (!$resultAtt) {
printf("Error: %s\n", mysqli_error($GLOBALS['con']));
exit();
}
From the output query that you posted, it looks like there are some additional spaces in the column names. Please try to trim your column names like below,
$sqlAtt = " update ". $class ." set ". trim($item) ." = 'P' where `date` = '". $date ."' ";
To check the values in $item, try var_dump($item).
I want to update my mysql database, using php using variable method but it is not updating. I don't know what the problem is. This is my code:
$result = mysql_query("SELECT * FROM total") or die(mysql_error());
$i=$row['number'];
$n=$i+1;
$result = mysql_query("UPDATE total SET number = " . $n . " WHERE number = " . $i . "") or die(mysql_error());
How can I update my mysql database using php?
You can increment the column_value like this column_name = column_name + 1 without using SELECT.
UPDATE total SET number = number + 1
It can be just with SQL without need of select. When it is not required don't use php. What can be done in mysql should be done in mysql. It's faster.
UPDATE `total` SET number = number + 1;
Moreover, you should read the red box on mysql_* documentation. These functions are depracated and will be removed in future. Consider using MYSQLI or PDO
your query syntax is wrong, try this,
$result = mysql_query("UPDATE total SET number = '" . $n . "' WHERE number = '" . $i . "'");
The syntax fo your query is wrong it should be
UPDATE `total` SET number = number + 1;
you have done
UPDATE `total` S number = number + 1;
refer this mysql doc
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.
I have two databases($db1, $db2) with exact table structure(table1). $db2.table1 has new rows which i want to insert into $db1.table1 (i.e. if $db2 is new and $db1 is old, I want to update $db1 with new entries from $db2).
I came up with following php code, and it should work fine, but I am worried about special characters in column ids as well as values to be inserted in it.
Here's the code:
require('update_functions.php'); //contains helper functions
function arraywalk_mysql_real_escape_string(&$value, &$key, $sql_connection) {
$value = mysql_real_escape_string($value, $sql_connection);
$key = mysql_real_escape_string($key, $sql_connection);
}
$sql_connection_old = connectdb('old');
$sql_connection_new = connectdb('new');
$table = 'member'; $pkey = 'id'; //table name and primary key
$last_row_member = mysql_fetch_assoc(last_row($sql_connection_old, $table, $pkey));
//fetches last row from old db
$new_row = new_row($sql_connection_new, $pkey, $last_row_member[$pkey], $table, 'ASC LIMIT 1');
//the new_row function executes following query (after sanitizing input)
//'SELECT * FROM '.$table.' WHERE '.$pkey.'>'.$pkey_value.' ORDER BY '.$pkey.' '.$extra
while($result = mysql_fetch_assoc($new_row)) {
array_walk($result, 'arraywalk_mysql_real_escape_string', $sql_connection_old);
$update_member_query = 'INSERT INTO ' . $table . '( '
. implode(", ", array_keys($insert_vars))
. ' ) VALUES ( \''
. implode("', '", $insert_vars)
. '\' )';
}
I don't know if there will be any special characters in column names. Should I enclose them in backticks?
If yes then should I parse them using mysql_real_escape_srting()?
What about VALUES ? Should I enclose them in quotes 'value'? What if the value to be inserted is a number? what if its Date/Time?
Is there a way where I can bypass fetching data from old database into PHP variables and inserting it back to database (so above questions become irrelevant)?
Note : Even though there are two connections, I have the same SQL server serving the two $db
You can do it in SQL:
INSERT INTO db1.table1
SELECT * FROM db2.table1
WHERE db2.table1.id > (SELECT MAX(id) FROM db1.table1)
I have an UPDATE query I'd like to perform.
But there need to be 2 conditions met before we can update a quantity in the database.
First, the sessions_id() must match one of the sessionid's in the sessionid column, and second, the Description of the product must match the description of the product corresponding to the sessionid.
Here's what I have:
mysql_query(UPDATE cart
SET quantity = $q,
WHERE sessionid = "'.session_id().'"
AND description = $d') or die(mysql_error());
Now, it is giving me the following 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 sessionid="bqlbh5rdogbhmq70skhtkbvmb0" AND description=$d' at line 1
However, I have copied this update query straight from W3Schools, so it must be correct, right? Any help at all would be appreciated.
The error occurs because of the ',' sign before the WHERE statement. The correct query would be:
mysql_query( "UPDATE cart SET quantity = " . $q . " WHERE sessionid = "' . session_id( ) . '" AND description = " . $d . "" ) or die( mysql_error( ) );
remove the , (comma) after $q
the code you have pasted is badly formatted, and i doubt the code used in your app.
$sql = sprintf(
"UPDATE `cart` SET `quantity` = '%d' WHERE `sessionid` = '%s' AND `description` = '%s'",
$q,
session_id(),
$d
);
mysql_query($sql);
It should look that way:
mysql_query("UPDATE cart SET quantity = $q WHERE sessionid='" .session_id(). "' AND description = '$d'") or die(mysql_error());
Also you have problem with the single quotes here .'" AND description=$d') and $d is not parsed. This will result wrong SQL query.
Change the single quotes to double quotes or just use string append . to append the value of $d, not the literal $d
example :
$a = 5;
$b = 'a is $a'; // a is $a;
$c = "a is $a"; // a is 5