Error in SQL while updating through webpage - php

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).

Related

Data will not enter database

For some reason $query3 and $query4 will throw out this error
Couldn't enter data: You have an error in your SQL syntax; check the
manual that corresponds to your MariaDB server version for the right
syntax to use near 'WHERE job_id = '35' at line 1
I cannot see why it is doing this the query syntax seems fine.
Table structure:
https://imgur.com/a/ioOKZ
Actionpage7:
session_start();
require 'config.php';
$id = $_SESSION['login_user'];
$bidid = $_POST['bid_id'];
$jobid = $_POST['job_id'];
$bidder_id = $_POST['bidder_id'];
$bid_amount = $_POST['bid_amount'];
$query = " UPDATE bid SET status = '1' WHERE bid_id = '$bidid'";
$success = $conn->query($query);
$query2 = " UPDATE job SET accepted = '1' WHERE job_id = '$jobid'";
$success = $conn->query($query2);
$query3 = "INSERT into job (accepted_bidder) VALUES('" . $bidder_id . "') WHERE job_id = '$jobid'";
$success = $conn->query($query3);
$query4 = "INSERT into job (accepted_bid) VALUES('" . $bid_amount . "') WHERE job_id = '$jobid'";
$success = $conn->query($query4);
if(!$success) {
die("Couldn't enter data: " . $conn->error);
}
echo "Thank You For Contacting Us <br>";
header("location: myjobs.php");
$conn->close();
You can do it in one query:
UPDATE job SET
accepted = '1',
accepted_bidder = 'value',
accepted_bid = 'value'
WHERE job_id = '$jobid'
As stated in comments - your code is vulnerable to SQL injections. Refer to this topic to know more.
You have two types of queries here.
Query 1 and 2 are updates
$query = " UPDATE bid SET status = '1' WHERE bid_id = '$bidid'";
$query2 = " UPDATE job SET accepted = '1' WHERE job_id = '$jobid'";
They say UPDATE table and SET column = value WHERE condition is true. As the name implies this updates existing rows. The condition is used to limit the rows that the update is applied to. Without it every bid would have its status set to 1 and every job would be accepted. Which is probably not good.
Query 3 and 4 are inserts
$query3 = "INSERT into job (accepted_bidder) VALUES('" . $bidder_id . "') WHERE job_id = '$jobid'";
$query4 = "INSERT into job (accepted_bid) VALUES('" . $bid_amount . "') WHERE job_id = '$jobid'";
They say INSERT into table using (columns...) having VALUES(values...) WHERE condition. Again the name says it all, INSERT inserts new rows into the table. Now the question is what is the WHERE clause supposed to do?
Are you trying to limit the inserted rows to only those that match your condition? Well you are the one saying what rows to insert so you don't really need to do that. Are you trying to set values on the rows to be inserted? Well you can do that by adding more columns to the column list and their respective values to the value list. So it turns out there isn't really much point to a WHERE clause on an INSERT statement like that and in fact it's not allowed. That's what the error is trying to tell you.
As the other answer says you probably want to update an existing job and not insert a new one anyways.

Copy column values to another column in the same table

I'm trying to copy title column to keywords column in database, so the keywords will be inserted automatically from the title.
http://store2.up-00.com/2015-06/1435609110941.png
I want to add comma ', ' before each word for example.
" It's my first program "
it will turn into
" It's, my, first, program, "
This the code I wrote.
<?php
// $id =mysql_insert_id;
$select_posts = mysql_query("SELECT * FROM `posts`");
while($row = mysql_fetch_array($select_posts)){
$id = $row['post_id'];
$text = $row['post_title'];
$delim = ' \n\t,.!?:;';
$tok = strtok($text, $delim);
while ( $tok !== false){
echo $tok1 = $tok.',';
mysql_query("UPDATE `posts` SET `post_keywords` = '$tok1' WHERE `post_id` = $id ");
$tok = strtok($delim);
}
}
?>
it insert the last word in each title column , because the words is overwritten by while loop.
Please help me .
Concat the values:
... SET post_keywords = CONCAT(post_keywords, '$tok1')
and note that you're vulnerable to sql injection attacks. Just because that $tok1 value came out of a database doesn't mean it's safe to REUSE in a query...
You can do it with a single query :
UPDATE `posts` SET post_keywords = REPLACE(post_title, ' ', ',');

MySQL update query, how to skip empty values?

