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
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 build my query like this:
foreach($ids as $key => $idi) {
$ids[$key] = "'" . $idi . "'";
};
$ids_imploded = implode(", ", $ids);
$sql = "SELECT record_id, email FROM `actions_attendees` WHERE `action_id` IN (" . $ids_imploded . ") AND `backup` = 1 ORDER BY `timestamp` ASC LIMIT " . count($ids) . ";";
$result = mysqli_query($con, $sql);
Where $ids is just array of few numbers (so the $ids_imploded = "'132', '165'").
When I run the generated query in phpMyAdmin, I get what I want. When I run it from PHP, it returns just object with nulls. Why?
I doesn't work neither if I remove the escaping loop.
EDIT: generated query is echoed like
SELECT record_id, email FROM `actions_attendees` WHERE `action_id` IN ('1614', '1615') AND `backup` = 1 ORDER BY `timestamp` ASC LIMIT 2;
The problem could be that you are querying the wrong database, try select a db first, try executing this before the query :
mysql_select_db('yourdb');
Is the result of your query true ? Check your connection object, it seems like you are not on the right database.
It appears that the query was indeed working even in PHP, but later when I was processing the results, intellisense tricked me and I was using mysql_fetch_assoc instead of mysqli_fetch_assoc...
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
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')
I have 2 variables that contain a a string of text. I need to update them in the table, but out of the 20 + different variations of about 5 different scripts that I've tried out, it just doesn't update!
I can update using this:
mysql_query("UPDATE cart SET quantity = $q WHERE sessionid='" .session_id(). "' AND description = '$d'") or die(mysql_error());
but I am now working on a different page, where I need a slightly different update query. Which is:
UPDATE cart SET quantity = $q WHERE sessionid = $somethin AND description = $desc
And for that I have:
mysql_query("UPDATE cart SET quantity = $q WHERE sessionid = $o AND description = $d") or die(mysql_error());
(I have tried many variations with different quotes in different places for the above query, but nothing works!)
I have also tried:
$conn = mysql_connect("my01..com", "dbase", "2354ret345ert");
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'UPDATE cart
SET quantity="'.$q.'"
WHERE sessionid="$o" AND description = "$d"';
mysql_select_db('mysql_94569_dbase');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
That last one doesn't display any errors, in fact, it even tells me that it has successfully updated! But it's lying. It hasn't updated anything.
Can someone please help me out here, I am really getting sick of reading tutorial after turorial and never learning anything because they all have differnt syntax and none of it seems to work.
What I would like to do is:
UPDATE table SET columnname = $this WHERE thiscolumn = $this AND thiscolumn = $that
$this = $var
Thank you
You are missing the quotes in description and SessionID, do it like this:
mysql_query("UPDATE cart
SET quantity = '".$q."'
WHERE sessionid = '".$o."' AND description = '".$d."'");
In order to save you confusion, I would recommend start using concatenation operator (eg 'UPDATE '.$table .' SET ...')instead of writing variables directly to strings (eg. "UPDATE $table SET ...").
in this case your query would look like:
mysql_query("UPDATE cart SET quantity = ".$q." WHERE sessionid='" .session_id(). "' AND description = '".$d."'") or die(mysql_error());
This might help you to find problems with quotes and parenthesis quicker
BAD:
I had this query in php:
$query = "UPDATE users SET username = ".$nume." WHERE id = ".$userID;
That did this SQL:
UPDATE users SET username = elev WHERE id = 2
GOOD: For it to work I changed it to this php:
$query = "UPDATE users SET username = ".'"'.$nume.'"'." WHERE id = ".$userID;
That did this SQL:
UPDATE users SET username = "elev" WHERE id = 2