I'm not a newbie to PHP but I have encountered a [seemingly] simple problem which I cannot figure out how to resolve.
MySQL throws error that the syntax is wrong.
My Statement is this:
if($value){
$query = "UPDATE ".$preuploads." SET words = '$words_amount' WHERE id= $sn_id";
$db->sql_query( $query ) or die( mysql_error() );
}
And then $words_amount is an integer, $sn_id is also an integer. They are double checked.
The statement when printed before execution is as follows:
UPDATE SET uploads words = '250' WHERE id= 8081
// edited, with the name of table added since the problem primarily was
// with the encapsulation and the name of table just was dropped in this question
// and not in the app
however words value ('250') is tested with integer data-type as well, but no change occurs and the error lingers on.
And the error thrown is:
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 'SET words = '250' WHERE id= 8081' at line 1
If I understand your question (and preuploads is a table), then
$query = "UPDATE ".$preuploads." SET words = '$words_amount' WHERE id= $sn_id";
should be
$query = "UPDATE ".$preuploads." SET words = '".$words_amount."' WHERE id=".$sn_id;
Or, even better prepare and use bind_param,
$stmt = $mysqli->prepare("UPDATE ? SET words=? WHERE id=?");
$stmt->bind_param($preuploads, $words_amount, $snd_id);
$stmt->execute();
check your string ($words_amount) has any single quotes ' if it is then remove it by using this option on php $words_amount=string_replace("'","/'",$your_string_variable);
I have found two errors:
First, not encapsulation of the data should occur, thus:
$words_count should be left as is, not to be encapsulated with '
And the table and fields name should be encapsulated with backtick
I think your having problem with name of table. The syntax for update query is
UPDATE table_name SET words = '250' WHERE id= 8081
Related
I have been stumped with this and cannot find a working example or tutorial anywhere.
Given the following stored procedure:
SQL
delimiter $$
CREATE PROCECURE sp1(IN 'myoffset' INT, IN 'myrows'
INT)
begin
select * from t1
limit 'myoffset', 'myrows'
END$$
delimiter
I am trying to call it from PHP like so:
... establish $conn, then
PHP
// ver1:
$sql = ( "SET #p0 = $tmp1;" . " SET #p1 = $tmp2;" . "
CALL `sp1`(#p0, #p1);" );
//OR
//ver2
$sql = "SET #p0 = `$tmp1`; SET #p1 = `$tmp2`; CALL
`sp1`(#p0, #p1);";
$result = mysqli_query($conn, $sql);
Neither one works. MariaDB complains that
"Error description: 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 'SET #p1 = 25; CALL sp1(#p0, #p1)' at line 2"
Any help would be much appreciated!
What is in $tmp1?
If it is a number, then the first one should work, but the second one does not make sense because it becomes
SET #p0 = `1234`;
I assume there is not a column or table named 1234? Keep in mind that backtics are for columns, tables, and database names.
If $tmp is the string "a string", then you get
SET #p0 = a string; -- strings need to be quoted here
or
SET #p0 = `a string`; -- again that is treated as a column (etc) name.
After that, you have another problem: Do not tack multiple statements together (separated by ;); run them separately.
Finally, there is no need for #p0, etc:
$sql = "CALL `sp1`('$tmp1', '$tmp2')";
is sufficient.
Well, not quite. If the values for $tmps came from the outside world, see the dreaded "SQL Injection" problem.
Oh, and what if
$tmp1 = "Don't do this";
Then you get
$sql = "CALL `sp1`('Don't do this', '$tmp2')";
Look at the single quotes. There are 3 of them. How will this be parsed?
I am an amateur programmer creating a PHP based online portal which will update values in a MySQL database in relation to a MMO-type game, in which we are using the portal to track a total number of land tiles protected by each user.
I am working on the script which will update the table count for a given type of protected land, upon submission of an HTML form through a $_POST array.
The MySQL table (players) in question has four similar fields (along with other fields):
wild_count
city_count
nether_count
end_count
On the HTML form, the user can select a land type when submitting, and the script attempts to perform a string concatenate to complete the field, then supplies this for the placeholder in the prepared SQL query, as such:
//Set land type string
$landtype = $_POST['landtype'] . '_count';
//Process ADD request
if (!isset($_POST['negative']))
{
$action = 'ADDED'; //This is for a transaction report further down in the code
try
{
$sql = 'UPDATE players SET
`:landtype` = `:landtype` + :tiles WHERE id = :id';
$query = $link->prepare($sql);
$query->bindValue(':landtype', $landtype);
$query->bindValue(':tiles', $_POST['tiles']);
$query->bindValue(':id', $_POST['player']);
$query->execute();
}
catch (PDOException $e)
{
$error = 'Error updating land count: ' . $e->getMessage();
include './includes/error.inc.php';
exit();
}
...more code follows...
When trying to POST my form using the following code, I get the following error:
Error updating land count: SQLSTATE[42S22]: Column not found: 1054 Unknown column ''city_count'' in 'field list'
(I had selected city in my form example).
I've tried the same code, except without the backticks around the placeholder :landtype (i.e. $sql = 'UPDATE players SET :landtype = :landtype + :tiles WHERE id = :id';) and I get a different error:
Error updating land count: SQLSTATE[42000]: Syntax error or access violation: 1064 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 ''city_count' = 'city_count' + '300' WHERE id = '1'' at line 2
I'm not certain how to proceed. Does the attempt at setting the field value by creating a concatenated string break it here?
Don't try to bind column name like it's a value:
$sql = 'UPDATE players SET `'.$landtype.'` = `'.$landtype.'` + :tiles WHERE id = :id';
Can PHP PDO Statements accept the table or column name as parameter?
I am trying set variable to NULL:
$q = NULL.",";
$q .= 'abc';
and save in to database:
mysql_query("INSERT INTO table (col_a, col_b) VALUES (".$q.")")
But this generates error message:
INSERT INTO table (col_a, col_b) VALUES (,'abc')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 ','abc')' at line 2
How to save NULL into database from variable?
you can get rid of the column where you want its value to be null, eg
$q = 'abc';
mysql_query("INSERT INTO table (col_b) VALUES ($q)")
or if value is dynamic, the only problem with your current code is that you haven't include NULL in your string,
$q = "NULL,";
$q .= "'abc'";
mysql_query("INSERT INTO table (col_a, col_b) VALUES ($q)")
the your code is vulnerable with SQL Injection, please read the article below to learn how to prevent from it.
How can I prevent SQL injection in PHP?
You're concatenating NULL and trying to parse it, which in the statement, would actually read:
, abc
Instead of the expected
NULL, abc
So just write a literal "NULL" in your statement.
Pass the literal, unquoted string inside the query:
$q = "NULL,";
$q = "NULL,";
$q .= '"abc"';
Gives you NULL,"abc" which you can include in your query.
The error you posted couldn't have come from the code in the question.. where did the quotes around abc come from? You need to enclose it in quotes inside the quotes for the php variable for them to show up in the SQL too.
I have a Mysql query as follows
$query = "UPDATE student_database SET fname='$fname',mname='$mname',lname='$lname',dob='$dob',Age='$age',Sex='$sex',Caste='$caste',dept='$dept', SSC%=$ssc , HSC%=$hsc, ATKTs=$atkt, Last_sem%=$lastsem, Aggregate%=$agg WHERE student_id=$id ; ";
Some column names have a '%' sign in it. Mysql throws the following error when I execute it
Cannot execute.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 '%=79.6 , HSC%=81.83, ATKTs=5, Last_sem%=52.35, Aggregate%=53.6 WHERE student_id=' at line 1
Can't figure out the problem I have tried "\" , "#" , "%%" as escape characters but can't figure it out.
Wrap it in backticks to tell SQL that it's a column, does this work?
$query = "UPDATE student_database SET fname='$fname',mname='$mname',lname='$lname',dob='$dob',Age='$age',Sex='$sex',Caste='$caste',dept='$dept', `SSC%`=$ssc , `HSC%`=$hsc, ATKTs=$atkt, `Last_sem%`=$lastsem, `Aggregate%`=$agg WHERE student_id=$id ; ";
Try wrapping the column names in backticks, e.g
`SSC%`=$ssc
How can I increment an int in a cell of a MySQL database? I know that auto-increment is no use because I never want to add a new row, just update an existing one. I'm currently using this (POST var used for clarify, is verified in the real code):
$columnToUpdate = 'type'.$_POST['voteid'];
$query = "UPDATE myTable $columnToUpdate = $columnToUpdate+1 WHERE id=1;";
if(!mysql_query($query)) {
echo json_encode(array('success' => false, 'message' => 'Update failed: '.mysql_error()));
exit;
}
In the database I have 6 fields, id, type1, type2, type3, type4, type5, and a single row with id set to 1. The intention is to recieve a number (1-5), and build a reference to the correct column before updating the field. That results in Update failed: 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 '=type4+1 WHERE id=1' at line 1, so I guess it's not getting the field value out properly before it increments.
Once this is working I'm also going to need to decrement a field in the same way, unless its value is 0. So for bonus points, can I do all this in one query or would it be better to split it up?
I think you've missed the keyword 'SET' from your query - try
$query = "UPDATE myTable SET $columnToUpdate = $columnToUpdate+1 WHERE id=1;";
Edit:
To do the "decrement unless it's zero" you could use something like:
UPDATE myTable SET $columnToUpdate =
CASE $columnToUpdate
WHEN 0 THEN 0
ELSE $columnToUpdate - 1
END CASE
WHERE id=1;`
For bonus points, to decrement:
$query = "UPDATE myTable SET '$columnToUpdate' = '$columnToUpdate'-1 WHERE id=1 AND '$columnToUpdate' > 0";
Besides the injection issues, it seems as if your workflow may need some work. Are you sure you want to choose the column that will be updated based on POST variable? It seems like you would specify the column and use the variable to find the record that needs to be updated:
IE:
"UPDATE myTable SET votes=votes+1 WHERE id=$post_variable;"
Again you should send the variable as a parameterized query to protect yourself from SQL injection.