I've got such query:
$sql = "UPDATE test_accs SET
acc_owner = '$owner_id',
acc_policy_version = '$version',
acc_policy_last_update = '$approved',
acc_policy_next_update = '$renewed'
WHERE acc_id = '1'";
Now, all of these values on the web folmular are optional, one can set one of these values, two, or so. Now, after I submit the form, it goes in the query like that:
UPDATE test_accs SET acc_owner = '2', acc_policy_version = '1.2', acc_policy_last_update = '2012-12-19', acc_policy_next_update = '2012-12-18' WHERE acc_id = '1'
It works only when I submit all values from the form. Can you please show me how could it work even if not all the values has been sent, just for example one of them?
When I set one value (f.ex. policy version), it looks like that:
UPDATE test_accs SET acc_owner = '', acc_policy_version = '1.2', acc_policy_last_update = '', acc_policy_next_update = '' WHERE acc_id = '1'
and it isn't working.
It might be possible cause of the acc_owner table values?
#1366 - Incorrect integer value: '' for column 'acc_owner' at row 1
Thanks in advice.
Form:
echo '<td>Change owner: <select name="owner_id" onchange="showUser(this.value)" style="font-size:9px"><option value="">Select a person:</option>';
while($owners = mysql_fetch_array($owners_query)) { echo '<option value="'.$owners['id'].'">'.$owners['surname'].' '.$owners['name'].'</option></h2>'; } echo '</select></td>';
echo "<td><input name='version' style='width:50px;text-align:center' placeholder='0.0' /></td>";
echo "<td><input name='approved' class='datepicker_all' readonly='readonly' style='text-align:center' placeholder='1999-01-01' /></td>";
echo "<td><input name='renewed' class='datepicker_all' readonly='readonly' style='text-align:center' placeholder='1999-01-01' /></td>";
One way to accomplish this is to use an expression in the SQL statement that tests whether the supplied value is an empty string. If the supplied value is an empty string, then use the current value of the column as the value to assign to the column. Otherwise, assign the supplied value to the column.
In the example below, the each of the supplied values have to be include TWICE in the statement: once in the conditional test, and then again, as a possible result of the conditional test.
This statement:
UPDATE test_accs
SET acc_owner = IF('2'='',acc_owner,'2')
, acc_policy_version = IF('1.2'='',acc_policy_version,'1.2')
, acc_policy_last_update = IF('2012-12-19'='',acc_policy_last_update,'2012-12-19')
, acc_policy_next_update = IF('2012-12-18'='',acc_policy_next_update,'2012-12-18')
WHERE acc_id = '1'
is equivalent to the first UPDATE statement in the question, in that it sets the value of all four columns to the new specified value.
This statement:
UPDATE test_accs
SET acc_owner = IF(''='',acc_owner,'')
, acc_policy_version = IF('1.2'='',acc_policy_version,'1.2')
, acc_policy_last_update = IF(''='',acc_policy_last_update,'')
, acc_policy_next_update = IF(''='',acc_policy_next_update,'')
WHERE acc_id = '1'
changes ONLY the value of the acc_policy_version column, the values of the other three columns will remain unchanged.
This is not necessarily the best approach, but it is workable for some scenarios.
It's also possible to create an expression that requires each supplied value be specified in the statement one time, although I think these expressions are a little less intuitive:
SET acc_owner = COALESCE(NULLIF( '' ,''),acc_owner )
, acc_policy_version = COALESCE(NULLIF( '1.2' ,''),acc_policy_version)
That's essentially doing the same thing as the examples above.
If the supplied value is equal to '' (like it is for acc_owner in the example above), then the NULLIF expression will return a NULL. The COALESCE function essentially causes that NULL value to be skipped, and the current value of the column will remain unchanged (the current value of the column is assigned to the column.)
If the supplied value is not equal to '' (like it is for acc_policy_version in the example above), then the NULLIF expression will return the supplied value. The COALESCE function will pick up that value, and assign it to the column.
Check if acc_owner is empty and set it to zero is one option, you can't insert empty space if column is supposed to hold integer - or just don't do update unless you have int value
1:
if(strlen($acc_owner)==0){
$acc_owner=0;
}
2:
if(is_int($acc_owner)){
//update it
}
Is the value for the Integer field required? If not, then check for the GET/POST value being set, and if its empty, don't include that in your update statement.
if(isset($_GET['acc_id'])) {
$acc_id = $_GET['acc_id'];
$sql = "UPDATE test_accs SET ";
if(isset($_GET['version'])) {
$version = $_GET['version'];
$sql = $sql . "acc_policy_version = " . $version . ",";
}
if(isset($_GET['owner_id'])) {
$owner_id = $_GET['owner_id'];
$sql = $sql . "acc_owner = " . $owner_id . ",";
}
$sql = $sql .
"acc_policy_last_update = '$approved',
acc_policy_next_update = '$renewed'
WHERE acc_id = " . $acc_id;
//Execute SQL
echo "successfully updated " . $acc_id;
} else {
echo "invalid acc_id";
}
1 - Convert your $owner_id to type int
$owner_id = (int)$owner_id;
2 - Use a condition to update this field only if a value > 0
$sql = "UPDATE test_accs SET " .
($owner_id > 0 ? "acc_owner = '$owner_id', " : "") .
"acc_policy_version = '$version', " .
"acc_policy_last_update = '$approved', " .
"acc_policy_next_update = '$renewed' " .
"WHERE acc_id = '1'";
Note : Be carrefull, your variables seems not correctly securised and you have risks of mysql injections. See http://php.net/manual/fr/mysqli.real-escape-string.php.
And, maybe you should think about use the PDO php extension (http://fr2.php.net/manual/en/intro.pdo.php) for you mysql developpement or any orm ?
You should verify all values that came from a html form. Than, if you mysql field can be NULL, just set NULL to php var:
if (strlen($owner_id) == 0) {
$owner_id = NULL;
// OR
$owner_id = 0;
} else {
$owner_id = addslashes($owner_id);
}
$sql = "UPDATE test_accs SET
acc_owner = '$owner_id',
acc_policy_version = '$version',
acc_policy_last_update = '$approved',
acc_policy_next_update = '$renewed'
WHERE acc_id = '1'";
You can initialize variables holding values for optional fields with default values according to their respective data types.
Please refer the code snippet mentioned below.
$owner_id=0;
$version=0;
$approved='';
$renewed='';
if($_SERVER['REQUEST_METHOD']=='POST')
{
extract($_POST);
}
$sql = "UPDATE test_accs SET
acc_owner = '$owner_id',
acc_policy_version = '$version',
acc_policy_last_update = '$approved',
acc_policy_next_update = '$renewed'
WHERE acc_id = '1'";

MySQL UPDATE fieldnames from array with fieldvalues from array

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')

Need help with multiple WHERE clause

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

Categories